"use strict";
var ZuzuBrowser = (() => {
  var __getOwnPropNames = Object.getOwnPropertyNames;
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
    get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
  }) : x)(function(x) {
    if (typeof require !== "undefined") return require.apply(this, arguments);
    throw Error('Dynamic require of "' + x + '" is not supported');
  });
  var __commonJS = (cb, mod) => function __require2() {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  };

  // modules/javascript.js
  var require_javascript = __commonJS({
    "modules/javascript.js"(exports2, module2) {
      "use strict";
      function isPlainObject2(value) {
        return value != null && typeof value === "object" && !Array.isArray(value) && Object.prototype.toString.call(value) === "[object Object]";
      }
      function decorateDict(value) {
        if (!isPlainObject2(value)) {
          return value;
        }
        for (const [name2, fn2] of [
          ["length", function _length() {
            return Object.keys(this).length;
          }],
          ["count", function _count() {
            return Object.keys(this).length;
          }],
          ["empty", function _empty() {
            return Object.keys(this).length === 0 ? 1 : 0;
          }],
          ["keys", function _keys() {
            return Object.keys(this);
          }],
          ["values", function _values() {
            return Object.keys(this).map((key) => this[key]);
          }],
          ["has", function _has(key) {
            return Object.prototype.hasOwnProperty.call(this, String(key)) ? 1 : 0;
          }],
          ["contains", function _contains(key) {
            return this.has(key);
          }],
          ["exists", function _exists(key) {
            return this.has(key);
          }],
          ["defined", function _defined(key) {
            return this.has(key) && this[String(key)] != null ? 1 : 0;
          }],
          ["get", function _get(key, fallback = null) {
            return this.has(key) ? this[String(key)] : fallback;
          }],
          ["add", function _add(key, inner) {
            this[String(key)] = inner;
            return this;
          }],
          ["set", function _set(key, inner) {
            return this.add(key, inner);
          }],
          ["to_Iterator", function _to_iterator() {
            return this.keys()[Symbol.iterator]();
          }]
        ]) {
          if (!Object.prototype.hasOwnProperty.call(value, name2)) {
            Object.defineProperty(value, name2, {
              value: fn2,
              enumerable: false,
              configurable: true,
              writable: true
            });
          }
        }
        for (const key of Object.keys(value)) {
          value[key] = convertSafeValue(value[key]);
        }
        return value;
      }
      function convertSafeValue(value) {
        if (value == null) {
          return null;
        }
        if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
          return value;
        }
        if (Array.isArray(value)) {
          for (let i = 0; i < value.length; i++) {
            value[i] = convertSafeValue(value[i]);
          }
          return value;
        }
        if (isPlainObject2(value)) {
          return decorateDict(value);
        }
        return value;
      }
      function isSafeValue(value, seen = /* @__PURE__ */ new Set()) {
        if (value == null) {
          return true;
        }
        if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
          return true;
        }
        if (typeof value === "bigint" || typeof value === "function" || typeof value === "symbol") {
          return false;
        }
        if (seen.has(value)) {
          return false;
        }
        seen.add(value);
        try {
          if (Array.isArray(value)) {
            return value.every((item) => isSafeValue(item, seen));
          }
          if (isPlainObject2(value)) {
            return Object.values(value).every((item) => isSafeValue(item, seen));
          }
          return false;
        } finally {
          seen.delete(value);
        }
      }
      function jsonValue(value, seen = /* @__PURE__ */ new Set()) {
        if (value == null) {
          return null;
        }
        if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
          return value;
        }
        if (typeof value === "bigint") {
          return value.toString();
        }
        if (typeof value === "function" || typeof value === "symbol") {
          return null;
        }
        if (seen.has(value)) {
          throw new Error("Exception: circular JavaScript value cannot be encoded as JSON");
        }
        seen.add(value);
        try {
          if (Array.isArray(value)) {
            return value.map((item) => jsonValue(item, seen));
          }
          if (isPlainObject2(value)) {
            const out = {};
            for (const [key, inner] of Object.entries(value)) {
              out[key] = jsonValue(inner, seen);
            }
            return out;
          }
          if (typeof value.toJSON === "function") {
            return jsonValue(value.toJSON(), seen);
          }
          return String(value);
        } finally {
          seen.delete(value);
        }
      }
      function evaluate(code, thisValue) {
        const src = String(code ?? "");
        return Function(
          "code",
          "return (function () { return eval( code ); }).call( this );"
        ).call(thisValue, src);
      }
      var JSResult = class _JSResult {
        constructor(value) {
          this._value = value;
        }
        eval(code) {
          return new _JSResult(evaluate(code, this._value));
        }
        isSafe() {
          return isSafeValue(this._value) ? 1 : 0;
        }
        value() {
          if (!this.isSafe()) {
            throw new Error("Exception: JavaScript value is not safely representable in Zuzu");
          }
          return convertSafeValue(this._value);
        }
        toJSON() {
          return JSON.stringify(jsonValue(this._value));
        }
        to_String() {
          if (this._value == null) {
            return "null";
          }
          return String(this._value);
        }
      };
      var JS = {
        eval(code) {
          return new JSResult(evaluate(code, globalThis));
        },
        version() {
          return String(globalThis.process && globalThis.process.version ? globalThis.process.version : "javascript");
        }
      };
      module2.exports = {
        JS,
        JSResult
      };
    }
  });

  // lib/collections.js
  var require_collections = __commonJS({
    "lib/collections.js"(exports2, module2) {
      "use strict";
      function runtimeHelpers() {
        return require_runtime_helpers();
      }
      function retainCollectionValue(collection, value) {
        return runtimeHelpers().retainCollectionValue(collection, value);
      }
      function releaseCollectionValue(collection, value) {
        return runtimeHelpers().releaseCollectionValue(collection, value);
      }
      function releaseCollectionValues(collection) {
        return runtimeHelpers().releaseCollectionValues(collection);
      }
      function makeArray(values) {
        return runtimeHelpers().makeArray(values);
      }
      function makeSet(values) {
        return runtimeHelpers().makeSet(values);
      }
      function operatorString(value) {
        return runtimeHelpers().operatorString(value);
      }
      function stringSortComparator(a, b) {
        return runtimeHelpers().stringSortComparator(a, b);
      }
      var ZuzuBag = class _ZuzuBag {
        constructor(...items) {
          let values;
          if (items.length === 0) {
            this.items = [];
            return;
          }
          if (items.length > 1) {
            values = items;
          } else {
            const first = items[0];
            if (Array.isArray(first)) {
              values = first;
            } else if (first != null && typeof first !== "string" && typeof first[Symbol.iterator] === "function") {
              values = Array.from(first);
            } else {
              values = [first];
            }
          }
          this.items = values.map((value) => retainCollectionValue(this, value));
        }
        length() {
          return this.items.length;
        }
        count(value) {
          if (arguments.length === 0) {
            return this.items.length;
          }
          return this.items.filter((item) => item === value).length;
        }
        empty() {
          return this.items.length === 0 ? 1 : 0;
        }
        is_empty() {
          return this.empty();
        }
        contains(value) {
          return this.items.includes(value) ? 1 : 0;
        }
        add(...values) {
          this.items.push(...values.map((value) => retainCollectionValue(this, value)));
          return this;
        }
        push(...values) {
          return this.add(...values);
        }
        remove(value) {
          for (let idx = this.items.length - 1; idx >= 0; idx--) {
            if (this.items[idx] === value) {
              releaseCollectionValue(this, this.items[idx]);
              this.items.splice(idx, 1);
            }
          }
          return this;
        }
        remove_first(value) {
          const idx = this.items.indexOf(value);
          if (idx >= 0) {
            releaseCollectionValue(this, this.items[idx]);
            this.items.splice(idx, 1);
          }
          return this;
        }
        remove_if(fn2) {
          this.items = this.items.filter((item) => {
            if (fn2(item)) {
              releaseCollectionValue(this, item);
              return false;
            }
            return true;
          });
          return this;
        }
        map(fn2) {
          return new _ZuzuBag(this.items.map(fn2));
        }
        grep(fn2) {
          return new _ZuzuBag(this.items.filter(fn2));
        }
        any(fn2) {
          return this.items.some(fn2) ? 1 : 0;
        }
        all(fn2) {
          return this.items.every(fn2) ? 1 : 0;
        }
        first(fn2) {
          for (const item of this.items) {
            if (fn2(item)) {
              return item;
            }
          }
          return null;
        }
        for_each_value(fn2) {
          this.items.forEach(fn2);
          return this;
        }
        to_Array() {
          return makeArray(this.items);
        }
        to_Set() {
          return makeSet(this.items);
        }
        to_Iterator() {
          return this.items[Symbol.iterator]();
        }
        copy() {
          return new _ZuzuBag(this.items);
        }
        uniq() {
          return new _ZuzuBag([...new Set(this.items)]);
        }
        sum() {
          return this.items.reduce((a, b) => Number(a) + Number(b), 0);
        }
        product() {
          return this.items.reduce((a, b) => Number(a) * Number(b), 1);
        }
        sort(fn2) {
          return this.to_Array().sort(fn2);
        }
        sortstr() {
          return this.to_Array().sort(stringSortComparator);
        }
        sortnum() {
          return this.to_Array().map((item) => Number(item)).sort((a, b) => a - b);
        }
        clear() {
          releaseCollectionValues(this);
          this.items = [];
          return this;
        }
        [Symbol.iterator]() {
          return this.items[Symbol.iterator]();
        }
      };
      var Pair = class {
        constructor(options = {}) {
          this.pair = options.pair || [];
        }
        key() {
          return this.pair[0] ?? null;
        }
        value() {
          return this.pair[1] ?? null;
        }
      };
      var PairList = class _PairList {
        constructor(...options) {
          this.list = [];
          if (options.length > 1) {
            this.list = options.filter((entry) => Array.isArray(entry) && entry.length >= 2).map(
              (entry) => [String(entry[0]), retainCollectionValue(this, entry[1])]
            );
            return;
          }
          const first = options.length === 0 ? {} : options[0];
          if (Array.isArray(first)) {
            const entries = Array.isArray(first[0]) ? first : [first];
            this.list = entries.filter((entry) => Array.isArray(entry) && entry.length >= 2).map(
              (entry) => [String(entry[0]), retainCollectionValue(this, entry[1])]
            );
            return;
          }
          if (Array.isArray(first.list)) {
            this.list = first.list.filter((entry) => Array.isArray(entry) && entry.length >= 2).map(
              (entry) => [String(entry[0]), retainCollectionValue(this, entry[1])]
            );
          }
          return new Proxy(this, {
            get(target, prop, receiver) {
              if (typeof prop === "symbol" || prop in target) {
                return Reflect.get(target, prop, receiver);
              }
              if (typeof prop === "string") {
                return target.get(prop, null);
              }
              return void 0;
            },
            set(target, prop, value, receiver) {
              if (typeof prop === "symbol" || prop in target) {
                return Reflect.set(target, prop, value, receiver);
              }
              if (typeof prop === "string") {
                const idx = target.list.findIndex((pair) => pair[0] === String(prop));
                if (idx >= 0) {
                  releaseCollectionValue(target, target.list[idx][1]);
                  target.list[idx][1] = retainCollectionValue(target, value);
                } else {
                  target.list.push([
                    String(prop),
                    retainCollectionValue(target, value)
                  ]);
                }
                return true;
              }
              return false;
            }
          });
        }
        length() {
          return this.list.length;
        }
        count() {
          return this.list.length;
        }
        empty() {
          return this.list.length === 0 ? 1 : 0;
        }
        is_empty() {
          return this.empty();
        }
        keys() {
          return this.list.map((pair) => pair[0]);
        }
        values() {
          return this.list.map((pair) => pair[1]);
        }
        enumerate() {
          return this.to_Array();
        }
        has(key) {
          return this.list.some((pair) => pair[0] === String(key)) ? 1 : 0;
        }
        exists(key) {
          return this.has(key);
        }
        defined(key) {
          const found = this.list.find((pair) => pair[0] === String(key));
          return found ? found[1] == null ? 0 : 1 : 0;
        }
        get(key, fallback = null) {
          const found = this.list.find((pair) => pair[0] === String(key));
          return found ? found[1] : fallback;
        }
        get_all(key) {
          return this.list.filter((pair) => pair[0] === String(key)).map((pair) => pair[1]);
        }
        all(key) {
          return this.get_all(key);
        }
        add(key, value) {
          this.list.push([String(key), retainCollectionValue(this, value)]);
          return this;
        }
        set(key, value) {
          return this.add(key, value);
        }
        kv() {
          const out = [];
          for (const [key, value] of this.list) {
            out.push(key, value);
          }
          return out;
        }
        sorted_keys() {
          return this.keys().slice().sort();
        }
        remove(key) {
          if (typeof key === "function") {
            this.list = this.list.filter((pair) => {
              if (key(new Pair({ pair: pair.slice() }))) {
                releaseCollectionValue(this, pair[1]);
                return false;
              }
              return true;
            });
            return this;
          }
          const normalized = String(key);
          this.list = this.list.filter((pair) => {
            if (pair[0] === normalized) {
              releaseCollectionValue(this, pair[1]);
              return false;
            }
            return true;
          });
          return this;
        }
        for_each_key(fn2) {
          for (const key of this.keys()) {
            fn2(key);
          }
          return this;
        }
        for_each_value(fn2) {
          for (const value of this.values()) {
            fn2(value);
          }
          return this;
        }
        for_each_pair(fn2) {
          for (const pair of this.list) {
            fn2(new Pair({ pair: pair.slice() }));
          }
          return this;
        }
        to_Array() {
          return this.list.map((pair) => new Pair({ pair: pair.slice() }));
        }
        to_Iterator() {
          return this.keys()[Symbol.iterator]();
        }
        copy() {
          return new _PairList({ list: this.list.map(([k, v]) => [k, v]) });
        }
        clear() {
          releaseCollectionValues(this);
          this.list = [];
          return this;
        }
      };
      Object.defineProperty(PairList.prototype, "__zuzu_builtin_type", {
        value: "PairList",
        enumerable: false,
        configurable: true
      });
      function withArrayMethods() {
        const nativeJoin = Array.prototype.join;
        const define = (name2, fn2) => {
          if (!Object.prototype.hasOwnProperty.call(Array.prototype, name2)) {
            const desc = /* @__PURE__ */ Object.create(null);
            desc.value = fn2;
            desc.enumerable = false;
            Object.defineProperty(Array.prototype, name2, desc);
          }
        };
        if (Array.prototype.join.__zuzu_array_join !== true) {
          const desc = /* @__PURE__ */ Object.create(null);
          desc.value = function _join(separator, fallback) {
            const hasFallback = arguments.length > 1;
            let fallbackString;
            const sep = operatorString(separator);
            const out = [];
            for (const value of this) {
              try {
                out.push(operatorString(value));
              } catch (err) {
                if (!hasFallback) {
                  throw err;
                }
                if (typeof fallback === "function") {
                  out.push(operatorString(fallback(value)));
                } else {
                  if (fallbackString === void 0) {
                    fallbackString = operatorString(fallback);
                  }
                  out.push(fallbackString);
                }
              }
            }
            return nativeJoin.call(out, sep);
          };
          desc.value.__zuzu_array_join = true;
          desc.enumerable = false;
          desc.configurable = true;
          desc.writable = true;
          Object.defineProperty(Array.prototype, "join", desc);
        }
        define("count", function _count() {
          return this.length;
        });
        define("empty", function _empty() {
          return this.length === 0 ? 1 : 0;
        });
        define("is_empty", function _is_empty() {
          return this.empty();
        });
        define("append", function _append(...values) {
          this.push(...values.map((value) => retainCollectionValue(this, value)));
          return this;
        });
        define("add", function _add(...values) {
          this.push(...values.map((value) => retainCollectionValue(this, value)));
          return this;
        });
        define("prepend", function _prepend(...values) {
          this.unshift(...values.map((value) => retainCollectionValue(this, value)));
          return this;
        });
        define("get", function _get(idx, fallback = null) {
          return idx >= 0 && idx < this.length ? this[idx] : fallback;
        });
        define("set", function _set(idx, value) {
          releaseCollectionValue(this, this[idx]);
          this[idx] = retainCollectionValue(this, value);
          return this;
        });
        define("grep", function _grep(fn2) {
          return this.filter(fn2);
        });
        define("any", function _any(fn2) {
          return this.some(fn2) ? 1 : 0;
        });
        define("all", function _all(fn2) {
          return this.every(fn2) ? 1 : 0;
        });
        define("first", function _first(fn2) {
          return this.find(fn2) ?? null;
        });
        define("remove", function _remove(fn2) {
          for (let i = this.length - 1; i >= 0; i--) {
            if (fn2(this[i])) {
              releaseCollectionValue(this, this[i]);
              this.splice(i, 1);
            }
          }
          return this;
        });
        define("contains", function _contains(value) {
          return this.includes(value) ? 1 : 0;
        });
        define("first_index", function _first_index(fn2) {
          return this.findIndex(fn2);
        });
        define("reductions", function _reductions(fn2) {
          const out = [];
          for (const item of this) {
            if (out.length === 0) {
              out.push(item);
            } else {
              out.push(fn2(out[out.length - 1], item));
            }
          }
          return out;
        });
        define("head", function _head(n) {
          return this.slice(0, n);
        });
        define("tail", function _tail(n) {
          return this.slice(n - 1);
        });
        define("sum", function _sum() {
          return this.reduce((a, b) => Number(a) + Number(b), 0);
        });
        define("product", function _product() {
          return this.reduce((a, b) => Number(a) * Number(b), 1);
        });
        define("shuffle", function _shuffle() {
          return this.slice();
        });
        define("sample", function _sample(n) {
          return this.slice(0, n);
        });
        define("for_each_value", function _for_each_value(fn2) {
          this.forEach(fn2);
          return this;
        });
        define("sortstr", function _sortstr() {
          return this.slice().sort(stringSortComparator);
        });
        define(
          "sortnum",
          function _sortnum() {
            return this.map((item) => Number(item)).sort((a, b) => a - b);
          }
        );
        define("to_Array", function _to_array() {
          return makeArray(this);
        });
        define("to_Set", function _to_set() {
          return makeSet(this);
        });
        define("to_Bag", function _to_bag() {
          return new ZuzuBag(this);
        });
        define("to_Iterator", function _to_iterator() {
          return this[Symbol.iterator]();
        });
        define("copy", function _copy() {
          return makeArray(this);
        });
        define("clear", function _clear() {
          releaseCollectionValues(this);
          this.splice(0, this.length);
          return this;
        });
      }
      module2.exports = {
        ZuzuBag,
        Pair,
        PairList,
        withArrayMethods
      };
    }
  });

  // lib/runtime-helpers.js
  var require_runtime_helpers = __commonJS({
    "lib/runtime-helpers.js"(exports2, module2) {
      "use strict";
      var { ZuzuBag, Pair, PairList, withArrayMethods } = require_collections();
      var ZuzuBinary = class _ZuzuBinary {
        constructor(bytes = []) {
          if (bytes instanceof _ZuzuBinary) {
            this.bytes = new Uint8Array(bytes.bytes);
            return;
          }
          if (bytes instanceof Uint8Array) {
            this.bytes = new Uint8Array(bytes);
            return;
          }
          if (Array.isArray(bytes)) {
            this.bytes = Uint8Array.from(bytes.map((item) => Number(item) & 255));
            return;
          }
          this.bytes = new Uint8Array(0);
        }
        get length() {
          return this.bytes.length;
        }
        byteLength() {
          return this.bytes.length;
        }
        isAscii() {
          for (const byte of this.bytes) {
            if (byte > 127) {
              return 0;
            }
          }
          return 1;
        }
        slice(start, end) {
          return new this.constructor(this.bytes.slice(start, end));
        }
        at(index) {
          let idx = Number(index);
          if (idx < 0) {
            idx = this.bytes.length + idx;
          }
          if (idx < 0 || idx >= this.bytes.length) {
            return null;
          }
          return new this.constructor([this.bytes[idx]]);
        }
        to_String() {
          let out = "";
          for (const byte of this.bytes) {
            out += String.fromCharCode(byte);
          }
          return out;
        }
        toString() {
          return this.to_String();
        }
        [Symbol.toPrimitive](hint) {
          if (hint === "number") {
            return NaN;
          }
          return this.to_String();
        }
      };
      var BinaryString2 = class extends ZuzuBinary {
        constructor(bytes) {
          super(bytes);
        }
      };
      var weakStates = /* @__PURE__ */ new WeakMap();
      var retainedCollectionValues = /* @__PURE__ */ new WeakMap();
      var ZuzuWeakCell = class {
        constructor(value) {
          this.value = value;
        }
        deref() {
          const value = this.value;
          if (!isWeakableValue(value)) {
            return value;
          }
          const state = weakStates.get(value);
          return state && state.strong > 0 ? value : null;
        }
      };
      function isWeakCell(value) {
        return value instanceof ZuzuWeakCell;
      }
      function isWeakableValue(value) {
        if (value == null) {
          return false;
        }
        if (typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
          return false;
        }
        const tag = Object.prototype.toString.call(value);
        if (tag === "[object Boolean]" || tag === "[object Number]" || tag === "[object String]" || tag === "[object RegExp]") {
          return false;
        }
        if (value instanceof ZuzuBinary) {
          return false;
        }
        return typeof value === "object" || typeof value === "function";
      }
      function resolveWeakValue(value) {
        return isWeakCell(value) ? value.deref() : value;
      }
      function makeWeakValue(value) {
        return new ZuzuWeakCell(resolveWeakValue(value));
      }
      function retainValue(value) {
        const resolved = resolveWeakValue(value);
        if (isWeakableValue(resolved)) {
          const state = weakStates.get(resolved) || { strong: 0 };
          state.strong += 1;
          weakStates.set(resolved, state);
        }
        return resolved;
      }
      function strongReferenceCount(value) {
        const resolved = resolveWeakValue(value);
        if (!isWeakableValue(resolved)) {
          return 0;
        }
        const state = weakStates.get(resolved);
        return state ? state.strong : 0;
      }
      function retainedValuesForCollection(collection, create = false) {
        const resolved = resolveWeakValue(collection);
        if (!isWeakableValue(resolved)) {
          return null;
        }
        let values = retainedCollectionValues.get(resolved);
        if (!values && create) {
          values = [];
          retainedCollectionValues.set(resolved, values);
        }
        return values || null;
      }
      function retainCollectionValue(collection, value) {
        if (isWeakCell(value)) {
          return value;
        }
        const retained = retainValue(value);
        const values = retainedValuesForCollection(collection, true);
        if (values) {
          values.push(retained);
        }
        return retained;
      }
      function releaseCollectionValue(collection, value) {
        const values = retainedValuesForCollection(collection);
        if (!values) {
          return false;
        }
        const idx = values.indexOf(value);
        if (idx < 0) {
          return false;
        }
        values.splice(idx, 1);
        releaseValue(value);
        return true;
      }
      function releaseCollectionValues(collection) {
        const resolved = resolveWeakValue(collection);
        if (!isWeakableValue(resolved)) {
          return null;
        }
        const values = retainedCollectionValues.get(resolved);
        if (!values) {
          return null;
        }
        retainedCollectionValues.delete(resolved);
        while (values.length > 0) {
          releaseValue(values.pop());
        }
        return null;
      }
      function releaseValue(value, options = {}) {
        if (isWeakCell(value)) {
          return null;
        }
        const resolved = resolveWeakValue(value);
        if (isWeakableValue(resolved)) {
          const state = weakStates.get(resolved);
          if (state) {
            const wasStrong = state.strong;
            state.strong = Math.max(0, state.strong - 1);
            if (wasStrong > 0 && state.strong === 0) {
              if (!options.preserveCollectionValues) {
                releaseCollectionValues(resolved);
              }
              if (!options.suppressDemolish && typeof resolved.__demolish__ === "function") {
                resolved.__demolish__();
              }
            }
          }
        }
        return null;
      }
      function assignStrongValue(oldValue, newValue) {
        releaseValue(oldValue);
        return retainValue(newValue);
      }
      function assignWeakValue(oldValue, newValue) {
        releaseValue(oldValue);
        return makeWeakValue(newValue);
      }
      function isSetLike(value) {
        return Object.prototype.toString.call(value) === "[object Set]";
      }
      function isPairListLike(value) {
        if (value == null) {
          return false;
        }
        if (value instanceof PairList) {
          return true;
        }
        if (value.__zuzu_builtin_type === "PairList") {
          return true;
        }
        const ctorName = value.constructor && value.constructor.name;
        return ctorName === "PairList" || ctorName === "_PairList";
      }
      function collectTopLevelDeclarations(source, stripPod) {
        const stripped = stripPod(source);
        const masked = [];
        let depth = 0;
        let inSingle = false;
        let inDouble = false;
        let inBacktick = false;
        let inRegex = false;
        let inRegexClass = false;
        let inLineComment = false;
        let inBlockComment = false;
        let escape = false;
        for (let i = 0; i < stripped.length; i++) {
          const ch = stripped[i];
          const next = stripped[i + 1] || "";
          if (inLineComment) {
            if (ch === "\n") {
              inLineComment = false;
              masked.push("\n");
            } else {
              masked.push(" ");
            }
            continue;
          }
          if (inBlockComment) {
            if (ch === "*" && next === "/") {
              inBlockComment = false;
              masked.push(" ");
              i++;
              masked.push(" ");
              continue;
            }
            masked.push(ch === "\n" ? "\n" : " ");
            continue;
          }
          if (inRegex) {
            if (escape) {
              escape = false;
              masked.push(" ");
              continue;
            }
            if (ch === "\\") {
              escape = true;
              masked.push(" ");
              continue;
            }
            if (ch === "[") {
              inRegexClass = true;
              masked.push(" ");
              continue;
            }
            if (ch === "]") {
              inRegexClass = false;
              masked.push(" ");
              continue;
            }
            if (ch === "/" && !inRegexClass) {
              inRegex = false;
              masked.push(" ");
              continue;
            }
            masked.push(ch === "\n" ? "\n" : " ");
            continue;
          }
          if (inSingle || inDouble || inBacktick) {
            if (escape) {
              escape = false;
              masked.push(" ");
              continue;
            }
            if (ch === "\\") {
              escape = true;
              masked.push(" ");
              continue;
            }
            if (inSingle && ch === "'") {
              inSingle = false;
            } else if (inDouble && ch === '"') {
              inDouble = false;
            } else if (inBacktick && ch === "`") {
              inBacktick = false;
            }
            masked.push(ch === "\n" ? "\n" : " ");
            continue;
          }
          if (ch === "/" && next === "/") {
            inLineComment = true;
            masked.push(" ");
            i++;
            masked.push(" ");
            continue;
          }
          if (ch === "/" && next === "*") {
            inBlockComment = true;
            masked.push(" ");
            i++;
            masked.push(" ");
            continue;
          }
          if (ch === "/" && looksLikeRegexLiteralStart(stripped, i)) {
            inRegex = true;
            inRegexClass = false;
            masked.push(" ");
            continue;
          }
          if (ch === "'") {
            inSingle = true;
            masked.push(" ");
            continue;
          }
          if (ch === '"') {
            inDouble = true;
            masked.push(" ");
            continue;
          }
          if (ch === "`") {
            inBacktick = true;
            masked.push(" ");
            continue;
          }
          if (ch === "{") {
            depth++;
            masked.push(" ");
            continue;
          }
          if (ch === "}") {
            if (depth > 0) {
              depth--;
            }
            masked.push(" ");
            continue;
          }
          masked.push(depth === 0 ? ch : ch === "\n" ? "\n" : " ");
        }
        const topLevel = masked.join("");
        const names = /* @__PURE__ */ new Set();
        const patterns = [
          /(?:^|[;\n])\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:\(|\b)/gm,
          /(?:^|[;\n])\s*(?:export\s+)?(?:async\s+)?fn\s+(?:[A-Za-z_][A-Za-z0-9_]*\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*(?:\(|\b)/gm,
          /(?:^|[;\n])\s*(?:export\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)\b/gm,
          /(?:^|[;\n])\s*(?:export\s+)?trait\s+([A-Za-z_][A-Za-z0-9_]*)\b/gm,
          /(?:^|[;\n])\s*(?:export\s+)?(?:let|const)\s+(?:[A-Za-z_][A-Za-z0-9_]*\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*(?::=|=|;)/gm
        ];
        for (const rx of patterns) {
          let match = rx.exec(topLevel);
          while (match) {
            names.add(match[1]);
            match = rx.exec(topLevel);
          }
        }
        for (const name2 of collectTopLevelUnpackDeclarationNames(stripped, topLevel)) {
          names.add(name2);
        }
        const importRx = /(?:^|[;\n])\s*from\s+[^;\n]+?\s+(?:try\s+)?import\s+([\s\S]*?);/gm;
        let importMatch = importRx.exec(topLevel);
        while (importMatch) {
          for (const rawPart of importMatch[1].split(",")) {
            const part = rawPart.trim();
            if (!part || part === "*") {
              continue;
            }
            const alias = part.match(/\bas\s+([A-Za-z_][A-Za-z0-9_]*)\s*$/u);
            if (alias) {
              names.add(alias[1]);
              continue;
            }
            const direct = part.match(/^([A-Za-z_][A-Za-z0-9_]*)\b/u);
            if (direct) {
              names.add(direct[1]);
            }
          }
          importMatch = importRx.exec(topLevel);
        }
        return [...names];
      }
      function looksLikeRegexLiteralStart(source, index) {
        let pos = index - 1;
        while (pos >= 0 && /\s/u.test(source[pos])) {
          pos--;
        }
        if (pos < 0) {
          return true;
        }
        const previous = source[pos];
        return /[({[=,:;!~?&|+\-*%^<>]/u.test(previous);
      }
      function collectTopLevelUnpackDeclarationNames(source, topLevelMask) {
        const names = [];
        const rx = /(?:^|[;\n])\s*(?:export\s+)?(?:let|const)\b/gm;
        let match = rx.exec(topLevelMask);
        while (match) {
          let cursor = rx.lastIndex;
          while (/\s/u.test(source[cursor] || "")) {
            cursor++;
          }
          if (source[cursor] !== "{") {
            match = rx.exec(topLevelMask);
            continue;
          }
          const end = findMatchingBrace(source, cursor);
          if (end !== -1) {
            const pattern = source.slice(cursor + 1, end);
            names.push(...extractUnpackBindingNames(pattern));
            rx.lastIndex = end + 1;
          }
          match = rx.exec(topLevelMask);
        }
        return names;
      }
      function findMatchingBrace(source, start) {
        let depth = 0;
        let quote = null;
        let escape = false;
        for (let i = start; i < source.length; i++) {
          const ch = source[i];
          if (quote) {
            if (escape) {
              escape = false;
            } else if (ch === "\\") {
              escape = true;
            } else if (ch === quote) {
              quote = null;
            }
            continue;
          }
          if (ch === '"' || ch === "'" || ch === "`") {
            quote = ch;
            continue;
          }
          if (ch === "{") {
            depth++;
          } else if (ch === "}") {
            depth--;
            if (depth === 0) {
              return i;
            }
          }
        }
        return -1;
      }
      function extractUnpackBindingNames(pattern) {
        const names = [];
        for (const entry of splitTopLevel(pattern, ",")) {
          const beforeDefault = splitFirstTopLevelOperator(entry, ":=")[0].trim();
          if (!beforeDefault) {
            continue;
          }
          const beforeWeak = beforeDefault.replace(/\s+but\s+weak\s*$/u, "");
          const aliasParts = splitFirstTopLevelOperator(beforeWeak, ":");
          const binding = (aliasParts.length > 1 ? aliasParts[1] : aliasParts[0]).trim();
          const match = binding.match(/(?:^|\s)([A-Za-z_][A-Za-z0-9_]*)\s*$/u);
          if (match) {
            names.push(match[1]);
          }
        }
        return names;
      }
      function splitTopLevel(source, delimiter) {
        const parts = [];
        let start = 0;
        let depth = 0;
        let quote = null;
        let escape = false;
        for (let i = 0; i < source.length; i++) {
          const ch = source[i];
          if (quote) {
            if (escape) {
              escape = false;
            } else if (ch === "\\") {
              escape = true;
            } else if (ch === quote) {
              quote = null;
            }
            continue;
          }
          if (ch === '"' || ch === "'" || ch === "`") {
            quote = ch;
            continue;
          }
          if (ch === "(" || ch === "[" || ch === "{") {
            depth++;
            continue;
          }
          if (ch === ")" || ch === "]" || ch === "}") {
            depth = Math.max(0, depth - 1);
            continue;
          }
          if (depth === 0 && source.slice(i, i + delimiter.length) === delimiter) {
            parts.push(source.slice(start, i));
            i += delimiter.length - 1;
            start = i + 1;
          }
        }
        parts.push(source.slice(start));
        return parts;
      }
      function splitFirstTopLevelOperator(source, operator) {
        const parts = splitTopLevel(source, operator);
        if (parts.length <= 1) {
          return [source];
        }
        return [parts[0], parts.slice(1).join(operator)];
      }
      function buildComparator(name2) {
        if (name2 === "eq") {
          return (left, right) => String(left) === String(right);
        }
        if (name2 === "eqi") {
          return (left, right) => String(left).toLowerCase() === String(right).toLowerCase();
        }
        if (name2 === "~") {
          return (left, right) => {
            if (right && typeof right.test === "function") {
              return right.test(String(left));
            }
            return false;
          };
        }
        return (left, right) => left == right;
      }
      function switchTruthy(value) {
        return !!value;
      }
      function runSwitch(value, cmpName, cases, defaultBody) {
        const cmp = buildComparator(cmpName);
        let runNext = false;
        for (const section of cases) {
          let matched = false;
          if (Array.isArray(section.tests)) {
            matched = section.tests.some((test) => switchTruthy(test(value)));
          } else {
            matched = section.values.some((item) => cmp(value, item));
          }
          if (matched || runNext) {
            const result = section.body();
            runNext = result === true;
            if (!runNext && result && typeof result === "object" && result.__zuzu_return) {
              return result;
            }
            if (!runNext) {
              return;
            }
          }
        }
        if (defaultBody) {
          const result = defaultBody();
          if (result && typeof result === "object" && result.__zuzu_return) {
            return result;
          }
        }
      }
      function runMatch(left, right) {
        if (right && typeof right.test === "function") {
          const flags = typeof right.flags === "string" ? right.flags : "";
          const clone = new RegExp(right.source || operatorString(right), flags);
          const input2 = operatorString(left);
          if (flags.includes("g")) {
            return [...input2.matchAll(clone)];
          }
          const matched2 = input2.match(clone);
          return matched2 || false;
        }
        const input = operatorString(left);
        const pattern = operatorRegexp(right);
        const matched = input.match(pattern);
        return matched || false;
      }
      function toArrayLike(value) {
        if (value instanceof ZuzuBag) {
          return value.to_Array();
        }
        if (isSetLike(value)) {
          return [...value];
        }
        if (Array.isArray(value)) {
          return value.slice();
        }
        if (value && typeof value === "object") {
          return Object.keys(value);
        }
        return [];
      }
      function contains(collection, item) {
        collection = resolveWeakValue(collection);
        item = resolveWeakValue(item);
        if (collection instanceof ZuzuBag) {
          return collection.contains(item);
        }
        if (isSetLike(collection)) {
          for (const value of collection) {
            if (resolveWeakValue(value) === item) {
              return 1;
            }
          }
          return 0;
        }
        if (Array.isArray(collection)) {
          return collection.some((value) => resolveWeakValue(value) === item) ? 1 : 0;
        }
        if (collection && typeof collection === "object") {
          return Object.prototype.hasOwnProperty.call(collection, String(item)) ? 1 : 0;
        }
        return 0;
      }
      function makeLike(left, values) {
        if (left instanceof ZuzuBag) {
          return new ZuzuBag(values);
        }
        if (isSetLike(left)) {
          return new Set(values);
        }
        if (Array.isArray(left)) {
          return [...new Set(values)];
        }
        if (left && typeof left === "object") {
          const out = {};
          for (const key of values) {
            out[String(key)] = true;
          }
          const desc = /* @__PURE__ */ Object.create(null);
          desc.value = function _containsKey(key) {
            return Object.prototype.hasOwnProperty.call(out, String(key)) ? 1 : 0;
          };
          desc.enumerable = false;
          Object.defineProperty(out, "contains", desc);
          return out;
        }
        return values;
      }
      function collectionUnion(left, right) {
        const merged = [...toArrayLike(left), ...toArrayLike(right)];
        const deduped = [...new Set(merged)];
        return makeLike(left, deduped);
      }
      function collectionIntersection(left, right) {
        const rightArr = toArrayLike(right);
        return makeLike(left, toArrayLike(left).filter((item) => rightArr.includes(item)));
      }
      function collectionDifference(left, right) {
        const rightArr = toArrayLike(right);
        return makeLike(left, toArrayLike(left).filter((item) => !rightArr.includes(item)));
      }
      function collectionSubsetOf(left, right) {
        const rightArr = toArrayLike(right);
        return toArrayLike(left).every((item) => rightArr.includes(item)) ? 1 : 0;
      }
      function collectionSupersetOf(left, right) {
        return collectionSubsetOf(right, left);
      }
      function collectionEquivalentOf(left, right) {
        return collectionSubsetOf(left, right) && collectionSubsetOf(right, left) ? 1 : 0;
      }
      function makeArray(values) {
        const array = [];
        for (const value of values) {
          array.push(retainCollectionValue(array, value));
        }
        return array;
      }
      function makeSet(values) {
        const set = /* @__PURE__ */ new Set();
        for (const value of values) {
          addSetValue(set, value);
        }
        if (typeof set.to_Iterator !== "function") {
          const desc = /* @__PURE__ */ Object.create(null);
          desc.value = function _toIterator() {
            return this.values();
          };
          desc.enumerable = false;
          Object.defineProperty(set, "to_Iterator", desc);
        }
        return set;
      }
      function addSetValue(set, value) {
        if (set.has(value)) {
          return value;
        }
        const retained = retainCollectionValue(set, value);
        set.add(retained);
        return retained;
      }
      function makeBag(values) {
        const bag = new ZuzuBag();
        bag.items = values.map((value) => retainCollectionValue(bag, value));
        return bag;
      }
      function makePairList(entries = []) {
        const pairs = new PairList();
        pairs.list = entries.map(
          (entry) => [String(entry[0]), retainCollectionValue(pairs, entry[1])]
        );
        return pairs;
      }
      function makeTemporaryPairList(entries = []) {
        const pairs = makePairList(entries);
        Object.defineProperty(pairs, "__zuzu_temporary_call_args", {
          value: true,
          enumerable: false,
          configurable: true
        });
        return pairs;
      }
      function lengthOf(value) {
        if (value instanceof ZuzuBinary) {
          return value.byteLength();
        }
        if (value && value.bytes instanceof Uint8Array) {
          return value.bytes.length;
        }
        if (isPairListLike(value)) {
          return value.length();
        }
        if (value instanceof ZuzuBag) {
          return value.length();
        }
        if (isSetLike(value)) {
          return value.size;
        }
        if (typeof value === "string") {
          return [...value].length;
        }
        if (Array.isArray(value)) {
          return value.length;
        }
        if (value && typeof value === "object") {
          return Object.keys(value).length;
        }
        return 0;
      }
      function typeName2(value) {
        value = resolveWeakValue(value);
        if (value == null) {
          return "Null";
        }
        if (value instanceof ZuzuBinary) {
          return "BinaryString";
        }
        if (isPairListLike(value)) {
          return "PairList";
        }
        if (value instanceof ZuzuBag) {
          return "Bag";
        }
        if (isSetLike(value)) {
          return "Set";
        }
        if (Array.isArray(value)) {
          return "Array";
        }
        if (value instanceof Pair) {
          return "Pair";
        }
        if (value instanceof RegExp || Object.prototype.toString.call(value) === "[object RegExp]") {
          return "Regexp";
        }
        if (typeof value === "boolean" || Object.prototype.toString.call(value) === "[object Boolean]") {
          return "Boolean";
        }
        if (typeof value === "number" || Object.prototype.toString.call(value) === "[object Number]") {
          return "Number";
        }
        if (typeof value === "string" || Object.prototype.toString.call(value) === "[object String]") {
          return "String";
        }
        if (typeof value === "function") {
          const source = Function.prototype.toString.call(value);
          return /^\s*class\b/.test(source) ? "Class" : "Function";
        }
        if (value && value.constructor && value.constructor.name) {
          const name2 = value.constructor.name;
          return name2 === "Object" ? "Dict" : name2;
        }
        return "Object";
      }
      function renderNumber(value) {
        if (Object.is(value, -0)) {
          return "0";
        }
        return String(value);
      }
      function operatorString(value) {
        value = resolveWeakValue(value);
        if (value == null) {
          return "";
        }
        if (typeof value === "string" || Object.prototype.toString.call(value) === "[object String]") {
          return String(value);
        }
        if (typeof value === "number" || Object.prototype.toString.call(value) === "[object Number]") {
          return renderNumber(Number(value));
        }
        if (typeof value === "boolean" || Object.prototype.toString.call(value) === "[object Boolean]") {
          return value.valueOf() ? "true" : "false";
        }
        if (value instanceof RegExp || Object.prototype.toString.call(value) === "[object RegExp]") {
          return value.source || "";
        }
        if (value instanceof ZuzuBinary) {
          throw new Error(`TypeException: cannot coerce ${typeName2(value)} to String`);
        }
        if (typeof value === "function" || value.__zuzu_method === true || value.constructor && value.constructor.name === "ZuzuMethod") {
          throw new Error(`TypeException: cannot coerce ${typeName2(value)} to String`);
        }
        if (value && typeof value.to_String === "function") {
          return operatorString(value.to_String());
        }
        throw new Error(`TypeException: cannot coerce ${typeName2(value)} to String`);
      }
      var surrogatePattern = /[\uD800-\uDFFF]/;
      function codePointStringCompare(left, right) {
        if (left === right) {
          return 0;
        }
        if (surrogatePattern.test(left) || surrogatePattern.test(right)) {
          const leftPoints = Array.from(left);
          const rightPoints = Array.from(right);
          const shared = Math.min(leftPoints.length, rightPoints.length);
          for (let i = 0; i < shared; i++) {
            const a = leftPoints[i].codePointAt(0);
            const b = rightPoints[i].codePointAt(0);
            if (a !== b) {
              return a < b ? -1 : 1;
            }
          }
          if (leftPoints.length === rightPoints.length) {
            return 0;
          }
          return leftPoints.length < rightPoints.length ? -1 : 1;
        }
        return left < right ? -1 : 1;
      }
      function stringSortComparator(a, b) {
        return codePointStringCompare(String(a), String(b));
      }
      function operatorRegexp(value) {
        value = resolveWeakValue(value);
        if (value instanceof RegExp || Object.prototype.toString.call(value) === "[object RegExp]") {
          const flags = typeof value.flags === "string" ? value.flags : "";
          return new RegExp(value.source || "", flags);
        }
        return new RegExp(operatorString(value));
      }
      module2.exports = {
        collectTopLevelDeclarations,
        runSwitch,
        runMatch,
        toArrayLike,
        contains,
        collectionUnion,
        collectionIntersection,
        collectionDifference,
        collectionSubsetOf,
        collectionSupersetOf,
        collectionEquivalentOf,
        makeArray,
        makeSet,
        makeBag,
        makePairList,
        makeTemporaryPairList,
        lengthOf,
        operatorString,
        operatorRegexp,
        codePointStringCompare,
        stringSortComparator,
        ZuzuBinary,
        BinaryString: BinaryString2,
        ZuzuWeakCell,
        isWeakCell,
        isWeakableValue,
        isPairListLike,
        makeWeakValue,
        resolveWeakValue,
        retainValue,
        releaseValue,
        strongReferenceCount,
        retainCollectionValue,
        releaseCollectionValue,
        releaseCollectionValues,
        addSetValue,
        assignStrongValue,
        assignWeakValue,
        ZuzuBag,
        Pair,
        PairList,
        withArrayMethods
      };
    }
  });

  // modules/std/string.js
  var require_string = __commonJS({
    "modules/std/string.js"(exports2, module2) {
      "use strict";
      var { BinaryString: BinaryString2 } = require_runtime_helpers();
      function toStringValue(value) {
        if (value instanceof RegExp) {
          return value.source;
        }
        if (value && typeof value.to_String === "function") {
          return String(value.to_String());
        }
        if (value instanceof Error) {
          return value.message || value.name || String(value);
        }
        return value == null ? "" : String(value);
      }
      function isRegexLike(value) {
        if (value == null) {
          return false;
        }
        if (value instanceof RegExp) {
          return true;
        }
        return Object.prototype.toString.call(value) === "[object RegExp]";
      }
      function index(text, needle, start = 0) {
        const haystack = [...toStringValue(text)];
        const find = [...toStringValue(needle)];
        const offset = Math.max(0, Math.trunc(Number(start ?? 0)));
        if (find.length === 0) {
          return Math.min(offset, haystack.length);
        }
        for (let i = offset; i <= haystack.length - find.length; i++) {
          let matched = true;
          for (let j = 0; j < find.length; j++) {
            if (haystack[i + j] !== find[j]) {
              matched = false;
              break;
            }
          }
          if (matched) {
            return i;
          }
        }
        return -1;
      }
      function rindex(text, needle, start = null) {
        const haystack = [...toStringValue(text)];
        const find = [...toStringValue(needle)];
        if (start == null) {
          start = haystack.length - find.length;
        } else {
          start = Math.trunc(Number(start));
        }
        if (find.length === 0) {
          return Math.min(Math.max(0, start), haystack.length);
        }
        start = Math.min(Math.max(0, start), haystack.length - find.length);
        for (let i = start; i >= 0; i--) {
          let matched = true;
          for (let j = 0; j < find.length; j++) {
            if (haystack[i + j] !== find[j]) {
              matched = false;
              break;
            }
          }
          if (matched) {
            return i;
          }
        }
        return -1;
      }
      function contains(text, needle) {
        return index(text, needle) >= 0;
      }
      function integerValue(value, label) {
        const number = Number(value ?? 0);
        if (!Number.isInteger(number)) {
          throw new Error(`${label} expects an integer`);
        }
        return number;
      }
      function chr(codepoint) {
        if (arguments.length !== 1) {
          throw new Error("chr() expects one argument");
        }
        const value = integerValue(codepoint, "chr()");
        if (value < 0 || value > 1114111) {
          throw new Error("chr() expects a Unicode code point in 0..0x10FFFF");
        }
        if (value >= 55296 && value <= 57343) {
          throw new Error("chr() rejects surrogate code points");
        }
        return String.fromCodePoint(value);
      }
      function ord(text, index2 = 0) {
        if (arguments.length < 1 || arguments.length > 2) {
          throw new Error("ord() expects one or two arguments");
        }
        const chars = [...toStringValue(text)];
        const offset = integerValue(index2, "ord()");
        if (offset < 0 || offset >= chars.length) {
          throw new Error("ord() index out of range");
        }
        return chars[offset].codePointAt(0);
      }
      function substr(text, offset, length = null) {
        const chars = [...toStringValue(text)];
        const from = Number(offset ?? 0);
        if (length == null) {
          return chars.slice(from).join("");
        }
        return chars.slice(from, from + Number(length)).join("");
      }
      function pattern_to_regexp(pattern, caseInsensitive = false) {
        return new RegExp(String(pattern ?? ""), caseInsensitive ? "i" : "");
      }
      var REGEXP_META_CHARS = /* @__PURE__ */ new Set([
        "\\",
        "/",
        "^",
        "$",
        ".",
        "|",
        "?",
        "*",
        "+",
        "(",
        ")",
        "[",
        "]",
        "{",
        "}",
        '"',
        "'"
      ]);
      function quotemeta(text) {
        return [...toStringValue(text)].map((ch) => REGEXP_META_CHARS.has(ch) ? `\\${ch}` : ch).join("");
      }
      function normalizePattern(pattern, flags = "") {
        if (isRegexLike(pattern)) {
          const mergedFlags = [...pattern.flags || "", ...flags || ""];
          const uniqFlags = [...new Set(mergedFlags)].join("");
          return new RegExp(pattern.source, uniqFlags);
        }
        return new RegExp(String(pattern ?? ""), flags);
      }
      function search(text, pattern, flags = "") {
        const match = toStringValue(text).match(normalizePattern(pattern, flags));
        return match ? match[0] : null;
      }
      function matches(text, pattern, flags = "") {
        return normalizePattern(pattern, flags).test(toStringValue(text));
      }
      function replace(text, pattern, replacement, flags = "") {
        return toStringValue(text).replace(normalizePattern(pattern, flags), toStringValue(replacement));
      }
      function sprint(format, ...args) {
        let idx = 0;
        return toStringValue(format).replace(/%([0-9]+)?(?:\.([0-9]+))?([sdfc])/gu, (_token, width, precision, kind) => {
          const value = args[idx++];
          let out = "";
          if (kind === "d") {
            out = String(Math.trunc(Number(value ?? 0)));
          } else if (kind === "f") {
            const num = Number(value ?? 0);
            out = precision != null ? num.toFixed(Number(precision)) : String(num);
          } else if (kind === "c") {
            out = String.fromCharCode(Number(value ?? 0));
          } else {
            out = toStringValue(value);
          }
          if (width != null) {
            const target = Number(width);
            if (out.length < target) {
              out = `${" ".repeat(target - out.length)}${out}`;
            }
          }
          return out;
        });
      }
      function join(separator, values) {
        const sep = toStringValue(separator);
        if (Array.isArray(values)) {
          return values.map((value) => toStringValue(value)).join(sep);
        }
        if (values == null) {
          return "";
        }
        if (typeof values.to_Iterator === "function") {
          const out = [];
          for (const value of values.to_Iterator()) {
            out.push(toStringValue(value));
          }
          return out.join(sep);
        }
        if (typeof values.to_Array === "function") {
          return join(sep, values.to_Array());
        }
        if (typeof values[Symbol.iterator] === "function") {
          return Array.from(values, (value) => toStringValue(value)).join(sep);
        }
        return toStringValue(values);
      }
      function split(text, pattern) {
        return toStringValue(text).split(pattern);
      }
      function starts_with(text, prefix) {
        return toStringValue(text).startsWith(toStringValue(prefix));
      }
      function ends_with(text, suffix) {
        return toStringValue(text).endsWith(toStringValue(suffix));
      }
      function trim(text) {
        return toStringValue(text).trim();
      }
      function pad(text, width, ch = " ", side = "right") {
        const src = toStringValue(text);
        const padChar = toStringValue(ch || " ");
        const target = Number(width ?? 0);
        if (src.length >= target) {
          return src;
        }
        const fill = padChar.repeat(target - src.length);
        return side === "left" ? `${fill}${src}` : `${src}${fill}`;
      }
      function chomp(text) {
        return toStringValue(text).replace(/\r?\n$/u, "");
      }
      function words(text) {
        return toStringValue(text).replace(/([a-z0-9])([A-Z])/gu, "$1 $2").replace(/[_\-]+/gu, " ").trim().split(/\s+/u).filter(Boolean);
      }
      function title(text) {
        return words(text).map((w) => `${w[0].toUpperCase()}${w.slice(1).toLowerCase()}`).join(" ");
      }
      function snake(text) {
        return words(text).map((w) => w.toLowerCase()).join("_");
      }
      function kebab(text) {
        return words(text).map((w) => w.toLowerCase()).join("-");
      }
      function camel(text) {
        const ws = words(text).map((w) => w.toLowerCase());
        return ws.map((w, i) => i === 0 ? w : `${w[0].toUpperCase()}${w.slice(1)}`).join("");
      }
      function to_binary(value) {
        if (typeof value !== "string" && !(value instanceof String)) {
          const type = value == null ? "Null" : value && value.bytes instanceof Uint8Array ? "BinaryString" : typeof value;
          throw new Error(`TypeException: to_binary expects String, got ${type}`);
        }
        return new BinaryString2(new TextEncoder().encode(String(value)));
      }
      function to_string(value) {
        if (!(value && value.bytes instanceof Uint8Array)) {
          throw new Error("TypeException: to_string expects BinaryString");
        }
        return new TextDecoder("utf-8", { fatal: true }).decode(value.bytes);
      }
      module2.exports = {
        camel,
        chomp,
        chr,
        contains,
        ends_with,
        index,
        join,
        kebab,
        matches,
        ord,
        pad,
        pattern_to_regexp,
        quotemeta,
        rindex,
        replace,
        search,
        snake,
        split,
        starts_with,
        sprint,
        substr,
        title,
        to_binary,
        to_string,
        trim
      };
    }
  });

  // modules/std/string/base64.js
  var require_base64 = __commonJS({
    "modules/std/string/base64.js"(exports2, module2) {
      "use strict";
      var { BinaryString: BinaryString2 } = require_runtime_helpers();
      var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
      var DECODE = (() => {
        const out = /* @__PURE__ */ Object.create(null);
        for (let i = 0; i < ALPHABET.length; i++) {
          out[ALPHABET[i]] = i;
        }
        return out;
      })();
      function typeName2(value) {
        if (value == null) {
          return "Null";
        }
        if (typeof value === "string") {
          return "String";
        }
        if (value.bytes instanceof Uint8Array) {
          return "BinaryString";
        }
        return value.constructor && value.constructor.name ? value.constructor.name : typeof value;
      }
      function encodeBytes(bytes) {
        let out = "";
        for (let i = 0; i < bytes.length; i += 3) {
          const b0 = bytes[i];
          const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;
          const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;
          out += ALPHABET[b0 >> 2];
          out += ALPHABET[(b0 & 3) << 4 | b1 >> 4];
          out += i + 1 < bytes.length ? ALPHABET[(b1 & 15) << 2 | b2 >> 6] : "=";
          out += i + 2 < bytes.length ? ALPHABET[b2 & 63] : "=";
        }
        return out;
      }
      function decodeText(value) {
        const clean = String(value).replace(/\s+/gu, "");
        if (clean.length % 4 !== 0) {
          throw new Error("Exception: invalid Base64 length");
        }
        let padding = 0;
        if (clean.endsWith("==")) {
          padding = 2;
        } else if (clean.endsWith("=")) {
          padding = 1;
        }
        const bytes = [];
        for (let i = 0; i < clean.length; i += 4) {
          const chunk = clean.slice(i, i + 4);
          const values = [];
          for (let j = 0; j < 4; j++) {
            const ch = chunk[j];
            if (ch === "=") {
              values.push(0);
              continue;
            }
            if (DECODE[ch] == null) {
              throw new Error(`Exception: invalid Base64 character '${ch}'`);
            }
            values.push(DECODE[ch]);
          }
          const triple = values[0] << 18 | values[1] << 12 | values[2] << 6 | values[3];
          bytes.push(triple >> 16 & 255);
          if (chunk[2] !== "=") {
            bytes.push(triple >> 8 & 255);
          }
          if (chunk[3] !== "=") {
            bytes.push(triple & 255);
          }
        }
        const firstPadding = clean.indexOf("=");
        if (firstPadding >= 0 && firstPadding !== clean.length - padding) {
          throw new Error("Exception: invalid Base64 padding");
        }
        return new Uint8Array(bytes);
      }
      function encode(value) {
        if (!(value && value.bytes instanceof Uint8Array)) {
          throw new Error(`TypeException: encode expects BinaryString, got ${typeName2(value)}`);
        }
        return encodeBytes(value.bytes);
      }
      function decode(value) {
        if (typeof value !== "string") {
          throw new Error(`TypeException: decode expects String, got ${typeName2(value)}`);
        }
        return new BinaryString2(decodeText(value));
      }
      function encode_urlsafe(value) {
        return encode(value).replace(/\+/gu, "-").replace(/\//gu, "_").replace(/=+$/gu, "");
      }
      function decode_urlsafe(value) {
        if (typeof value !== "string") {
          throw new Error(`TypeException: decode expects String, got ${typeName2(value)}`);
        }
        let normalized = value.replace(/-/gu, "+").replace(/_/gu, "/");
        const mod = normalized.length % 4;
        if (mod !== 0) {
          normalized += "=".repeat(4 - mod);
        }
        return decode(normalized);
      }
      module2.exports = {
        decode,
        decode_urlsafe,
        encode,
        encode_urlsafe
      };
    }
  });

  // modules/std/string/encode.js
  var require_encode = __commonJS({
    "modules/std/string/encode.js"(exports2, module2) {
      "use strict";
      var { BinaryString: BinaryString2 } = require_runtime_helpers();
      function typeName2(value) {
        if (value == null) {
          return "Null";
        }
        if (typeof value === "string" || value instanceof String) {
          return "String";
        }
        if (value.bytes instanceof Uint8Array) {
          return "BinaryString";
        }
        return value.constructor && value.constructor.name ? value.constructor.name : typeof value;
      }
      function canonicalEncoding(name2) {
        const upper = String(name2 == null ? "UTF-8" : name2).toUpperCase().replace(/\s+/g, "");
        if (upper === "UTF-8" || upper === "UTF8") {
          return "utf8";
        }
        if (upper === "UTF-16" || upper === "UTF16" || upper === "UTF-16BE") {
          return "utf16";
        }
        if (upper === "UTF-32" || upper === "UTF32" || upper === "UTF-32BE") {
          return "utf32";
        }
        if (upper === "ISO-8859-1" || upper === "ISO8859-1" || upper === "LATIN-1" || upper === "LATIN1" || upper === "LATIN") {
          return "latin1";
        }
        return null;
      }
      function codePoints(text) {
        return Array.from(text, (ch) => ch.codePointAt(0));
      }
      function encode(value, encoding) {
        if (typeName2(value) !== "String") {
          throw new Error(`TypeException: encode expects String, got ${typeName2(value)}`);
        }
        const text = String(value);
        const codec = canonicalEncoding(encoding);
        if (codec === "utf8") {
          return new BinaryString2(new TextEncoder().encode(text));
        }
        if (codec === "utf16") {
          const out = [];
          for (let i = 0; i < text.length; i++) {
            const unit = text.charCodeAt(i);
            out.push(unit >> 8 & 255, unit & 255);
          }
          return new BinaryString2(out);
        }
        if (codec === "utf32") {
          const out = [];
          for (const point of codePoints(text)) {
            out.push(
              point >>> 24 & 255,
              point >>> 16 & 255,
              point >>> 8 & 255,
              point & 255
            );
          }
          return new BinaryString2(out);
        }
        if (codec === "latin1") {
          const out = [];
          for (const point of codePoints(text)) {
            if (point > 255) {
              const hex = point.toString(16).toUpperCase().padStart(4, "0");
              throw new Error(`Exception: Character U+${hex} cannot be encoded as ISO-8859-1`);
            }
            out.push(point);
          }
          return new BinaryString2(out);
        }
        throw new Error(`Exception: Unsupported encoding: ${encoding}`);
      }
      function decode(value, encoding) {
        if (typeName2(value) !== "BinaryString") {
          throw new Error(`TypeException: decode expects BinaryString, got ${typeName2(value)}`);
        }
        let bytes = value.bytes;
        const codec = canonicalEncoding(encoding);
        if (codec === "utf8") {
          try {
            return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
          } catch (_err) {
            throw new Error("Exception: Invalid UTF-8 in BinaryString");
          }
        }
        if (codec === "utf16") {
          let bigEndian = true;
          if (bytes.length >= 2 && bytes[0] === 254 && bytes[1] === 255) {
            bytes = bytes.subarray(2);
          } else if (bytes.length >= 2 && bytes[0] === 255 && bytes[1] === 254) {
            bigEndian = false;
            bytes = bytes.subarray(2);
          }
          if (bytes.length % 2 !== 0) {
            throw new Error("Exception: UTF-16 input length must be a multiple of 2 bytes");
          }
          const units = [];
          for (let i = 0; i < bytes.length; i += 2) {
            units.push(bigEndian ? bytes[i] << 8 | bytes[i + 1] : bytes[i + 1] << 8 | bytes[i]);
          }
          let out = "";
          for (let i = 0; i < units.length; i++) {
            const unit = units[i];
            if (unit >= 55296 && unit <= 56319) {
              const next = units[i + 1];
              if (next == null || next < 56320 || next > 57343) {
                throw new Error("Exception: Invalid UTF-16 in BinaryString");
              }
              out += String.fromCharCode(unit, next);
              i++;
              continue;
            }
            if (unit >= 56320 && unit <= 57343) {
              throw new Error("Exception: Invalid UTF-16 in BinaryString");
            }
            out += String.fromCharCode(unit);
          }
          return out;
        }
        if (codec === "utf32") {
          let bigEndian = true;
          if (bytes.length >= 4 && bytes[0] === 0 && bytes[1] === 0 && bytes[2] === 254 && bytes[3] === 255) {
            bytes = bytes.subarray(4);
          } else if (bytes.length >= 4 && bytes[0] === 255 && bytes[1] === 254 && bytes[2] === 0 && bytes[3] === 0) {
            bigEndian = false;
            bytes = bytes.subarray(4);
          }
          if (bytes.length % 4 !== 0) {
            throw new Error("Exception: UTF-32 input length must be a multiple of 4 bytes");
          }
          let out = "";
          for (let i = 0; i < bytes.length; i += 4) {
            const point = bigEndian ? bytes[i] * 16777216 + (bytes[i + 1] << 16) + (bytes[i + 2] << 8) + bytes[i + 3] : bytes[i + 3] * 16777216 + (bytes[i + 2] << 16) + (bytes[i + 1] << 8) + bytes[i];
            if (point > 1114111 || point >= 55296 && point <= 57343) {
              throw new Error("Exception: Invalid UTF-32 in BinaryString");
            }
            out += String.fromCodePoint(point);
          }
          return out;
        }
        if (codec === "latin1") {
          let out = "";
          for (const byte of bytes) {
            out += String.fromCharCode(byte);
          }
          return out;
        }
        throw new Error(`Exception: Unsupported encoding: ${encoding}`);
      }
      module2.exports = {
        encode,
        decode,
        ENCODING_UTF8: "UTF-8",
        ENCODING_UTF16: "UTF-16",
        ENCODING_UTF32: "UTF-32",
        ENCODING_LATIN: "ISO-8859-1"
      };
    }
  });

  // modules/std/time.js
  var require_time = __commonJS({
    "modules/std/time.js"(exports2, module2) {
      "use strict";
      var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
      var MONTH_BY_NAME = /* @__PURE__ */ new Map([
        ["jan", 1],
        ["january", 1],
        ["feb", 2],
        ["february", 2],
        ["mar", 3],
        ["march", 3],
        ["apr", 4],
        ["april", 4],
        ["may", 5],
        ["jun", 6],
        ["june", 6],
        ["jul", 7],
        ["july", 7],
        ["aug", 8],
        ["august", 8],
        ["sep", 9],
        ["sept", 9],
        ["september", 9],
        ["oct", 10],
        ["october", 10],
        ["nov", 11],
        ["november", 11],
        ["dec", 12],
        ["december", 12]
      ]);
      var DAY_ABBR = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
      var WEEKDAY_BY_NAME = /* @__PURE__ */ new Set([
        "sun",
        "sunday",
        "mon",
        "monday",
        "tue",
        "tues",
        "tuesday",
        "wed",
        "weds",
        "wednesday",
        "thu",
        "thur",
        "thurs",
        "thursday",
        "fri",
        "friday",
        "sat",
        "saturday"
      ]);
      function defineType(object, name2) {
        Object.defineProperty(object, "__zuzu_type_name", {
          value: name2,
          enumerable: false,
          configurable: true
        });
      }
      function zoneName(zone) {
        if (zone instanceof TimeZone) {
          return zone.name();
        }
        if (zone == null || String(zone) === "") {
          return "UTC";
        }
        const text = String(zone);
        if (/^z$/iu.test(text) || /^gmt$/iu.test(text)) {
          return "UTC";
        }
        if (/^([+-]\d\d):?(\d\d)$/u.test(text)) {
          return text.replace(/^([+-]\d\d):?(\d\d)$/u, "$1:$2");
        }
        return text;
      }
      function isFixedOffset(zone) {
        return /^([+-]\d\d):(\d\d)$/u.test(zoneName(zone));
      }
      function offsetSeconds(zone) {
        const m = zoneName(zone).match(/^([+-])(\d\d):(\d\d)$/u);
        if (!m) {
          return null;
        }
        const seconds = Number(m[2]) * 3600 + Number(m[3]) * 60;
        return m[1] === "-" ? -seconds : seconds;
      }
      function pad(value, width = 2, fill = "0") {
        return String(value).padStart(width, fill);
      }
      function stripTrailingPeriod(text) {
        return String(text).replace(/\.+$/u, "").toLowerCase();
      }
      function weekdayIndex(parts) {
        const date = new Date(
          parts.year,
          parts.month - 1,
          parts.day
        );
        return (date.getDay() + 6) % 7 + 1;
      }
      function weekParts(parts) {
        const date = new Date(
          parts.year,
          parts.month - 1,
          parts.day
        );
        const weekDay = date.getDay() || 7;
        const shifted = new Date(date);
        shifted.setDate(date.getDate() + 4 - weekDay);
        const weekYear = shifted.getFullYear();
        const yearStart = new Date(weekYear, 0, 1);
        return {
          year: weekYear,
          week: Math.ceil((shifted - yearStart) / 864e5 / 7 + 1)
        };
      }
      function dayOfMonthForDisplay(day) {
        return String(day).padStart(2, " ");
      }
      function dayOfYear(parts) {
        const start = new Date(parts.year, 0, 1);
        const now = new Date(parts.year, parts.month - 1, parts.day);
        return (now - start) / 864e5;
      }
      function julianDay(parts) {
        let year = parts.year;
        let month = parts.month;
        const day = parts.day;
        if (month <= 2) {
          year -= 1;
          month += 12;
        }
        const a = Math.floor((14 - month) / 12);
        const y = year + 4800 - a;
        const m = month + 12 * a - 3;
        const jd = day + Math.floor((153 * m + 2) / 5) + 365 * y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) - 32045;
        const fraction = (parts.hour * 3600 + parts.minute * 60 + parts.second) / 86400;
        return jd + fraction - 0.5;
      }
      function isLeapYear(year) {
        if (year % 4 !== 0) return false;
        if (year % 100 !== 0) return true;
        return year % 400 === 0;
      }
      function daysInMonth(year, month) {
        if ([1, 3, 5, 7, 8, 10, 12].includes(month)) return 31;
        if ([4, 6, 9, 11].includes(month)) return 30;
        if (month === 2) return isLeapYear(year) ? 29 : 28;
        return 0;
      }
      function normaliseParts(parts) {
        if (parts.hour === 24) {
          parts.hour = 0;
        }
        return parts;
      }
      function partsForEpoch(epoch, zone) {
        const name2 = zoneName(zone);
        if (isFixedOffset(name2)) {
          const d = new Date((epoch + offsetSeconds(name2)) * 1e3);
          return {
            year: d.getUTCFullYear(),
            month: d.getUTCMonth() + 1,
            day: d.getUTCDate(),
            hour: d.getUTCHours(),
            minute: d.getUTCMinutes(),
            second: d.getUTCSeconds(),
            offset: offsetSeconds(name2)
          };
        }
        const formatter = new Intl.DateTimeFormat("en-GB-u-ca-gregory", {
          timeZone: name2 === "local" ? void 0 : name2,
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
          hour: "2-digit",
          minute: "2-digit",
          second: "2-digit",
          hourCycle: "h23"
        });
        const out = {};
        for (const part of formatter.formatToParts(new Date(epoch * 1e3))) {
          if (part.type === "year") out.year = Number(part.value);
          if (part.type === "month") out.month = Number(part.value);
          if (part.type === "day") out.day = Number(part.value);
          if (part.type === "hour") out.hour = Number(part.value);
          if (part.type === "minute") out.minute = Number(part.value);
          if (part.type === "second") out.second = Number(part.value);
        }
        return normaliseParts(out);
      }
      function offsetForEpoch(epoch, zone) {
        if (isFixedOffset(zone)) {
          return offsetSeconds(zone);
        }
        const parts = partsForEpoch(epoch, zone);
        const naive = Date.UTC(
          parts.year,
          parts.month - 1,
          parts.day,
          parts.hour,
          parts.minute,
          parts.second
        ) / 1e3;
        return naive - Math.floor(epoch);
      }
      function sameWallEpoch(wall, zone) {
        const name2 = zoneName(zone);
        let current = { ...wall };
        for (let shift = 0; shift <= 180; shift++) {
          if (shift > 0) {
            const shifted = new Date(Date.UTC(
              wall.year,
              wall.month - 1,
              wall.day,
              wall.hour,
              wall.minute + shift,
              wall.second
            ));
            current = {
              year: shifted.getUTCFullYear(),
              month: shifted.getUTCMonth() + 1,
              day: shifted.getUTCDate(),
              hour: shifted.getUTCHours(),
              minute: shifted.getUTCMinutes(),
              second: shifted.getUTCSeconds()
            };
          }
          const naive = Date.UTC(
            current.year,
            current.month - 1,
            current.day,
            current.hour,
            current.minute,
            current.second
          ) / 1e3;
          const offsets = /* @__PURE__ */ new Set([
            offsetForEpoch(naive - 172800, name2),
            offsetForEpoch(naive - 86400, name2),
            offsetForEpoch(naive - 3600, name2),
            offsetForEpoch(naive, name2),
            offsetForEpoch(naive + 3600, name2),
            offsetForEpoch(naive + 86400, name2),
            offsetForEpoch(naive + 172800, name2)
          ]);
          const candidates = [];
          for (const offset of offsets) {
            const candidate = naive - offset;
            const check = partsForEpoch(candidate, name2);
            if (check.year === current.year && check.month === current.month && check.day === current.day && check.hour === current.hour && check.minute === current.minute && check.second === current.second) {
              candidates.push(candidate);
            }
          }
          if (candidates.length) {
            return Math.min(...candidates) + (wall.fraction || 0);
          }
        }
        return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) / 1e3;
      }
      function addMonthsToWall(parts, months) {
        const total = parts.year * 12 + (parts.month - 1) + Number(months);
        const year = Math.floor(total / 12);
        const month = (total % 12 + 12) % 12 + 1;
        const last = new Date(Date.UTC(year, month, 0)).getUTCDate();
        return { ...parts, year, month, day: Math.min(parts.day, last) };
      }
      function formatOffset(seconds, colon = true) {
        const sign = seconds < 0 ? "-" : "+";
        const abs = Math.abs(seconds);
        const text = `${sign}${pad(Math.floor(abs / 3600))}${pad(Math.floor(abs % 3600 / 60))}`;
        return colon ? `${text.slice(0, 3)}:${text.slice(3)}` : text;
      }
      function parseOffset(text) {
        if (text == null || /^(?:z|utc|gmt)$/iu.test(text)) {
          return 0;
        }
        if (/^ut$/iu.test(text)) {
          return 0;
        }
        const m = String(text).match(/^([+-])(\d\d):?(\d\d)$/u);
        if (!m) {
          return null;
        }
        const hours = Number(m[2]);
        const minutes = Number(m[3]);
        if (hours > 23 || minutes > 59) {
          return null;
        }
        const value = hours * 3600 + minutes * 60;
        return m[1] === "-" ? -value : value;
      }
      function parseRfc5322Zone(text) {
        const offset = parseOffset(text);
        if (offset != null) {
          return offset;
        }
        const key = String(text).toUpperCase();
        const legacy = {
          EST: -5 * 3600,
          EDT: -4 * 3600,
          CST: -6 * 3600,
          CDT: -5 * 3600,
          MST: -7 * 3600,
          MDT: -6 * 3600,
          PST: -8 * 3600,
          PDT: -7 * 3600
        };
        if (Object.prototype.hasOwnProperty.call(legacy, key)) {
          return legacy[key];
        }
        if (/^[A-Z]$/u.test(key) && key !== "J") {
          const pos = "ABCDEFGHIKLMNOPQRSTUVWXYZ".indexOf(key);
          if (pos >= 0) {
            return pos < 12 ? (pos + 1) * 3600 : -(pos - 11) * 3600;
          }
        }
        return null;
      }
      var TimeZone = class _TimeZone {
        constructor(name2 = "UTC") {
          defineType(this, "TimeZone");
          this._name = zoneName(name2);
        }
        static utc() {
          return new _TimeZone("UTC");
        }
        static local() {
          return new _TimeZone("local");
        }
        static named(name2) {
          return new _TimeZone(name2);
        }
        static offset(seconds) {
          return new _TimeZone(formatOffset(Number(seconds), true));
        }
        name() {
          return zoneName(this._name);
        }
        to_String() {
          return this.name();
        }
      };
      var Duration = class _Duration {
        constructor(seconds = 0, options = {}) {
          defineType(this, "Duration");
          this._years = Number(options.years || 0);
          this._months = Number(options.months || 0);
          this._weeks = Number(options.weeks || 0);
          this._days = Number(options.days || 0);
          this._hours = Number(options.hours || 0);
          this._minutes = Number(options.minutes || 0);
          this._seconds = Number(options.seconds == null ? seconds : options.seconds);
        }
        static seconds(n) {
          return new _Duration(n);
        }
        static minutes(n) {
          return new _Duration(0, { minutes: n });
        }
        static hours(n) {
          return new _Duration(0, { hours: n });
        }
        static days(n) {
          return new _Duration(0, { days: n });
        }
        static weeks(n) {
          return new _Duration(0, { weeks: n });
        }
        static months(n) {
          return new _Duration(0, { months: n });
        }
        static years(n) {
          return new _Duration(0, { years: n });
        }
        years() {
          return this._years;
        }
        months() {
          return this._months;
        }
        weeks() {
          return this._weeks;
        }
        days() {
          return this._days;
        }
        hours() {
          return this._hours;
        }
        minutes() {
          return this._minutes;
        }
        seconds() {
          return this._seconds;
        }
      };
      var TimeFormat = class _TimeFormat {
        constructor(pattern = "", options = {}) {
          defineType(this, "TimeFormat");
          this._kind = options.kind || "strftime";
          this._pattern = pattern == null ? "" : String(pattern);
          this._timezone = options.timezone == null ? null : zoneName(options.timezone);
        }
        static iso8601() {
          return new _TimeFormat("", { kind: "iso8601" });
        }
        static rfc3339() {
          return new _TimeFormat("", { kind: "rfc3339" });
        }
        static rfc5322() {
          return new _TimeFormat("", { kind: "rfc5322" });
        }
        static strftime(pattern, options = {}) {
          return new _TimeFormat(pattern, { kind: "strftime", timezone: options.timezone });
        }
        format(time) {
          return time.format(this);
        }
        parse(text, options = {}) {
          const parsed = parseTimeText(String(text), this._timezone || options.timezone, true);
          return new Time2(parsed.epoch, { timezone: this._timezone || options.timezone || parsed.zone });
        }
      };
      function parseTimeText(text, defaultZone, requireZone) {
        let m = text.match(/^(\d{4})-(\d\d)-(\d\d)(?:[Tt ](\d\d):(\d\d)(?::(\d\d)(?:\.\d+)?)?)?(?:\s*(Z|[+-]\d\d:?\d\d))?$/u);
        if (m) {
          if (requireZone && !m[7] && defaultZone == null) {
            throw new Error("Time.parse() requires a timezone");
          }
          const offset = m[7] ? parseOffset(m[7]) : null;
          if (m[7] && offset == null) {
            throw new Error("invalid time zone");
          }
          const zone = m[7] ? formatOffset(offset, true) : zoneName(defaultZone);
          const year = Number(m[1]);
          const month = Number(m[2]);
          const day = Number(m[3]);
          const hour = Number(m[4] || 0);
          const minute = Number(m[5] || 0);
          const second = Number(m[6] || 0);
          if (hour > 23 || minute > 59 || second > 59) {
            throw new Error("invalid time");
          }
          if (day < 1 || day > daysInMonth(year, month)) {
            throw new Error("invalid date");
          }
          return {
            epoch: sameWallEpoch({
              year,
              month,
              day,
              hour,
              minute,
              second
            }, zone),
            zone
          };
        }
        m = text.match(/^(?:([A-Za-z.]+),\s*)?(\d{1,2})\s+([A-Za-z.]+)\s+(\d{2}|\d{4})\s+(\d{1,2}):(\d\d)(?::(\d\d))?\s+([+-]\d\d:?\d\d|[A-Za-z]{1,5})$/iu);
        if (m) {
          if (m[1] && !WEEKDAY_BY_NAME.has(stripTrailingPeriod(m[1]))) {
            throw new Error("invalid weekday");
          }
          const month = MONTH_BY_NAME.get(stripTrailingPeriod(m[3]));
          if (!month) throw new Error("invalid month");
          let year = Number(m[4]);
          if (String(m[4]).length === 2) {
            year += year >= 50 ? 1900 : 2e3;
          }
          if (year < 1) {
            throw new Error("invalid year");
          }
          const day = Number(m[2]);
          const hour = Number(m[5]);
          const minute = Number(m[6]);
          const second = Number(m[7] || 0);
          if (hour > 23 || minute > 59 || second > 59) {
            throw new Error("invalid time");
          }
          if (day < 1 || day > daysInMonth(year, month)) {
            throw new Error("invalid date");
          }
          const offset = parseRfc5322Zone(m[8]);
          if (offset == null) {
            throw new Error("invalid time zone");
          }
          const zone = formatOffset(offset, true);
          return {
            epoch: sameWallEpoch({
              year,
              month,
              day,
              hour,
              minute,
              second
            }, zone),
            zone
          };
        }
        throw new Error("Error parsing time");
      }
      var Time2 = class _Time {
        constructor(epoch = null, options = {}) {
          defineType(this, "Time");
          this._epoch = epoch == null ? Math.floor(Date.now() / 1e3) : Number(epoch);
          this._timezone = zoneName(options.timezone || "UTC");
        }
        static parse(text, options = {}) {
          const parsed = parseTimeText(String(text), options.timezone, true);
          return new _Time(parsed.epoch, { timezone: options.timezone || parsed.zone });
        }
        _clone(nextEpoch, zone = this._timezone) {
          return new _Time(nextEpoch, { timezone: zone });
        }
        _parts() {
          return partsForEpoch(this._epoch, this._timezone);
        }
        epoch() {
          return this._epoch;
        }
        timezone() {
          return new TimeZone(this._timezone);
        }
        with_timezone(zone) {
          return this._clone(this._epoch, zoneName(zone));
        }
        reinterpret_timezone(zone) {
          return this._clone(sameWallEpoch(this._parts(), zone), zoneName(zone));
        }
        as_utc() {
          return this.with_timezone("UTC");
        }
        as_local() {
          return this.with_timezone("local");
        }
        sec() {
          return this._parts().second;
        }
        min() {
          return this._parts().minute;
        }
        hour() {
          return this._parts().hour;
        }
        day_of_month() {
          return this._parts().day;
        }
        mon() {
          return this._parts().month;
        }
        month() {
          return this.mon();
        }
        year() {
          return this._parts().year;
        }
        yy() {
          return pad(this._parts().year % 100, 2);
        }
        day_of_week() {
          return weekdayIndex(this._parts());
        }
        day() {
          return DAY_ABBR[this.day_of_week() - 1];
        }
        day_of_year() {
          return dayOfYear(this._parts());
        }
        month_last_day() {
          return daysInMonth(this._parts().year, this._parts().month);
        }
        hms(separator = ":") {
          const p = this._parts();
          return `${pad(p.hour)}${String(separator)}${pad(p.minute)}${String(separator)}${pad(p.second)}`;
        }
        ymd(separator = "-") {
          const p = this._parts();
          const sep = String(separator);
          return `${pad(p.year, 4)}${sep}${pad(p.month)}${sep}${pad(p.day)}`;
        }
        mdy(separator = "-") {
          const p = this._parts();
          const sep = String(separator);
          return `${pad(p.month)}${sep}${pad(p.day)}${sep}${pad(p.year, 4)}`;
        }
        dmy(separator = "-") {
          const p = this._parts();
          const sep = String(separator);
          return `${pad(p.day)}${sep}${pad(p.month)}${sep}${pad(p.year, 4)}`;
        }
        cdate() {
          const p = this._parts();
          return `${DAY_ABBR[weekdayIndex(p) - 1]} ${MONTHS[p.month - 1]} ${dayOfMonthForDisplay(p.day)} ${pad(p.hour)}:${pad(p.minute)}:${pad(p.second)} ${p.year}`;
        }
        tzoffset() {
          return offsetForEpoch(this._epoch, this._timezone);
        }
        is_leap_year() {
          return isLeapYear(this._parts().year);
        }
        week() {
          return weekParts(this._parts()).week;
        }
        week_year() {
          return weekParts(this._parts()).year;
        }
        julian_day() {
          return julianDay(this._parts());
        }
        add_seconds(n) {
          return this._clone(this._epoch + Number(n));
        }
        add_minutes(n) {
          return this.add_seconds(Number(n) * 60);
        }
        add_hours(n) {
          return this.add_seconds(Number(n) * 3600);
        }
        _calendarAdd(delta) {
          let parts = this._parts();
          if (delta.years) parts = addMonthsToWall(parts, Number(delta.years) * 12);
          if (delta.months) parts = addMonthsToWall(parts, delta.months);
          const dayDelta = Number(delta.days || 0) + Number(delta.weeks || 0) * 7;
          if (dayDelta) {
            const d = new Date(Date.UTC(
              parts.year,
              parts.month - 1,
              parts.day + dayDelta,
              parts.hour,
              parts.minute,
              parts.second
            ));
            parts = {
              year: d.getUTCFullYear(),
              month: d.getUTCMonth() + 1,
              day: d.getUTCDate(),
              hour: d.getUTCHours(),
              minute: d.getUTCMinutes(),
              second: d.getUTCSeconds()
            };
          }
          return this._clone(sameWallEpoch(parts, this._timezone));
        }
        add_days(n) {
          return this._calendarAdd({ days: n });
        }
        add_weeks(n) {
          return this._calendarAdd({ weeks: n });
        }
        add_months(n) {
          return this._calendarAdd({ months: n });
        }
        add_years(n) {
          return this._calendarAdd({ years: n });
        }
        subtract_seconds(n) {
          return this.add_seconds(-Number(n));
        }
        subtract_minutes(n) {
          return this.add_minutes(-Number(n));
        }
        subtract_hours(n) {
          return this.add_hours(-Number(n));
        }
        subtract_days(n) {
          return this.add_days(-Number(n));
        }
        subtract_weeks(n) {
          return this.add_weeks(-Number(n));
        }
        subtract_months(n) {
          return this.add_months(-Number(n));
        }
        subtract_years(n) {
          return this.add_years(-Number(n));
        }
        add(duration) {
          return this.add_seconds(
            Number(duration.seconds()) + Number(duration.minutes()) * 60 + Number(duration.hours()) * 3600
          )._calendarAdd({
            days: duration.days(),
            weeks: duration.weeks(),
            months: duration.months(),
            years: duration.years()
          });
        }
        subtract(duration) {
          return this.add(new Duration(-duration.seconds(), {
            minutes: -duration.minutes(),
            hours: -duration.hours(),
            days: -duration.days(),
            weeks: -duration.weeks(),
            months: -duration.months(),
            years: -duration.years()
          }));
        }
        elapsed_seconds_until(other) {
          return other.epoch() - this._epoch;
        }
        compare(other) {
          return this._epoch < other.epoch() ? -1 : this._epoch > other.epoch() ? 1 : 0;
        }
        is_before(other) {
          return this._epoch < other.epoch();
        }
        is_after(other) {
          return this._epoch > other.epoch();
        }
        datetime() {
          return this.strftime("%Y-%m-%dT%H:%M:%S");
        }
        to_String() {
          return this.datetime();
        }
        to_iso8601() {
          return this.to_rfc3339();
        }
        to_rfc3339() {
          const p = this._parts();
          return `${pad(p.year, 4)}-${pad(p.month)}-${pad(p.day)}T${pad(p.hour)}:${pad(p.minute)}:${pad(p.second)}${formatOffset(offsetForEpoch(this._epoch, this._timezone), true)}`;
        }
        to_rfc5322(options = {}) {
          const p = this._parts();
          const weekday = DAY_ABBR[weekdayIndex(p) - 1];
          const core = `${pad(p.day)} ${MONTHS[p.month - 1]} ${pad(p.year, 4)} ${pad(p.hour)}:${pad(p.minute)}:${pad(p.second)} ${formatOffset(offsetForEpoch(this._epoch, this._timezone), false)}`;
          return options.include_weekday === false ? core : `${weekday}, ${core}`;
        }
        format(timeFormat) {
          const time = timeFormat._timezone == null ? this : this.with_timezone(timeFormat._timezone);
          if (timeFormat._kind === "iso8601" || timeFormat._kind === "rfc3339") return time.to_rfc3339();
          if (timeFormat._kind === "rfc5322") return time.to_rfc5322();
          return time.strftime(timeFormat._pattern);
        }
        strftime(fmt) {
          const p = this._parts();
          const offset = offsetForEpoch(this._epoch, this._timezone);
          const parts = {
            Y: pad(p.year, 4),
            m: pad(p.month),
            d: pad(p.day),
            H: pad(p.hour),
            M: pad(p.minute),
            S: pad(p.second),
            z: formatOffset(offset, false),
            Z: this._timezone,
            "%": "%"
          };
          return String(fmt).replace(/%([%YmdHMSzZ])/g, (_match, key) => parts[key]);
        }
      };
      var TimeParser = class {
        constructor(_fmt = "%Y-%m-%d") {
          this._format = String(_fmt);
        }
        parse(text) {
          const m = String(text).match(/(?:[A-Za-z]+\.?\s+)?([0-9]{1,2})(?:st|nd|rd|th)\s+([A-Za-z]{3}),\s+([0-9]{4})/u);
          if (!m) {
            try {
              return new Time2(parseTimeText(String(text), "UTC", false).epoch, { timezone: "UTC" });
            } catch (_err) {
              throw new Error("Exception: unable to parse time string");
            }
          }
          const day = Number(m[1]);
          const mon = MONTH_BY_NAME.get(m[2].toLowerCase());
          const year = Number(m[3]);
          if (!mon) {
            throw new Error("Exception: unable to parse month");
          }
          return new Time2(sameWallEpoch({
            year,
            month: mon,
            day,
            hour: 0,
            minute: 0,
            second: 0
          }, "UTC"), { timezone: "UTC" });
        }
      };
      module2.exports = {
        Time: Time2,
        TimeZone,
        Duration,
        TimeFormat,
        TimeParser
      };
    }
  });

  // modules/std/marshal/cbor.js
  var require_cbor = __commonJS({
    "modules/std/marshal/cbor.js"(exports2, module2) {
      "use strict";
      var { BinaryString: BinaryString2, ZuzuBinary } = require_runtime_helpers();
      var MAX_SAFE_INTEGER = 9007199254740991;
      var SELF_DESCRIBED_TAG = 55799;
      var PUSH_BYTES_CHUNK = 16384;
      var CborTextString = class {
        constructor(value) {
          this.value = String(value ?? "");
        }
      };
      var CborByteString = class {
        constructor(value) {
          this.value = toUint8Array(value);
        }
      };
      var CborTagged = class {
        constructor(tagNumberValue, value) {
          this.tagNumber = Number(tagNumberValue);
          this.value = value;
        }
      };
      function textString(value) {
        return new CborTextString(value);
      }
      function byteString(value) {
        return new CborByteString(value);
      }
      function tag(tagNumberValue, value) {
        return new CborTagged(tagNumberValue, value);
      }
      function isTextString(value) {
        return value instanceof CborTextString;
      }
      function isByteString(value) {
        return value instanceof CborByteString;
      }
      function isTagged(value) {
        return value instanceof CborTagged;
      }
      function textValue(value) {
        if (!isTextString(value)) {
          throw new Error("Not a CBOR text string");
        }
        return value.value;
      }
      function bytesValue(value) {
        if (!isByteString(value)) {
          throw new Error("Not a CBOR byte string");
        }
        return new Uint8Array(value.value);
      }
      function tagNumber(value) {
        if (!isTagged(value)) {
          throw new Error("Not a CBOR tag");
        }
        return value.tagNumber;
      }
      function tagValue(value) {
        if (!isTagged(value)) {
          throw new Error("Not a CBOR tag");
        }
        return value.value;
      }
      function encodeOne(item) {
        const out = [];
        encodeItem(item, out);
        return new BinaryString2(Uint8Array.from(out));
      }
      function decodeOne(input) {
        const bytes = toUint8Array(input);
        const decoded = decodeItem(bytes, 0, true);
        if (decoded.offset !== bytes.length) {
          throw cborError("trailing bytes after item");
        }
        return decoded.value;
      }
      function validateProfile(input) {
        const bytes = toUint8Array(input);
        const offset = scanItem(bytes, 0, true);
        if (offset !== bytes.length) {
          throw cborError("trailing bytes after item");
        }
        return true;
      }
      function encodeItem(item, out) {
        if (item == null) {
          out.push(246);
          return;
        }
        if (item === false) {
          out.push(244);
          return;
        }
        if (item === true) {
          out.push(245);
          return;
        }
        if (typeof item === "number") {
          encodeNumber(item, out);
          return;
        }
        if (typeof item === "string" || item instanceof CborTextString) {
          const text = item instanceof CborTextString ? item.value : item;
          const bytes = new TextEncoder().encode(text);
          encodeUnsigned(3, bytes.length, out);
          pushBytes(out, bytes);
          return;
        }
        if (item instanceof CborByteString) {
          encodeUnsigned(2, item.value.length, out);
          pushBytes(out, item.value);
          return;
        }
        if (item instanceof CborTagged) {
          if (item.tagNumber !== SELF_DESCRIBED_TAG) {
            throw cborError(`unsupported tag ${item.tagNumber}`);
          }
          encodeUnsigned(6, item.tagNumber, out);
          encodeItem(item.value, out);
          return;
        }
        if (item instanceof Uint8Array || item instanceof ZuzuBinary) {
          const bytes = toUint8Array(item);
          encodeUnsigned(2, bytes.length, out);
          pushBytes(out, bytes);
          return;
        }
        if (Array.isArray(item)) {
          encodeUnsigned(4, item.length, out);
          for (const value of item) {
            encodeItem(value, out);
          }
          return;
        }
        if (item instanceof Map) {
          encodeUnsigned(5, item.size, out);
          for (const [key, value] of item.entries()) {
            encodeItem(key, out);
            encodeItem(value, out);
          }
          return;
        }
        if (typeof item === "object") {
          const entries = Object.entries(item);
          encodeUnsigned(5, entries.length, out);
          for (const [key, value] of entries) {
            encodeItem(new CborTextString(key), out);
            encodeItem(value, out);
          }
          return;
        }
        throw cborError(`unsupported value type ${typeof item}`);
      }
      function encodeNumber(value, out) {
        if (!Number.isFinite(value)) {
          throw cborError(Number.isNaN(value) ? "NaN is invalid" : "infinite float is invalid");
        }
        if (!Object.is(value, -0) && Number.isInteger(value) && Math.abs(value) <= MAX_SAFE_INTEGER) {
          if (value >= 0) {
            encodeUnsigned(0, value, out);
          } else {
            encodeUnsigned(1, -1 - value, out);
          }
          return;
        }
        out.push(251);
        const buffer = new ArrayBuffer(8);
        new DataView(buffer).setFloat64(0, value, false);
        pushBytes(out, new Uint8Array(buffer));
      }
      function encodeUnsigned(major, value, out) {
        if (!Number.isSafeInteger(value) || value < 0) {
          throw cborError("integer is outside supported range");
        }
        const prefix = major << 5;
        if (value <= 23) {
          out.push(prefix | value);
        } else if (value <= 255) {
          out.push(prefix | 24, value);
        } else if (value <= 65535) {
          out.push(prefix | 25, value >> 8, value & 255);
        } else if (value <= 4294967295) {
          out.push(
            prefix | 26,
            value >>> 24 & 255,
            value >>> 16 & 255,
            value >>> 8 & 255,
            value & 255
          );
        } else {
          out.push(prefix | 27);
          const high = Math.floor(value / 4294967296);
          const low = value >>> 0;
          out.push(
            high >>> 24 & 255,
            high >>> 16 & 255,
            high >>> 8 & 255,
            high & 255,
            low >>> 24 & 255,
            low >>> 16 & 255,
            low >>> 8 & 255,
            low & 255
          );
        }
      }
      function decodeItem(bytes, offset, topLevel) {
        requireAvailable(bytes, offset, 1, "initial byte");
        const initial = bytes[offset];
        const major = initial >> 5;
        const ai = initial & 31;
        offset++;
        if (ai === 31) {
          throw cborError("indefinite-length item");
        }
        if (ai >= 28 && ai <= 30) {
          throw cborError("reserved additional information");
        }
        if (major === 7) {
          return decodeSimpleOrFloat(bytes, offset, ai);
        }
        const argument = readArgument(bytes, offset, ai);
        const value = argument.value;
        offset = argument.offset;
        switch (major) {
          case 0:
            assertUnsignedNumberRange(value);
            return { value, offset };
          case 1:
            assertNegativeNumberRange(value);
            return { value: -1 - value, offset };
          case 2:
            requireAvailable(bytes, offset, value, "byte string payload");
            return {
              value: new CborByteString(bytes.subarray(offset, offset + value)),
              offset: offset + value
            };
          case 3: {
            requireAvailable(bytes, offset, value, "text string payload");
            const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(offset, offset + value));
            return { value: new CborTextString(text), offset: offset + value };
          }
          case 4: {
            const values = [];
            for (let i = 0; i < value; i++) {
              const item = decodeItem(bytes, offset, false);
              values.push(item.value);
              offset = item.offset;
            }
            return { value: values, offset };
          }
          case 5: {
            const map = /* @__PURE__ */ new Map();
            for (let i = 0; i < value; i++) {
              const key = decodeItem(bytes, offset, false);
              const mapValue = decodeItem(bytes, key.offset, false);
              map.set(key.value, mapValue.value);
              offset = mapValue.offset;
            }
            return { value: map, offset };
          }
          case 6: {
            if (!topLevel || value !== SELF_DESCRIBED_TAG) {
              throw cborError(`unsupported tag ${value}`);
            }
            const inner = decodeItem(bytes, offset, false);
            return {
              value: new CborTagged(value, inner.value),
              offset: inner.offset
            };
          }
          default:
            throw cborError("unsupported major type");
        }
      }
      function scanItem(bytes, offset, topLevel) {
        return decodeItem(bytes, offset, topLevel).offset;
      }
      function decodeSimpleOrFloat(bytes, offset, ai) {
        if (ai === 20) {
          return { value: false, offset };
        }
        if (ai === 21) {
          return { value: true, offset };
        }
        if (ai === 22) {
          return { value: null, offset };
        }
        if (ai === 25) {
          throw cborError("half-precision float is invalid");
        }
        if (ai === 26) {
          throw cborError("single-precision float is invalid");
        }
        if (ai === 27) {
          requireAvailable(bytes, offset, 8, "binary64 float");
          const value = new DataView(
            bytes.buffer,
            bytes.byteOffset + offset,
            8
          ).getFloat64(0, false);
          if (Number.isNaN(value)) {
            throw cborError("NaN is invalid");
          }
          if (!Number.isFinite(value)) {
            throw cborError("infinite float is invalid");
          }
          return { value, offset: offset + 8 };
        }
        throw cborError("unsupported simple value");
      }
      function readArgument(bytes, offset, ai) {
        if (ai <= 23) {
          return { value: ai, offset };
        }
        if (ai === 24) {
          requireAvailable(bytes, offset, 1, "uint8 argument");
          const value = bytes[offset];
          assertShortestArgument(value, 24);
          return { value, offset: offset + 1 };
        }
        if (ai === 25) {
          requireAvailable(bytes, offset, 2, "uint16 argument");
          const value = bytes[offset] << 8 | bytes[offset + 1];
          assertShortestArgument(value, 256);
          return { value, offset: offset + 2 };
        }
        if (ai === 26) {
          requireAvailable(bytes, offset, 4, "uint32 argument");
          const value = bytes[offset] * 16777216 + (bytes[offset + 1] << 16) + (bytes[offset + 2] << 8) + bytes[offset + 3];
          assertShortestArgument(value, 65536);
          return { value, offset: offset + 4 };
        }
        if (ai === 27) {
          requireAvailable(bytes, offset, 8, "uint64 argument");
          const high = bytes[offset] * 16777216 + (bytes[offset + 1] << 16) + (bytes[offset + 2] << 8) + bytes[offset + 3];
          const low = bytes[offset + 4] * 16777216 + (bytes[offset + 5] << 16) + (bytes[offset + 6] << 8) + bytes[offset + 7];
          const value = high * 4294967296 + low;
          assertShortestArgument(value, 4294967296);
          return { value, offset: offset + 8 };
        }
        throw cborError("unsupported additional information");
      }
      function assertShortestArgument(value, minimum) {
        if (value < minimum) {
          throw cborError("non-shortest integer encoding");
        }
      }
      function assertUnsignedNumberRange(value) {
        if (value > MAX_SAFE_INTEGER) {
          throw cborError("integer is outside Zuzu Number range");
        }
      }
      function assertNegativeNumberRange(value) {
        if (value >= MAX_SAFE_INTEGER) {
          throw cborError("integer is outside Zuzu Number range");
        }
      }
      function requireAvailable(bytes, offset, length, context) {
        if (offset + length > bytes.length) {
          throw cborError(`incomplete ${context}`);
        }
      }
      function pushBytes(out, bytes) {
        for (let offset = 0; offset < bytes.length; offset += PUSH_BYTES_CHUNK) {
          out.push(...bytes.subarray(offset, offset + PUSH_BYTES_CHUNK));
        }
      }
      function toUint8Array(value) {
        if (value instanceof ZuzuBinary) {
          return new Uint8Array(value.bytes);
        }
        if (value instanceof Uint8Array) {
          return new Uint8Array(value);
        }
        if (Array.isArray(value)) {
          return Uint8Array.from(value.map((item) => Number(item) & 255));
        }
        if (value && value.buffer instanceof ArrayBuffer) {
          return new Uint8Array(value.buffer, value.byteOffset || 0, value.byteLength);
        }
        throw new Error("TypeException: CBOR adapter expects BinaryString or Uint8Array bytes");
      }
      function cborError(message) {
        return new Error(`CBOR profile error: ${message}`);
      }
      module2.exports = {
        CborTextString,
        CborByteString,
        CborTagged,
        SELF_DESCRIBED_TAG,
        byteString,
        bytesValue,
        decodeOne,
        encodeOne,
        isByteString,
        isTagged,
        isTextString,
        tag,
        tagNumber,
        tagValue,
        textString,
        textValue,
        validateProfile
      };
    }
  });

  // lib/gui/dom-renderer.js
  var require_dom_renderer = __commonJS({
    "lib/gui/dom-renderer.js"(exports2, module2) {
      "use strict";
      function installSafeDefineProperties() {
        if (Object.__zuzu_safe_define_properties) {
          return;
        }
        const nativeDefineProperty = Object.defineProperty;
        const nativeDefineProperties = Object.defineProperties;
        function safeDescriptor(descriptor) {
          if (!descriptor || typeof descriptor !== "object") {
            return descriptor;
          }
          const safe = /* @__PURE__ */ Object.create(null);
          for (const key of [
            "value",
            "get",
            "set",
            "writable",
            "enumerable",
            "configurable"
          ]) {
            if (Object.prototype.hasOwnProperty.call(descriptor, key)) {
              safe[key] = descriptor[key];
            }
          }
          return safe;
        }
        Object.defineProperty = function zuzuSafeDefineProperty(obj, prop, descriptor) {
          return nativeDefineProperty(obj, prop, safeDescriptor(descriptor));
        };
        Object.defineProperties = function zuzuSafeDefineProperties(obj, descriptors) {
          const safe = /* @__PURE__ */ Object.create(null);
          for (const key of Object.keys(descriptors || {})) {
            safe[key] = safeDescriptor(descriptors[key]);
          }
          return nativeDefineProperties(obj, safe);
        };
        nativeDefineProperty(Object, "__zuzu_safe_define_properties", {
          value: true,
          enumerable: false,
          configurable: false
        });
      }
      var activeState = null;
      function rendererState() {
        if (!activeState) {
          throw new Error("Zuzu GUI DOM renderer is not active");
        }
        return activeState;
      }
      function rendererDocument() {
        const state = rendererState();
        return state.document || document;
      }
      function itemLabel(item) {
        if (item == null) {
          return "";
        }
        if (typeof item === "string" || typeof item === "number") {
          return String(item);
        }
        return String(item.label ?? item.value ?? "");
      }
      function itemValue(item) {
        if (item == null) {
          return "";
        }
        if (typeof item === "string" || typeof item === "number") {
          return String(item);
        }
        return item.value ?? itemLabel(item);
      }
      function itemChildren(item) {
        return Array.isArray(item && item.children) ? item.children : [];
      }
      function pathKey(path) {
        return Array.isArray(path) ? path.map(Number).join(",") : "";
      }
      function sendWidgetEvent(type, node, extra = {}) {
        const state = node.__zuzuRendererState || rendererState();
        if (state.sendEvent) {
          state.sendEvent({
            windowId: state.windowId,
            type,
            widgetGuid: node.dataset.guid || null,
            ...extra
          });
          return;
        }
        if (!window.zuzuGui) {
          return;
        }
        window.zuzuGui.sendEvent({
          windowId: state.windowId,
          type,
          widgetGuid: node.dataset.guid || null,
          ...extra
        });
      }
      function sendThrottledWidgetEvent(type, node, extraFactory) {
        if (node.__zuzuPendingEvent) {
          node.__zuzuPendingEvent.extraFactory = extraFactory;
          return;
        }
        node.__zuzuPendingEvent = { extraFactory };
        setTimeout(() => {
          const pending = node.__zuzuPendingEvent;
          node.__zuzuPendingEvent = null;
          sendWidgetEvent(type, node, pending.extraFactory());
        }, 50);
      }
      function applyCommonProps(element, snapshot) {
        const props = snapshot.props || {};
        element.dataset.guid = snapshot.guid || "";
        element.hidden = props.visible === false;
        element.className = "";
        if (snapshot.classes && snapshot.classes.length > 0) {
          element.classList.add(...snapshot.classes);
        }
        if (snapshot.id) {
          element.id = snapshot.id;
        } else {
          element.removeAttribute("id");
        }
        if (props.disabled) {
          element.setAttribute("aria-disabled", "true");
          if ("disabled" in element) {
            element.disabled = true;
          }
        } else {
          element.removeAttribute("aria-disabled");
          if ("disabled" in element) {
            element.disabled = false;
          }
        }
        for (const [key, cssName] of [
          ["width", "width"],
          ["height", "height"],
          ["minwidth", "minWidth"],
          ["minheight", "minHeight"],
          ["maxwidth", "maxWidth"],
          ["maxheight", "maxHeight"]
        ]) {
          if (props[key] != null && props[key] !== "") {
            element.style[cssName] = `${Number(props[key]) || 0}px`;
          } else {
            element.style[cssName] = "";
          }
        }
      }
      function applyBoxStyle(element, snapshot) {
        const props = snapshot.props || {};
        element.classList.add(snapshot.type === "HBox" ? "zuzu-hbox" : "zuzu-vbox");
        element.style.display = "flex";
        element.style.flexDirection = snapshot.type === "HBox" ? "row" : "column";
        if (props.gap != null) {
          element.style.gap = `${Number(props.gap) || 0}px`;
        }
        if (props.padding != null) {
          element.style.padding = `${Number(props.padding) || 0}px`;
        }
      }
      function applySpecificProps(element, snapshot) {
        const type = snapshot.type || "Widget";
        const props = snapshot.props || {};
        if (type === "Window") {
          return;
        }
        if (type === "Frame") {
          let legend = element.querySelector(":scope > legend");
          if (!legend) {
            legend = rendererDocument().createElement("legend");
            element.prepend(legend);
          }
          legend.textContent = props.label || "";
          element.classList.toggle("zuzu-collapsed", props.collapsed === true);
          return;
        }
        if (type === "VBox" || type === "HBox") {
          applyBoxStyle(element, snapshot);
          return;
        }
        if (type === "Label") {
          element.textContent = props.text || "";
          if (props.for_id) {
            element.htmlFor = props.for_id;
          }
          return;
        }
        if (type === "Text") {
          element.textContent = props.text || props.value || "";
          element.style.whiteSpace = props.wrap === false ? "pre" : "pre-wrap";
          return;
        }
        if (type === "RichText") {
          element.innerHTML = props.value || "";
          return;
        }
        if (type === "Image") {
          element.src = props.src || "";
          element.alt = props.alt || "";
          element.style.objectFit = props.fit === "stretch" ? "fill" : props.fit || "contain";
          return;
        }
        if (type === "Input") {
          setInputValue(element, props.value || "");
          element.placeholder = props.placeholder || "";
          element.readOnly = props.readonly === true;
          element.required = props.required === true;
          if ("type" in element) {
            element.type = props.password ? "password" : "text";
          }
          return;
        }
        if (type === "DatePicker") {
          setInputValue(element, props.value || "");
          element.placeholder = "YYYY-MM-DD";
          element.pattern = "\\d{4}-\\d{2}-\\d{2}";
          element.dataset.min = props.min || "";
          element.dataset.max = props.max || "";
          return;
        }
        if (type === "Checkbox" || type === "Radio") {
          const input = element.querySelector("input");
          const label = element.querySelector("span");
          input.checked = props.checked === true;
          input.indeterminate = props.indeterminate === true;
          input.value = props.value || "";
          input.name = props.name || props.group || "";
          label.textContent = props.label || "";
          return;
        }
        if (type === "RadioGroup") {
          const radios = element.querySelectorAll(':scope input[type="radio"]');
          for (const radio of radios) {
            radio.name = snapshot.guid || "";
          }
          return;
        }
        if (type === "Select") {
          renderSelectOptions(element, props);
          element.value = props.value == null ? "" : String(props.value);
          element.multiple = props.multiple === true;
          return;
        }
        if (type === "Separator") {
          element.classList.toggle("zuzu-vertical-separator", props.orientation === "vertical");
          return;
        }
        if (type === "Slider") {
          setInputValue(element, props.value ?? 0);
          element.min = props.min ?? 0;
          element.max = props.max ?? 100;
          element.step = props.step ?? 1;
          element.disabled = props.disabled === true || props.readonly === true;
          return;
        }
        if (type === "Progress") {
          element.value = Number(props.value ?? 0);
          element.max = Number(props.max ?? 100);
          element.classList.toggle("zuzu-indeterminate", props.indeterminate === true);
          element.title = props.show_text ? `${element.value} / ${element.max}` : "";
          return;
        }
        if (type === "Tabs") {
          element.dataset.selected = props.selected || "";
          for (const child of Array.from(element.children)) {
            if (child.__zuzuGuiType === "Tab") {
              child.open = child.dataset.value === element.dataset.selected;
            }
          }
          return;
        }
        if (type === "Tab") {
          element.open = props.selected === true;
          element.dataset.value = props.value || "";
          element.querySelector("summary").textContent = props.title || props.value || "";
          return;
        }
        if (type === "ListView") {
          renderListView(element, props);
          return;
        }
        if (type === "TreeView") {
          renderTreeView(element, props);
          return;
        }
        if (type === "Menu") {
          let label = element.__zuzuMenuLabel;
          if (!label) {
            label = rendererDocument().createElement("span");
            label.className = "zuzu-menu-label";
            label.__zuzuRendererState = rendererState();
            element.__zuzuMenuLabel = label;
            element.insertBefore(label, element.children[0] || null);
          }
          label.textContent = props.text || "";
          return;
        }
        if (type === "Button" || type === "MenuItem") {
          element.textContent = props.text || "";
        }
      }
      function setInputValue(element, value) {
        const text = String(value ?? "");
        if (element.value === text) {
          return;
        }
        const focused = rendererDocument().activeElement === element;
        const selectionStart = focused ? element.selectionStart : null;
        const selectionEnd = focused ? element.selectionEnd : null;
        element.value = text;
        if (focused && typeof element.setSelectionRange === "function" && selectionStart != null && selectionEnd != null) {
          const start = Math.min(selectionStart, text.length);
          const end = Math.min(selectionEnd, text.length);
          element.setSelectionRange(start, end);
        }
      }
      function createElement(snapshot) {
        const type = snapshot.type || "Widget";
        let element;
        if (type === "Window") {
          element = rendererDocument().createElement("main");
        } else if (type === "Frame") {
          element = rendererDocument().createElement("fieldset");
        } else if (type === "VBox" || type === "HBox") {
          element = rendererDocument().createElement("div");
        } else if (type === "Label") {
          element = rendererDocument().createElement("label");
        } else if (type === "Text" || type === "RichText") {
          element = rendererDocument().createElement("div");
          element.addEventListener("click", () => {
            sendWidgetEvent("click", element);
          });
        } else if (type === "Image") {
          element = rendererDocument().createElement("img");
          element.addEventListener("click", () => {
            sendWidgetEvent("click", element);
          });
        } else if (type === "Input") {
          element = snapshot.props && snapshot.props.multiline ? rendererDocument().createElement("textarea") : rendererDocument().createElement("input");
          element.addEventListener("input", () => {
            sendWidgetEvent("input", element, { value: element.value });
          });
          element.addEventListener("change", () => {
            sendWidgetEvent("change", element, { value: element.value });
          });
        } else if (type === "DatePicker") {
          element = rendererDocument().createElement("input");
          element.type = "text";
          element.inputMode = "numeric";
          element.autocomplete = "off";
          element.addEventListener("input", () => {
            sendWidgetEvent("input", element, { value: element.value });
          });
          element.addEventListener("change", () => {
            sendWidgetEvent("change", element, { value: element.value });
          });
        } else if (type === "Checkbox" || type === "Radio") {
          element = rendererDocument().createElement("label");
          element.className = "zuzu-check-control";
          const input = rendererDocument().createElement("input");
          input.type = type === "Radio" ? "radio" : "checkbox";
          const label = rendererDocument().createElement("span");
          element.append(input, label);
          input.addEventListener("change", () => {
            const eventTarget = type === "Radio" && element.dataset.parentGuid ? element.dataset.parentGuid : element.dataset.guid;
            sendWidgetEvent("change", element, {
              widgetGuid: eventTarget,
              checked: input.checked,
              value: input.value
            });
          });
        } else if (type === "Select") {
          element = rendererDocument().createElement("select");
          element.addEventListener("change", () => {
            sendWidgetEvent("change", element, { value: element.value });
          });
        } else if (type === "Button" || type === "MenuItem") {
          element = rendererDocument().createElement("button");
          element.type = "button";
          element.addEventListener("click", () => {
            sendWidgetEvent("click", element);
          });
        } else if (type === "Menu") {
          element = rendererDocument().createElement("nav");
        } else if (type === "Separator") {
          element = rendererDocument().createElement("hr");
        } else if (type === "Slider") {
          element = rendererDocument().createElement("input");
          element.type = "range";
          element.addEventListener("input", () => {
            sendThrottledWidgetEvent("input", element, () => ({
              value: Number(element.value)
            }));
          });
          element.addEventListener("change", () => {
            sendWidgetEvent("change", element, { value: Number(element.value) });
          });
        } else if (type === "Progress") {
          element = rendererDocument().createElement("progress");
        } else if (type === "Tabs") {
          element = rendererDocument().createElement("div");
          element.className = "zuzu-tabs";
        } else if (type === "Tab") {
          element = rendererDocument().createElement("details");
          const summary = rendererDocument().createElement("summary");
          element.appendChild(summary);
          summary.addEventListener("click", (event) => {
            event.preventDefault();
            const parent = element.parentNode;
            if (parent) {
              for (const child of Array.from(parent.children)) {
                if (child.__zuzuGuiType === "Tab") {
                  child.open = child === element;
                }
              }
            }
            element.open = true;
            sendWidgetEvent("select", element, {
              widgetGuid: element.dataset.parentGuid || element.dataset.guid,
              selected: element.dataset.value || "",
              value: element.dataset.value || ""
            });
          });
        } else if (type === "ListView" || type === "TreeView") {
          element = rendererDocument().createElement("div");
          element.tabIndex = 0;
        } else {
          element = rendererDocument().createElement("div");
        }
        element.__zuzuRendererState = rendererState();
        element.__zuzuGuiType = type;
        element.__zuzuGuiSubType = type === "Input" && snapshot.props && snapshot.props.multiline ? "multiline" : "";
        return element;
      }
      function renderNode(snapshot) {
        const element = createElement(snapshot);
        applyCommonProps(element, snapshot);
        applySpecificProps(element, snapshot);
        rendererState().nodes.set(snapshot.guid, element);
        for (const child of snapshot.children || []) {
          if (snapshot.type === "Window" && child.type === "Menu" && !rendererState().renderMenus) {
            continue;
          }
          const childElement = renderNode(child);
          childElement.dataset.parentGuid = snapshot.guid || "";
          if (snapshot.type === "RadioGroup" && child.type === "Radio") {
            const radio = childElement.querySelector('input[type="radio"]');
            if (radio) {
              radio.name = snapshot.guid || "";
            }
          }
          element.appendChild(childElement);
        }
        return element;
      }
      function renderSelectOptions(element, props) {
        element.replaceChildren();
        for (const item of props.options || []) {
          const option = rendererDocument().createElement("option");
          option.textContent = itemLabel(item);
          option.value = String(itemValue(item));
          option.disabled = item && item.disabled === true;
          element.appendChild(option);
        }
      }
      function renderListView(element, props) {
        element.classList.add("zuzu-listview");
        element.replaceChildren();
        const list = rendererDocument().createElement("ul");
        const selected = props.selected_index == null ? null : Number(props.selected_index);
        (props.items || []).forEach((item, index) => {
          const row = rendererDocument().createElement("li");
          row.textContent = itemLabel(item);
          row.dataset.index = String(index);
          row.classList.toggle("selected", index === selected);
          row.addEventListener("click", () => {
            markListSelected(element, index);
            sendWidgetEvent("select", element, { selected_index: index });
          });
          row.addEventListener("dblclick", () => {
            markListSelected(element, index);
            sendWidgetEvent("activate", element, { selected_index: index });
          });
          list.appendChild(row);
        });
        element.appendChild(list);
      }
      function markListSelected(element, index) {
        for (const row of element.querySelectorAll("li")) {
          row.classList.toggle("selected", Number(row.dataset.index) === Number(index));
        }
      }
      function renderTreeView(element, props) {
        element.classList.add("zuzu-treeview");
        element.replaceChildren();
        const selected = pathKey(props.selected_path || []);
        const expanded = new Set((props.expanded_paths || []).map(pathKey));
        element.appendChild(renderTreeItems(props.items || [], [], selected, expanded, element));
      }
      function renderTreeItems(items, prefix, selected, expanded, owner) {
        const list = rendererDocument().createElement("ul");
        items.forEach((item, index) => {
          const path = [...prefix, index];
          const key = pathKey(path);
          const children = itemChildren(item);
          const row = rendererDocument().createElement("li");
          if (children.length > 0) {
            const details = rendererDocument().createElement("details");
            details.open = expanded.has(key);
            const summary = rendererDocument().createElement("summary");
            summary.textContent = itemLabel(item);
            summary.dataset.path = key;
            summary.classList.toggle("selected", key === selected);
            summary.addEventListener("click", () => {
              markTreeSelected(owner, key);
              sendWidgetEvent("select", owner, { selected_path: path });
            });
            summary.addEventListener("dblclick", () => {
              markTreeSelected(owner, key);
              sendWidgetEvent("activate", owner, { selected_path: path });
            });
            details.addEventListener("toggle", () => {
              sendWidgetEvent(details.open ? "expand" : "collapse", owner, {
                selected_path: path
              });
            });
            details.append(summary, renderTreeItems(children, path, selected, expanded, owner));
            row.appendChild(details);
          } else {
            const button = rendererDocument().createElement("button");
            button.type = "button";
            button.textContent = itemLabel(item);
            button.dataset.path = key;
            button.classList.toggle("selected", key === selected);
            button.addEventListener("click", () => {
              markTreeSelected(owner, key);
              sendWidgetEvent("select", owner, { selected_path: path });
            });
            button.addEventListener("dblclick", () => {
              markTreeSelected(owner, key);
              sendWidgetEvent("activate", owner, { selected_path: path });
            });
            row.appendChild(button);
          }
          list.appendChild(row);
        });
        return list;
      }
      function markTreeSelected(element, key) {
        for (const node of element.querySelectorAll("[data-path]")) {
          node.classList.toggle("selected", node.dataset.path === key);
        }
      }
      function replaceNode(snapshot) {
        const old = rendererState().nodes.get(snapshot.guid);
        if (!old) {
          return;
        }
        const parent = old.parentNode;
        const next = renderNode(snapshot);
        forgetNode(old);
        parent.replaceChild(next, old);
      }
      function forgetNode(node) {
        const guid = node && node.dataset ? node.dataset.guid : null;
        if (guid) {
          rendererState().nodes.delete(guid);
        }
        for (const child of Array.from(node.children || [])) {
          forgetNode(child);
        }
      }
      function updateNode(snapshot) {
        const element = rendererState().nodes.get(snapshot.guid);
        if (!element) {
          return;
        }
        if (element.__zuzuGuiType !== (snapshot.type || "Widget")) {
          replaceNode(snapshot);
          return;
        }
        if (element.__zuzuGuiType === "Input" && element.__zuzuGuiSubType !== (snapshot.props && snapshot.props.multiline ? "multiline" : "")) {
          replaceNode(snapshot);
          return;
        }
        applyCommonProps(element, snapshot);
        applySpecificProps(element, snapshot);
      }
      function createZuzuGuiDomRenderer(options = {}) {
        installSafeDefineProperties();
        const doc = options.document || options.root && options.root.ownerDocument || document;
        const root = options.root || doc.getElementById(options.rootId || "app");
        if (!root) {
          throw new Error("Zuzu GUI DOM renderer requires a root element");
        }
        const state = {
          document: doc,
          windowId: null,
          nodes: /* @__PURE__ */ new Map(),
          root,
          sendEvent: typeof options.sendEvent === "function" ? options.sendEvent : null,
          renderMenus: options.renderMenus === true
        };
        function withState(fn2) {
          const previous = activeState;
          activeState = state;
          try {
            return fn2();
          } finally {
            activeState = previous;
          }
        }
        return {
          render(payload = {}) {
            return withState(() => {
              state.windowId = payload.windowId;
              state.nodes.clear();
              root.replaceChildren(renderNode(payload.snapshot));
            });
          },
          create(payload = {}) {
            return withState(() => {
              if (payload.snapshot && payload.snapshot.type === "Menu" && !state.renderMenus) {
                return;
              }
              const parent = state.nodes.get(payload.parentGuid);
              if (!parent) {
                return;
              }
              const node = renderNode(payload.snapshot);
              const index = Number.isInteger(payload.index) ? payload.index : null;
              if (index == null || index >= parent.children.length) {
                parent.appendChild(node);
              } else {
                parent.insertBefore(node, parent.children[index]);
              }
            });
          },
          update(payload = {}) {
            return withState(() => {
              if (!payload.snapshot) {
                return;
              }
              if ((payload.snapshot.type === "Menu" || payload.snapshot.type === "MenuItem") && !state.renderMenus) {
                return;
              }
              updateNode(payload.snapshot);
            });
          },
          destroy(payload = {}) {
            return withState(() => {
              const node = state.nodes.get(payload.widgetGuid);
              if (node && node.parentNode) {
                node.parentNode.removeChild(node);
              }
              if (node) {
                forgetNode(node);
              }
            });
          },
          nodeForGuid(guid) {
            return state.nodes.get(guid) || null;
          }
        };
      }
      if (typeof module2 !== "undefined" && module2.exports) {
        module2.exports = {
          createZuzuGuiDomRenderer
        };
      }
      if (typeof window !== "undefined") {
        window.ZuzuGuiDomRenderer = {
          createZuzuGuiDomRenderer
        };
      }
    }
  });

  // lib/browser-gui-renderer.js
  var require_browser_gui_renderer = __commonJS({
    "lib/browser-gui-renderer.js"(exports2, module2) {
      "use strict";
      var {
        createZuzuGuiDomRenderer
      } = require_dom_renderer();
      var DEFAULT_ROOT_ID = "zuzu-browser-gui";
      var STYLE_ID = "zuzu-browser-gui-style";
      function createBrowserGuiRenderer(options = {}) {
        return createZuzuGuiDomRenderer({
          document: options.document,
          root: options.root,
          rootId: options.rootId,
          renderMenus: options.renderMenus,
          sendEvent: options.sendEvent
        });
      }
      function browserDocument(options) {
        if (options.document) {
          return options.document;
        }
        if (typeof document !== "undefined") {
          return document;
        }
        throw new Error("Zuzu browser GUI requires a DOM document");
      }
      function resolveRoot(doc, options) {
        if (options.root) {
          return options.root;
        }
        const rootId = options.rootId || DEFAULT_ROOT_ID;
        let root = doc.getElementById ? doc.getElementById(rootId) : null;
        if (root) {
          return root;
        }
        root = doc.createElement("div");
        root.id = rootId;
        root.className = "zuzu-browser-gui-root";
        const parent = doc.body || doc.documentElement;
        if (!parent) {
          throw new Error("Zuzu browser GUI requires document.body");
        }
        parent.appendChild(root);
        return root;
      }
      function installStyles(doc) {
        if (!doc.createElement || !doc.head) {
          return;
        }
        if (doc.getElementById && doc.getElementById(STYLE_ID)) {
          return;
        }
        const style = doc.createElement("style");
        style.id = STYLE_ID;
        style.textContent = [
          ".zuzu-browser-gui-root{position:fixed;inset:0;pointer-events:none;",
          "z-index:2147480000;font:13px/1.4 system-ui,sans-serif;color:#202124;}",
          ".zuzu-browser-window{position:absolute;display:flex;flex-direction:column;",
          "min-width:220px;min-height:120px;background:#fff;border:1px solid #8c939f;",
          "box-shadow:0 12px 36px rgba(0,0,0,.22);pointer-events:auto;}",
          ".zuzu-browser-window-titlebar{display:flex;align-items:center;gap:8px;",
          "height:32px;padding:0 6px 0 10px;background:#e9edf3;border-bottom:1px solid #c8ced8;",
          "user-select:none;cursor:default;}",
          ".zuzu-browser-window-title{flex:1;overflow:hidden;text-overflow:ellipsis;",
          "white-space:nowrap;font-weight:600;}",
          ".zuzu-browser-window-close{width:24px;height:24px;border:0;background:transparent;",
          "font:16px/1 system-ui,sans-serif;cursor:pointer;}",
          ".zuzu-browser-window-close:hover{background:#d8dde6;}",
          ".zuzu-browser-window-content{flex:1;min-height:0;overflow:auto;padding:12px;}",
          ".zuzu-browser-window-content>main{display:flex;flex-direction:column;gap:8px;}",
          ".zuzu-browser-window nav{display:flex;gap:4px;padding:4px 8px;",
          "border-bottom:1px solid #d7dbe2;background:#f7f8fa;}",
          ".zuzu-browser-window .zuzu-menu-label{padding:4px 8px;font-weight:600;}",
          ".zuzu-browser-window nav button{border:1px solid transparent;background:transparent;",
          "padding:4px 8px;cursor:pointer;}",
          ".zuzu-browser-window nav button:hover{border-color:#c4c9d2;background:#fff;}"
        ].join("");
        doc.head.appendChild(style);
      }
      function snapshotTitle(snapshot) {
        const props = snapshot && snapshot.props ? snapshot.props : {};
        return String(props.title || "Zuzu Window");
      }
      function snapshotDimension(snapshot, name2, fallback) {
        const props = snapshot && snapshot.props ? snapshot.props : {};
        const value = Number(props[name2]);
        return Number.isFinite(value) && value > 0 ? value : fallback;
      }
      var WINDOW_FRAME_PROPS = /* @__PURE__ */ new Set([
        "height",
        "maxheight",
        "maxwidth",
        "minheight",
        "minwidth",
        "width"
      ]);
      function contentSnapshot(snapshot) {
        if (!snapshot || snapshot.type !== "Window" || !snapshot.props) {
          return snapshot;
        }
        const props = { ...snapshot.props };
        for (const key of WINDOW_FRAME_PROPS) {
          delete props[key];
        }
        return {
          ...snapshot,
          props
        };
      }
      function optionValue(options, key, fallback = null) {
        if (options && typeof options.get === "function") {
          return options.get(key, fallback);
        }
        if (options && Object.prototype.hasOwnProperty.call(options, key)) {
          return options[key];
        }
        return fallback;
      }
      function optionString2(options, key, fallback = "") {
        const value = optionValue(options, key, fallback);
        return value == null ? value : String(value);
      }
      function browserDialogHost(doc, options) {
        if (options.dialogs && typeof options.dialogs === "object") {
          return options.dialogs;
        }
        if (options.window && typeof options.window === "object") {
          return options.window;
        }
        if (doc.defaultView && typeof doc.defaultView === "object") {
          return doc.defaultView;
        }
        if (typeof window !== "undefined" && window) {
          return window;
        }
        if (typeof globalThis !== "undefined" && globalThis) {
          return globalThis;
        }
        return {};
      }
      function removeNode(node) {
        if (node && node.parentNode) {
          node.parentNode.removeChild(node);
        }
      }
      function createBrowserGuiBridge(options = {}) {
        const doc = browserDocument(options);
        const root = resolveRoot(doc, options);
        installStyles(doc);
        let nextWindowId = 1;
        let nextZIndex = Number(options.baseZIndex || 100);
        const windows = /* @__PURE__ */ new Map();
        const dialogs = browserDialogHost(doc, options);
        function focusWindow(id) {
          const win = windows.get(Number(id));
          if (!win) {
            return;
          }
          win.frame.style.zIndex = String(nextZIndex++);
          if (typeof win.frame.focus === "function") {
            win.frame.focus();
          }
        }
        function closeNativeWindow(id, notifyClosed = true) {
          const win = windows.get(Number(id));
          if (!win) {
            return;
          }
          windows.delete(Number(id));
          removeNode(win.frame);
          if (notifyClosed && typeof win.options.onClosed === "function") {
            win.options.onClosed();
          }
        }
        function requestClose(id) {
          const win = windows.get(Number(id));
          if (!win) {
            return;
          }
          let cancelled = false;
          if (typeof win.options.onCloseRequest === "function") {
            cancelled = win.options.onCloseRequest() === true;
          }
          if (cancelled) {
            return;
          }
          closeNativeWindow(id);
        }
        function createFrame(id, snapshot) {
          const width = snapshotDimension(snapshot, "width", 480);
          const height = snapshotDimension(snapshot, "height", 320);
          const title = snapshotTitle(snapshot);
          const frame = doc.createElement("div");
          frame.className = "zuzu-browser-window";
          frame.dataset.windowId = String(id);
          frame.setAttribute("role", "dialog");
          frame.setAttribute("aria-label", title);
          frame.tabIndex = -1;
          frame.style.width = `${width}px`;
          frame.style.height = `${height}px`;
          frame.style.left = `${24 + (id - 1) % 8 * 28}px`;
          frame.style.top = `${24 + (id - 1) % 8 * 24}px`;
          frame.addEventListener("mousedown", () => focusWindow(id));
          const titlebar = doc.createElement("div");
          titlebar.className = "zuzu-browser-window-titlebar";
          const titleText = doc.createElement("span");
          titleText.className = "zuzu-browser-window-title";
          titleText.textContent = title;
          const close = doc.createElement("button");
          close.className = "zuzu-browser-window-close";
          close.type = "button";
          close.setAttribute("aria-label", `Close ${title}`);
          close.textContent = "x";
          close.addEventListener("click", () => requestClose(id));
          titlebar.append(titleText, close);
          const content = doc.createElement("div");
          content.className = "zuzu-browser-window-content";
          frame.append(titlebar, content);
          return {
            frame,
            content,
            titleText
          };
        }
        return {
          windows,
          openWindow(snapshot, bridgeOptions = {}) {
            const id = nextWindowId++;
            const frameParts = createFrame(id, snapshot);
            const renderer = createBrowserGuiRenderer({
              document: doc,
              root: frameParts.content,
              renderMenus: true,
              sendEvent(payload) {
                if (typeof bridgeOptions.onEvent === "function") {
                  bridgeOptions.onEvent(payload);
                }
              }
            });
            windows.set(id, {
              id,
              snapshot,
              options: bridgeOptions,
              renderer,
              ...frameParts
            });
            root.appendChild(frameParts.frame);
            renderer.render({
              windowId: id,
              snapshot: contentSnapshot(snapshot)
            });
            focusWindow(id);
            return id;
          },
          closeWindow(id) {
            closeNativeWindow(id);
          },
          createWidget(id, parentGuid, snapshot, index) {
            const win = windows.get(Number(id));
            if (win) {
              win.renderer.create({
                parentGuid,
                snapshot,
                index
              });
            }
          },
          updateWidget(id, snapshot) {
            const win = windows.get(Number(id));
            if (!win) {
              return;
            }
            if (snapshot && snapshot.type === "Window") {
              win.snapshot = snapshot;
              const title = snapshotTitle(snapshot);
              win.titleText.textContent = title;
              win.frame.setAttribute("aria-label", title);
              win.frame.style.width = `${snapshotDimension(snapshot, "width", 480)}px`;
              win.frame.style.height = `${snapshotDimension(snapshot, "height", 320)}px`;
              return;
            }
            win.renderer.update({
              snapshot
            });
          },
          destroyWidget(id, widgetGuid) {
            const win = windows.get(Number(id));
            if (win) {
              win.renderer.destroy({
                widgetGuid
              });
            }
          },
          alert(message, optionsForDialog = {}) {
            if (typeof dialogs.alert === "function") {
              dialogs.alert(String(message ?? ""));
            }
            return true;
          },
          confirm(message, optionsForDialog = {}) {
            if (typeof dialogs.confirm === "function") {
              return dialogs.confirm(String(message ?? "")) ? true : false;
            }
            return optionValue(optionsForDialog, "default", false) ? true : false;
          },
          prompt(message, optionsForDialog = {}) {
            const defaultValue = optionString2(
              optionsForDialog,
              "value",
              optionString2(optionsForDialog, "default", "")
            );
            if (typeof dialogs.prompt === "function") {
              return dialogs.prompt(String(message ?? ""), defaultValue);
            }
            return defaultValue;
          },
          colourPicker(optionsForDialog = {}) {
            const defaultValue = optionString2(
              optionsForDialog,
              "value",
              "#000000"
            );
            if (typeof dialogs.colourPicker === "function") {
              return dialogs.colourPicker(defaultValue, optionsForDialog);
            }
            if (typeof dialogs.colorPicker === "function") {
              return dialogs.colorPicker(defaultValue, optionsForDialog);
            }
            if (typeof dialogs.prompt === "function") {
              const answer = dialogs.prompt(
                optionString2(optionsForDialog, "label", "Colour:"),
                defaultValue
              );
              return answer == null ? defaultValue : answer;
            }
            return defaultValue;
          },
          fileOpen() {
            throw new Error(
              "GUI_DIALOGUE_UNSUPPORTED: file dialogues are unsupported in JS/Browser"
            );
          },
          fileSave() {
            throw new Error(
              "GUI_DIALOGUE_UNSUPPORTED: file dialogues are unsupported in JS/Browser"
            );
          },
          directoryOpen() {
            throw new Error(
              "GUI_DIALOGUE_UNSUPPORTED: directory dialogues are unsupported in JS/Browser"
            );
          },
          directorySave() {
            throw new Error(
              "GUI_DIALOGUE_UNSUPPORTED: directory dialogues are unsupported in JS/Browser"
            );
          },
          focusWindow
        };
      }
      module2.exports = {
        createBrowserGuiBridge,
        createBrowserGuiRenderer
      };
    }
  });

  // lib/host/browser-host.js
  var require_browser_host = __commonJS({
    "lib/host/browser-host.js"(exports2, module2) {
      "use strict";
      function _splitPath(value) {
        return String(value ?? "").split(/[\\/]+/u).filter(Boolean);
      }
      function _normalizePath(value) {
        const isAbs = String(value ?? "").startsWith("/");
        const stack = [];
        for (const part of _splitPath(value)) {
          if (part === ".") {
            continue;
          }
          if (part === "..") {
            if (stack.length > 0) {
              stack.pop();
            }
            continue;
          }
          stack.push(part);
        }
        if (isAbs) {
          return `/${stack.join("/")}`;
        }
        return stack.join("/") || ".";
      }
      function _resolvePath(...parts) {
        const raw = parts.map((item) => String(item ?? "")).join("/");
        const seeded = raw.startsWith("/") ? raw : `/${raw}`;
        return _normalizePath(seeded);
      }
      function _dirname(value) {
        const normalized = _normalizePath(value);
        if (normalized === "/" || normalized === ".") {
          return "/";
        }
        const parts = _splitPath(normalized);
        parts.pop();
        return parts.length > 0 ? `/${parts.join("/")}` : "/";
      }
      function _sourceUrlComment(runOptions = {}) {
        const filename = runOptions.filename == null ? "/<browser>.zzs" : String(runOptions.filename);
        return `
//# sourceURL=${filename.replace(/[\r\n]/gu, "_")}`;
      }
      var browserModuleUrls = /* @__PURE__ */ new Map();
      function _normalizeModuleName(value) {
        const name2 = String(value ?? "").trim().replace(/\\/gu, "/");
        if (name2 === "" || name2.startsWith("/") || name2.endsWith("/") || /(^|\/)\.\.?(\/|$)/u.test(name2)) {
          throw new Error(`Invalid browser module name: ${value}`);
        }
        return name2.replace(/\.zzm$/u, "");
      }
      function _moduleNameFromPath(filename) {
        const path = _resolvePath(filename);
        if (!path.startsWith("/modules/") || !path.endsWith(".zzm")) {
          return null;
        }
        return path.slice("/modules/".length, -".zzm".length);
      }
      function addBrowserModule(moduleName, url) {
        const logicalName = _normalizeModuleName(moduleName);
        const moduleUrl = String(url ?? "").trim();
        if (moduleUrl === "") {
          throw new Error(`Invalid URL for browser module '${logicalName}'`);
        }
        browserModuleUrls.set(logicalName, moduleUrl);
        return logicalName;
      }
      function hasBrowserModules() {
        return browserModuleUrls.size > 0;
      }
      function _browserEval(source, context, runOptions = {}) {
        context.globalThis = context;
        const sourceUrl = _sourceUrlComment(runOptions);
        try {
          const expr = Function(
            "__zuzu_context",
            `with ( __zuzu_context ) { return ( ${source} ); }${sourceUrl}`
          );
          return expr(context);
        } catch (_exprError) {
          const script = Function(
            "__zuzu_context",
            `with ( __zuzu_context ) { ${source}
 }${sourceUrl}`
          );
          return script(context);
        }
      }
      function _defaultGuiBridge(options) {
        if (Object.prototype.hasOwnProperty.call(options, "guiBridge")) {
          return options.guiBridge;
        }
        const doc = options.document || (typeof document !== "undefined" ? document : null);
        if (!doc || typeof doc.createElement !== "function") {
          return null;
        }
        let bridge = null;
        function getBridge() {
          if (bridge) {
            return bridge;
          }
          const {
            createBrowserGuiBridge
          } = require_browser_gui_renderer();
          bridge = createBrowserGuiBridge({
            document: doc,
            root: options.guiRoot,
            rootId: options.guiRootId,
            baseZIndex: options.guiBaseZIndex,
            dialogs: options.guiDialogs,
            window: options.window
          });
          return bridge;
        }
        return {
          get windows() {
            return getBridge().windows;
          },
          openWindow(...args) {
            return getBridge().openWindow(...args);
          },
          closeWindow(...args) {
            return getBridge().closeWindow(...args);
          },
          createWidget(...args) {
            return getBridge().createWidget(...args);
          },
          updateWidget(...args) {
            return getBridge().updateWidget(...args);
          },
          destroyWidget(...args) {
            return getBridge().destroyWidget(...args);
          },
          focusWindow(...args) {
            return getBridge().focusWindow(...args);
          },
          alert(...args) {
            return getBridge().alert(...args);
          },
          confirm(...args) {
            return getBridge().confirm(...args);
          },
          prompt(...args) {
            return getBridge().prompt(...args);
          },
          colourPicker(...args) {
            return getBridge().colourPicker(...args);
          },
          fileOpen(...args) {
            return getBridge().fileOpen(...args);
          },
          fileSave(...args) {
            return getBridge().fileSave(...args);
          },
          directoryOpen(...args) {
            return getBridge().directoryOpen(...args);
          },
          directorySave(...args) {
            return getBridge().directorySave(...args);
          }
        };
      }
      function createBrowserHost(options = {}) {
        const repoRoot = options.repoRoot || "/";
        const includePaths = Array.isArray(options.includePaths) ? options.includePaths.map((item) => _resolvePath(item)) : [];
        const virtualFiles = new Map(Object.entries(options.virtualFiles || {}).map(([filename, source]) => [_resolvePath(filename), String(source)]));
        const jsModules = new Map(Object.entries(options.jsModules || {}).map(([filename, loaded]) => [_resolvePath(filename), loaded]));
        const fetchedFiles = /* @__PURE__ */ new Map();
        const fetchingFiles = /* @__PURE__ */ new Map();
        const optionModuleUrls = new Map(
          Object.entries(options.remoteModules || {}).map(([name2, url]) => [_normalizeModuleName(name2), String(url)])
        );
        const fetchText = typeof options.fetch === "function" ? options.fetch : typeof fetch === "function" ? fetch : null;
        const fetchModule = typeof options.fetchModule === "function" ? options.fetchModule : null;
        const runInContext = typeof options.evaluate === "function" ? options.evaluate : _browserEval;
        const capabilities2 = /* @__PURE__ */ new Set([
          "console",
          "time",
          "module_load",
          "module_fetch",
          "file_availability",
          "http",
          "js",
          "gui"
        ]);
        const workerSource = options.workerSource || typeof globalThis !== "undefined" && globalThis.__ZUZU_BROWSER_WORKER_SOURCE__ || null;
        const workerUrl = options.workerUrl || typeof globalThis !== "undefined" && globalThis.__ZUZU_BROWSER_WORKER_URL__ || null;
        const workerFactory = typeof options.workerFactory === "function" ? options.workerFactory : typeof globalThis !== "undefined" && typeof globalThis.__ZUZU_BROWSER_WORKER_FACTORY__ === "function" ? globalThis.__ZUZU_BROWSER_WORKER_FACTORY__ : null;
        if (workerSource || workerUrl || workerFactory) {
          capabilities2.add("worker");
        }
        const gui = _defaultGuiBridge(options);
        function browserModuleUrlForPath(filename) {
          const logicalName = _moduleNameFromPath(filename);
          if (!logicalName) {
            return null;
          }
          if (optionModuleUrls.has(logicalName)) {
            return optionModuleUrls.get(logicalName);
          }
          return browserModuleUrls.get(logicalName) || null;
        }
        function hasAsyncModules() {
          return optionModuleUrls.size > 0 || browserModuleUrls.size > 0;
        }
        async function fetchBrowserModule(key, url) {
          if (fetchedFiles.has(key)) {
            return fetchedFiles.get(key);
          }
          if (fetchingFiles.has(key)) {
            return fetchingFiles.get(key);
          }
          if (!fetchText) {
            throw new Error(`Exception: Browser host cannot fetch module '${key}'`);
          }
          const pending = Promise.resolve(fetchText(url)).then(async (response) => {
            if (typeof response === "string") {
              return response;
            }
            if (response && response.ok === false) {
              throw new Error(
                `Exception: Fetch failed for browser module '${key}' (${response.status})`
              );
            }
            if (!response || typeof response.text !== "function") {
              throw new Error(
                `Exception: Fetch did not return text for browser module '${key}'`
              );
            }
            return response.text();
          }).then((source) => {
            const text = String(source);
            fetchedFiles.set(key, text);
            fetchingFiles.delete(key);
            return text;
          }, (err) => {
            fetchingFiles.delete(key);
            throw err;
          });
          fetchingFiles.set(key, pending);
          return pending;
        }
        return {
          name: "browser",
          repoRoot,
          includePaths,
          capabilities: capabilities2,
          gui,
          workerSource,
          workerUrl,
          workerFactory,
          cwd() {
            return "/";
          },
          resolve(...parts) {
            return _resolvePath(...parts);
          },
          dirname(value) {
            return _dirname(value);
          },
          join(...parts) {
            return _normalizePath(parts.map((item) => String(item ?? "")).join("/"));
          },
          readFileText(filename) {
            const key = _resolvePath(filename);
            if (virtualFiles.has(key)) {
              return virtualFiles.get(key);
            }
            if (fetchedFiles.has(key)) {
              return fetchedFiles.get(key);
            }
            if (fetchModule) {
              const fetched = fetchModule(key);
              if (typeof fetched === "string") {
                fetchedFiles.set(key, fetched);
                return fetched;
              }
            }
            if (browserModuleUrlForPath(key)) {
              throw new Error(`Exception: Browser module '${filename}' requires asynchronous loading`);
            }
            throw new Error(`Exception: Browser host cannot read file '${filename}'`);
          },
          async readFileTextAsync(filename) {
            const key = _resolvePath(filename);
            if (virtualFiles.has(key)) {
              return virtualFiles.get(key);
            }
            if (fetchedFiles.has(key)) {
              return fetchedFiles.get(key);
            }
            const browserModuleUrl = browserModuleUrlForPath(key);
            if (browserModuleUrl) {
              return fetchBrowserModule(key, browserModuleUrl);
            }
            return this.readFileText(key);
          },
          fileExists(filename) {
            const key = _resolvePath(filename);
            if (virtualFiles.has(key) || jsModules.has(key) || fetchedFiles.has(key)) {
              return true;
            }
            if (browserModuleUrlForPath(key)) {
              return true;
            }
            if (fetchModule) {
              const fetched = fetchModule(key);
              if (typeof fetched === "string") {
                fetchedFiles.set(key, fetched);
                return true;
              }
            }
            return false;
          },
          runInContext(source, context, runOptions = {}) {
            return runInContext(source, context, runOptions);
          },
          consoleLog(value) {
            if (typeof options.consoleLog === "function") {
              options.consoleLog(value);
              return;
            }
            if (typeof console !== "undefined" && typeof console.log === "function") {
              console.log(value);
            }
          },
          now() {
            return Date.now();
          },
          getEnv(_name) {
            return null;
          },
          loadJsModule(filename) {
            const key = _resolvePath(filename);
            if (!jsModules.has(key)) {
              throw new Error(`Exception: Browser host has no JS module for '${filename}'`);
            }
            return jsModules.get(key);
          },
          hasAsyncModules
        };
      }
      module2.exports = {
        addBrowserModule,
        createBrowserHost,
        hasBrowserModules
      };
    }
  });

  // lib/transpiler-utils.js
  var require_transpiler_utils = __commonJS({
    "lib/transpiler-utils.js"(exports2, module2) {
      "use strict";
      function isEscaped(text, idx) {
        let k = idx - 1;
        let backslashes = 0;
        while (k >= 0 && text[k] === "\\") {
          backslashes++;
          k--;
        }
        return backslashes % 2 === 1;
      }
      function findMatching(source, start, openChar, closeChar) {
        let depth = 0;
        let quote = null;
        for (let i = start; i < source.length; i++) {
          const ch = source[i];
          if (quote) {
            if (ch === quote && !isEscaped(source, i)) {
              quote = null;
            }
            continue;
          }
          if (ch === '"' || ch === "'" || ch === "`") {
            quote = ch;
            continue;
          }
          if (ch === openChar) {
            depth++;
          } else if (ch === closeChar) {
            depth--;
            if (depth === 0) {
              return i;
            }
          }
        }
        return -1;
      }
      function splitCaseValues(text) {
        return text.split(",").map((v) => v.trim()).filter((v) => v.length > 0);
      }
      function stripPod(source) {
        const lines = source.split(/\r?\n/);
        const out = [];
        let inPod = false;
        for (const line of lines) {
          if (/^=cut\b/.test(line)) {
            inPod = false;
            continue;
          }
          if (/^=\w+/.test(line)) {
            inPod = true;
            continue;
          }
          if (inPod) {
            continue;
          }
          out.push(line);
        }
        return out.join("\n");
      }
      function stripPodPreservingLines(source) {
        const lines = source.split(/\r?\n/);
        const out = [];
        let inPod = false;
        for (const line of lines) {
          if (/^=cut\b/.test(line)) {
            inPod = false;
            out.push("");
            continue;
          }
          if (/^=\w+/.test(line)) {
            inPod = true;
            out.push("");
            continue;
          }
          out.push(inPod ? "" : line);
        }
        return out.join("\n");
      }
      module2.exports = {
        isEscaped,
        findMatching,
        splitCaseValues,
        stripPod,
        stripPodPreservingLines
      };
    }
  });

  // lib/transpiler-new/errors.js
  var require_errors = __commonJS({
    "lib/transpiler-new/errors.js"(exports2, module2) {
      "use strict";
      var TranspilerSyntaxError = class extends Error {
        constructor(message, token = null) {
          const suffix = token && token.line != null && token.column != null ? ` at ${token.line}:${token.column}` : "";
          super(`${message}${suffix}`);
          this.name = "TranspilerSyntaxError";
          this.token = token;
        }
      };
      var UnsupportedSyntaxError = class extends Error {
        constructor(message, token = null) {
          const suffix = token && token.line != null && token.column != null ? ` at ${token.line}:${token.column}` : "";
          super(`${message}${suffix}`);
          this.name = "UnsupportedSyntaxError";
          this.token = token;
        }
      };
      module2.exports = {
        TranspilerSyntaxError,
        UnsupportedSyntaxError
      };
    }
  });

  // lib/transpiler-new/lexer.js
  var require_lexer = __commonJS({
    "lib/transpiler-new/lexer.js"(exports2, module2) {
      "use strict";
      var { stripPod } = require_transpiler_utils();
      var {
        TranspilerSyntaxError,
        UnsupportedSyntaxError
      } = require_errors();
      var UTF8_ENCODER = new TextEncoder();
      var KEYWORDS = /* @__PURE__ */ new Set([
        "from",
        "import",
        "as",
        "let",
        "const",
        "function",
        "async",
        "await",
        "spawn",
        "return",
        "if",
        "else",
        "true",
        "false",
        "null",
        "and",
        "or",
        "xor",
        "nand",
        "nor",
        "xnor",
        "onlyif",
        "butnot",
        "not",
        // TODO: Remove stale legacy JS-only words that are not current
        // ZuzuScript keywords: contains, difference, elsif, export, foreach,
        // given, isa, my, not_in, our, package, sub, then, use, when.
        "not_in",
        "eq",
        "ne",
        "gt",
        "ge",
        "lt",
        "le",
        "cmp",
        "eqi",
        "nei",
        "gti",
        "gei",
        "lti",
        "lei",
        "cmpi",
        "mod",
        "abs",
        "sqrt",
        "floor",
        "ceil",
        "round",
        "int",
        "length",
        "uc",
        "lc",
        "say",
        "class",
        "trait",
        "try",
        "catch",
        "switch",
        "case",
        "default",
        "for",
        "while",
        "do",
        "fn",
        "next",
        "continue",
        "last",
        "unless",
        "export",
        "die",
        "new",
        "method",
        "static",
        "extends",
        "with",
        "but",
        "super",
        "does",
        "my",
        "our",
        "use",
        "package",
        "given",
        "when",
        "then",
        "elsif",
        "foreach",
        "in",
        "isa",
        "can",
        "does",
        "typeof",
        "debug",
        "warn",
        "assert",
        "throw",
        "sub",
        "union",
        "divides",
        "intersection",
        "difference",
        "subsetof",
        "supersetof",
        "equivalentof",
        "contains"
      ]);
      var SIMPLE_PUNCTUATION = /* @__PURE__ */ new Set(["(", ")", "{", "}", "[", "]", ",", ";", "."]);
      var VALUE_PRESERVING_LOGICAL_OPERATORS = /* @__PURE__ */ new Set([
        "and",
        "\u22C0",
        "or",
        "\u22C1",
        "xor",
        "\u22BB",
        "xnor",
        "\u2194",
        "nand",
        "\u22BC",
        "nor",
        "\u22BD",
        "onlyif",
        "\u22A8",
        "butnot",
        "\u22AD"
      ]);
      function maybeValuePreservingOperator(value, peek, advance) {
        if (VALUE_PRESERVING_LOGICAL_OPERATORS.has(value) && peek() === "?") {
          advance();
          return `${value}?`;
        }
        return value;
      }
      function decodeSimpleEscape(esc) {
        switch (esc) {
          case "n":
            return "\n";
          case "r":
            return "\r";
          case "t":
            return "	";
          case '"':
          case "'":
          case "`":
          case "/":
          case "$":
          case "\\":
            return esc;
          default:
            return null;
        }
      }
      function decodeUnicodeEscape(digits) {
        if (!/^[0-9A-Fa-f]{4}$/u.test(digits)) {
          return null;
        }
        const code = Number.parseInt(digits, 16);
        if (code >= 55296 && code <= 57343) {
          return null;
        }
        return String.fromCodePoint(code);
      }
      function decodeHexEscape(digits) {
        if (!/^[0-9A-Fa-f]{2}$/u.test(digits)) {
          return null;
        }
        return String.fromCharCode(Number.parseInt(digits, 16));
      }
      function isDigit(ch) {
        return ch >= "0" && ch <= "9";
      }
      function isUnicodeLetter(ch) {
        return ch.toLowerCase() !== ch.toUpperCase();
      }
      function isIdentifierStart(ch) {
        return ch === "_" || ch === "$" || isUnicodeLetter(ch);
      }
      function isIdentifierPart(ch) {
        return isIdentifierStart(ch) || isDigit(ch);
      }
      function appendUtf8ByteChars(out, ch) {
        for (const byte of UTF8_ENCODER.encode(ch)) {
          out.value += String.fromCharCode(byte);
        }
      }
      function makeToken(type, value, start, end, source) {
        return {
          type,
          value,
          start: start.offset,
          end: end.offset,
          line: start.line,
          column: start.column,
          endLine: end.line,
          endColumn: end.column,
          raw: source.slice(start.offset, end.offset)
        };
      }
      function readTemplateLiteral(text, start, state) {
        const parts = [];
        let offset = state.offset;
        let line = state.line;
        let column = state.column;
        const delimiter = text.slice(start.offset, start.offset + 3) === "```" ? "```" : "`";
        function peek(n = 0) {
          return text[offset + n] || "";
        }
        function advance() {
          const ch = text[offset] || "";
          offset++;
          if (ch === "\n") {
            line++;
            column = 1;
          } else {
            column++;
          }
          return ch;
        }
        function cursor() {
          return { offset, line, column };
        }
        function skipQuoted() {
          const quote = advance();
          while (offset < text.length) {
            const ch = advance();
            if (ch === "\\") {
              advance();
              continue;
            }
            if (ch === quote) {
              return;
            }
          }
          throw new TranspilerSyntaxError("Unterminated quoted section in template literal");
        }
        function skipLineComment() {
          advance();
          advance();
          while (offset < text.length && peek() !== "\n") {
            advance();
          }
        }
        function skipBlockComment() {
          advance();
          advance();
          while (offset < text.length) {
            if (peek() === "*" && peek(1) === "/") {
              advance();
              advance();
              return;
            }
            advance();
          }
          throw new TranspilerSyntaxError("Unterminated block comment in template literal");
        }
        let textPart = "";
        for (let i = 0; i < delimiter.length; i++) {
          advance();
        }
        while (offset < text.length) {
          const ch = peek();
          if (delimiter === "```" ? text.slice(offset, offset + 3) === "```" : ch === "`") {
            if (textPart.length > 0) {
              parts.push({
                type: "text",
                value: textPart
              });
            }
            for (let i = 0; i < delimiter.length; i++) {
              advance();
            }
            return {
              parts,
              end: cursor()
            };
          }
          if (delimiter !== "```" && ch === "\\") {
            advance();
            const escStart = cursor();
            const esc = advance();
            if (esc === "x") {
              const digits = advance() + advance();
              const decoded2 = decodeHexEscape(digits);
              if (decoded2 == null) {
                throw new TranspilerSyntaxError(
                  "Invalid hex escape sequence",
                  makeToken("escape", `x${digits}`, escStart, cursor(), text)
                );
              }
              textPart += decoded2;
              continue;
            }
            if (esc === "u") {
              const digits = advance() + advance() + advance() + advance();
              const decoded2 = decodeUnicodeEscape(digits);
              if (decoded2 == null) {
                throw new TranspilerSyntaxError(
                  "Invalid unicode escape sequence",
                  makeToken("escape", `u${digits}`, escStart, cursor(), text)
                );
              }
              textPart += decoded2;
              continue;
            }
            const decoded = decodeSimpleEscape(esc);
            if (decoded == null) {
              throw new TranspilerSyntaxError(
                `Unsupported escape sequence \\${esc}`,
                makeToken("escape", esc, escStart, cursor(), text)
              );
            }
            textPart += decoded;
            continue;
          }
          if (delimiter !== "```" && ch === "\n") {
            throw new TranspilerSyntaxError("Unterminated template literal", makeToken("template", "", start, cursor(), text));
          }
          if (ch === "$" && peek(1) === "{") {
            if (textPart.length > 0) {
              parts.push({
                type: "text",
                value: textPart
              });
              textPart = "";
            }
            advance();
            advance();
            const exprStart = offset;
            let depth = 1;
            while (offset < text.length) {
              if (peek() === '"' || peek() === "'" || peek() === "`") {
                skipQuoted();
                continue;
              }
              if (peek() === "/" && peek(1) === "/") {
                skipLineComment();
                continue;
              }
              if (peek() === "/" && peek(1) === "*") {
                skipBlockComment();
                continue;
              }
              const cur = advance();
              if (cur === "{") {
                depth++;
              } else if (cur === "}") {
                depth--;
                if (depth === 0) {
                  parts.push({
                    type: "expr",
                    value: text.slice(exprStart, offset - 1)
                  });
                  break;
                }
              }
            }
            if (depth !== 0) {
              throw new TranspilerSyntaxError("Unterminated template interpolation");
            }
            continue;
          }
          textPart += advance();
        }
        throw new TranspilerSyntaxError("Unterminated template literal", makeToken("template", "", start, cursor(), text));
      }
      function tokenize(source) {
        const text = stripPod(String(source ?? ""));
        const tokens = [];
        let lastToken = null;
        let offset = 0;
        let line = 1;
        let column = 1;
        function cursor() {
          return { offset, line, column };
        }
        function peek(n = 0) {
          return text[offset + n] || "";
        }
        function advance() {
          const ch = text[offset] || "";
          offset++;
          if (ch === "\n") {
            line++;
            column = 1;
          } else {
            column++;
          }
          return ch;
        }
        function addToken(type, value, start, end2) {
          const token = makeToken(type, value, start, end2, text);
          tokens.push(token);
          lastToken = token;
        }
        function canStartRegex() {
          if (!lastToken) {
            return true;
          }
          if (lastToken.type === "punctuation" && ["(", "[", "{", ",", ";"].includes(lastToken.value)) {
            return true;
          }
          if (lastToken.type === "operator") {
            return true;
          }
          if (lastToken.type === "keyword" && [
            "return",
            "case",
            "if",
            "while",
            "throw",
            "and",
            "and?",
            "or",
            "or?",
            "xor",
            "xor?",
            "xnor",
            "xnor?",
            "nand",
            "nand?",
            "nor",
            "nor?",
            "onlyif",
            "onlyif?",
            "butnot",
            "butnot?",
            "not"
          ].includes(lastToken.value)) {
            return true;
          }
          return false;
        }
        function readInterpolationSource() {
          advance();
          advance();
          const exprStart = offset;
          let depth = 1;
          while (offset < text.length) {
            if (peek() === '"' || peek() === "'" || peek() === "`") {
              const quote = advance();
              while (offset < text.length) {
                const ch = advance();
                if (ch === "\\") {
                  advance();
                  continue;
                }
                if (ch === quote) {
                  break;
                }
              }
              continue;
            }
            if (peek() === "/" && peek(1) === "/") {
              advance();
              advance();
              while (offset < text.length && peek() !== "\n") {
                advance();
              }
              continue;
            }
            if (peek() === "/" && peek(1) === "*") {
              advance();
              advance();
              while (offset < text.length) {
                if (peek() === "*" && peek(1) === "/") {
                  advance();
                  advance();
                  break;
                }
                advance();
              }
              continue;
            }
            const cur = advance();
            if (cur === "{") {
              depth++;
            } else if (cur === "}") {
              depth--;
              if (depth === 0) {
                return text.slice(exprStart, offset - 1);
              }
            }
          }
          throw new TranspilerSyntaxError("Unterminated template interpolation");
        }
        while (offset < text.length) {
          const ch = peek();
          if (offset === 0 && ch === "#" && peek(1) === "!") {
            advance();
            advance();
            while (offset < text.length && peek() !== "\n") {
              advance();
            }
            continue;
          }
          if (ch === " " || ch === "	" || ch === "\r" || ch === "\n") {
            advance();
            continue;
          }
          if (ch === "/" && peek(1) === "/") {
            while (offset < text.length && peek() !== "\n") {
              advance();
            }
            continue;
          }
          if (ch === "/" && peek(1) === "*") {
            advance();
            advance();
            while (offset < text.length && !(peek() === "*" && peek(1) === "/")) {
              advance();
            }
            if (offset >= text.length) {
              throw new TranspilerSyntaxError("Unterminated block comment");
            }
            advance();
            advance();
            continue;
          }
          const start = cursor();
          if (ch === "/" && peek(1) !== "/" && peek(1) !== "*" && canStartRegex()) {
            let pattern = "";
            let textPart = "";
            const parts = [];
            let inClass = false;
            let sawInterpolation = false;
            advance();
            while (offset < text.length) {
              const cur = peek();
              if (cur === "\\") {
                const backslash = advance();
                const escaped = advance();
                pattern += backslash + escaped;
                textPart += backslash + escaped;
                continue;
              }
              if (cur === "[") {
                inClass = true;
              } else if (cur === "]") {
                inClass = false;
              }
              if (cur === "$" && peek(1) === "{") {
                if (textPart.length > 0) {
                  parts.push({
                    type: "text",
                    value: textPart
                  });
                  textPart = "";
                }
                const expr = readInterpolationSource();
                parts.push({
                  type: "expr",
                  value: expr
                });
                sawInterpolation = true;
                pattern += `\${${expr}}`;
                continue;
              }
              if (cur === "/" && !inClass) {
                break;
              }
              if (cur === "\n") {
                throw new TranspilerSyntaxError("Unterminated regexp literal");
              }
              const value = advance();
              pattern += value;
              textPart += value;
            }
            if (peek() !== "/") {
              throw new TranspilerSyntaxError("Unterminated regexp literal");
            }
            advance();
            let flags = "";
            while (/[a-z]/i.test(peek())) {
              flags += advance();
            }
            if (sawInterpolation && textPart.length > 0) {
              parts.push({
                type: "text",
                value: textPart
              });
            }
            addToken("regexp", { pattern, parts, flags }, start, cursor());
            continue;
          }
          if (ch === '"') {
            if (peek(1) === '"' && peek(2) === '"') {
              let value2 = "";
              advance();
              advance();
              advance();
              while (offset < text.length) {
                if (peek() === '"' && peek(1) === '"' && peek(2) === '"') {
                  advance();
                  advance();
                  advance();
                  addToken("string", value2, start, cursor());
                  value2 = null;
                  break;
                }
                value2 += advance();
              }
              if (value2 !== null) {
                throw new TranspilerSyntaxError("Unterminated triple-quoted string literal");
              }
              continue;
            }
            let value = "";
            advance();
            while (offset < text.length && peek() !== '"') {
              if (peek() === "\\") {
                const escStart = cursor();
                advance();
                const esc = advance();
                if (esc === "x") {
                  const digits = advance() + advance();
                  const decoded = decodeHexEscape(digits);
                  if (decoded == null) {
                    throw new TranspilerSyntaxError(
                      "Invalid hex escape sequence",
                      makeToken("escape", `x${digits}`, escStart, cursor(), text)
                    );
                  }
                  value += decoded;
                } else if (esc === "u") {
                  const digits = advance() + advance() + advance() + advance();
                  const decoded = decodeUnicodeEscape(digits);
                  if (decoded == null) {
                    throw new TranspilerSyntaxError(
                      "Invalid unicode escape sequence",
                      makeToken("escape", `u${digits}`, escStart, cursor(), text)
                    );
                  }
                  value += decoded;
                } else {
                  const decoded = decodeSimpleEscape(esc);
                  if (decoded == null) {
                    throw new TranspilerSyntaxError(
                      `Unsupported escape sequence \\${esc}`,
                      makeToken("escape", esc, escStart, cursor(), text)
                    );
                  }
                  value += decoded;
                }
                continue;
              }
              if (peek() === "\n") {
                throw new TranspilerSyntaxError("Unterminated string literal");
              }
              value += advance();
            }
            if (peek() !== '"') {
              throw new TranspilerSyntaxError("Unterminated string literal");
            }
            advance();
            addToken("string", value, start, cursor());
            continue;
          }
          if (ch === "'") {
            if (peek(1) === "'" && peek(2) === "'") {
              const out = { value: "" };
              advance();
              advance();
              advance();
              while (offset < text.length) {
                if (peek() === "'" && peek(1) === "'" && peek(2) === "'") {
                  advance();
                  advance();
                  advance();
                  addToken("binary_string", out.value, start, cursor());
                  out.value = null;
                  break;
                }
                appendUtf8ByteChars(out, advance());
              }
              if (out.value !== null) {
                throw new TranspilerSyntaxError("Unterminated triple-quoted binary string literal");
              }
              continue;
            }
            let value = "";
            advance();
            while (offset < text.length && peek() !== "'") {
              if (peek() === "\\") {
                const escStart = cursor();
                advance();
                const esc = advance();
                if (esc === "u") {
                  throw new TranspilerSyntaxError(
                    "Unicode escapes are not supported in binary strings",
                    makeToken("escape", esc, escStart, cursor(), text)
                  );
                }
                if (esc === "x") {
                  const digits = advance() + advance();
                  const decoded2 = decodeHexEscape(digits);
                  if (decoded2 == null) {
                    throw new TranspilerSyntaxError(
                      "Invalid hex escape sequence",
                      makeToken("escape", `x${digits}`, escStart, cursor(), text)
                    );
                  }
                  value += decoded2;
                  continue;
                }
                const decoded = decodeSimpleEscape(esc);
                if (decoded == null) {
                  throw new TranspilerSyntaxError(
                    `Unsupported escape sequence \\${esc}`,
                    makeToken("escape", esc, escStart, cursor(), text)
                  );
                }
                value += decoded;
                continue;
              }
              if (peek() === "\n") {
                throw new TranspilerSyntaxError("Unterminated binary string literal");
              }
              const out = { value: "" };
              appendUtf8ByteChars(out, advance());
              value += out.value;
            }
            if (peek() !== "'") {
              throw new TranspilerSyntaxError("Unterminated binary string literal");
            }
            advance();
            addToken("binary_string", value, start, cursor());
            continue;
          }
          if (ch === "`") {
            const template = readTemplateLiteral(text, start, cursor());
            offset = template.end.offset;
            line = template.end.line;
            column = template.end.column;
            addToken("template", template.parts, start, template.end);
            continue;
          }
          const twoChar = ch + peek(1);
          const threeChar = twoChar + peek(2);
          if (twoChar === "^^") {
            advance();
            advance();
            addToken("identifier", "^^", start, cursor());
            continue;
          }
          if (["...", "<<<", ">>>", "**=", "?:=", "<=>"].includes(threeChar)) {
            advance();
            advance();
            advance();
            addToken("operator", threeChar, start, cursor());
            continue;
          }
          if (["{{", "<<", ">>", ":=", "==", "!=", "<=", ">=", "+=", "-=", "*=", "/=", "%=", "_=", "++", "--", "->", "?:", "**", "@@", "@?", "~=", "|>", "<|", "\u2282\u2283", "\xD7=", "\xF7="].includes(twoChar)) {
            advance();
            advance();
            addToken("operator", twoChar, start, cursor());
            continue;
          }
          if (ch === "_" && !isIdentifierPart(peek(1))) {
            advance();
            addToken("operator", "_", start, cursor());
            continue;
          }
          if (isDigit(ch)) {
            const radixDigitOk = ch === "0" ? peek(1) === "x" ? (c) => /[0-9a-fA-F]/.test(c || "") : peek(1) === "b" ? (c) => c === "0" || c === "1" : peek(1) === "o" ? (c) => /[0-7]/.test(c || "") : null : null;
            if (radixDigitOk && radixDigitOk(peek(2))) {
              const radix = peek(1) === "x" ? 16 : peek(1) === "b" ? 2 : 8;
              advance();
              advance();
              let digits = "";
              while (radixDigitOk(peek())) {
                digits += advance();
              }
              addToken("number", String(parseInt(digits, radix)), start, cursor());
              continue;
            }
            let value = "";
            while (isDigit(peek())) {
              value += advance();
            }
            if (peek() === "." && isDigit(peek(1))) {
              value += advance();
              while (isDigit(peek())) {
                value += advance();
              }
            }
            if (peek() === "E" && (isDigit(peek(1)) || (peek(1) === "+" || peek(1) === "-") && isDigit(peek(2)))) {
              value += advance();
              if (peek() === "+" || peek() === "-") {
                value += advance();
              }
              while (isDigit(peek())) {
                value += advance();
              }
            }
            addToken("number", value, start, cursor());
            continue;
          }
          if (ch === "\u22A4" || ch === "\u22A5") {
            advance();
            addToken("keyword", ch === "\u22A4" ? "true" : "false", start, cursor());
            continue;
          }
          if (isIdentifierStart(ch)) {
            let value = "";
            while (isIdentifierPart(peek())) {
              value += advance();
            }
            if (KEYWORDS.has(value)) {
              value = maybeValuePreservingOperator(value, peek, advance);
              addToken("keyword", value, start, cursor());
            } else {
              addToken("identifier", value, start, cursor());
            }
            continue;
          }
          if (SIMPLE_PUNCTUATION.has(ch)) {
            advance();
            addToken("punctuation", ch, start, cursor());
            continue;
          }
          if (["+", "-", "*", "/", "%", "<", ">", "=", "_", "?", ":", "~", "!", "\\", "&", "|", "^", "@", "\xD7", "\xF7", "\xAC", "\u22C0", "\u22C1", "\u22BB", "\u22BC", "\u22BD", "\u2194", "\u22A8", "\u22AD"].includes(ch)) {
            advance();
            const value = maybeValuePreservingOperator(ch, peek, advance);
            addToken("operator", value, start, cursor());
            continue;
          }
          if (["\u2261", "\u2262", "\u2260", "\u2264", "\u2265", "\u2192", "\u221A", "\u230A", "\u230B", "\u2308", "\u2309", "\u2208", "\u2209", "\u22C3", "\u22C2", "\u2216", "\u2282", "\u2283", "\xAB", "\xBB", "\u2276", "\u2277", "\u25B7", "\u25C1", "\u2223", "\u2224"].includes(ch)) {
            advance();
            addToken("operator", ch, start, cursor());
            continue;
          }
          throw new UnsupportedSyntaxError(
            `Unsupported character ${JSON.stringify(ch)}`,
            makeToken("unsupported", ch, start, start, text)
          );
        }
        const end = cursor();
        tokens.push(makeToken("eof", "", end, end, text));
        return tokens;
      }
      module2.exports = {
        tokenize
      };
    }
  });

  // lib/transpiler-new/ast.js
  var require_ast = __commonJS({
    "lib/transpiler-new/ast.js"(exports2, module2) {
      "use strict";
      function withLoc(node, start, end) {
        return {
          ...node,
          loc: {
            start: start ? {
              offset: start.start,
              line: start.line,
              column: start.column
            } : null,
            end: end ? {
              offset: end.end,
              line: end.endLine,
              column: end.endColumn
            } : null
          }
        };
      }
      module2.exports = {
        withLoc
      };
    }
  });

  // lib/transpiler-new/parser.js
  var require_parser = __commonJS({
    "lib/transpiler-new/parser.js"(exports2, module2) {
      "use strict";
      var { withLoc } = require_ast();
      var { tokenize } = require_lexer();
      var {
        TranspilerSyntaxError,
        UnsupportedSyntaxError
      } = require_errors();
      function parse(tokens, options = {}) {
        const pendingSetClosers = [];
        let index = 0;
        let asyncContextDepth = 1;
        function startLocFromToken(token) {
          return {
            start: token.start,
            line: token.line,
            column: token.column
          };
        }
        function startLocFromNode(node) {
          return {
            start: node.loc.start.offset,
            line: node.loc.start.line,
            column: node.loc.start.column
          };
        }
        function endLocFromToken(token) {
          return {
            end: token.end,
            endLine: token.endLine,
            endColumn: token.endColumn
          };
        }
        function endLocFromNode(node) {
          return {
            end: node.loc.end.offset,
            endLine: node.loc.end.line,
            endColumn: node.loc.end.column
          };
        }
        function current() {
          return tokens[index];
        }
        function peekToken(n = 1) {
          return tokens[index + n] || tokens[tokens.length - 1];
        }
        function previous() {
          return tokens[index - 1];
        }
        function canTerminateSimpleStatement() {
          const token = current();
          if (token.type === "punctuation" && token.value === "}") {
            return true;
          }
          if (token.type === "eof") {
            return true;
          }
          return false;
        }
        function consumeStatementTerminator(message) {
          if (match("punctuation", ";")) {
            return;
          }
          if (canTerminateSimpleStatement()) {
            return;
          }
          throw new TranspilerSyntaxError(message || "Expected statement terminator", current());
        }
        function atEnd() {
          return current().type === "eof";
        }
        function match(type, value = null) {
          const token = current();
          if (token.type !== type) {
            return false;
          }
          if (value != null && token.value !== value) {
            return false;
          }
          index++;
          return true;
        }
        function expect(type, value = null, message = null) {
          const token = current();
          if (match(type, value)) {
            return previous();
          }
          throw new TranspilerSyntaxError(
            message || `Expected ${value != null ? `${type} ${value}` : type}`,
            token
          );
        }
        function expectIdentifier(message = "Expected identifier") {
          const token = current();
          if (token.type === "identifier" || token.type === "keyword") {
            if (token.value === "^^") {
              throw new TranspilerSyntaxError("'^^' is reserved for the chain placeholder", token);
            }
            index++;
            return token;
          }
          throw new TranspilerSyntaxError(message, token);
        }
        function parseProgram() {
          const body = [];
          const start = current();
          while (!atEnd()) {
            body.push(parseStatement());
          }
          return withLoc({
            type: "Program",
            body
          }, start, previous() || start);
        }
        function matchPairListClose() {
          if (current().type === "punctuation" && current().value === "}" && peekToken().type === "punctuation" && peekToken().value === "}") {
            index += 2;
            return true;
          }
          return false;
        }
        function parseExpressionRoot() {
          const expr = parseExpression();
          if (!atEnd()) {
            throw new TranspilerSyntaxError("Unexpected token after expression", current());
          }
          return expr;
        }
        function parseStatement() {
          const token = current();
          if (token.type === "punctuation" && token.value === ";") {
            index++;
            return withLoc({ type: "EmptyStatement" }, token, token);
          }
          if (token.type === "keyword") {
            switch (token.value) {
              case "from":
                return parseImportDeclaration();
              case "let":
              case "const":
                return parseVariableDeclaration();
              case "function":
                return parseFunctionDeclaration();
              case "async":
                if (peekToken().type === "keyword" && peekToken().value === "function") {
                  return parseFunctionDeclaration();
                }
                if (peekToken().type === "keyword" && peekToken().value === "fn") {
                  const start = expect("keyword", "async");
                  return parseFunctionDeclarationLikeFn(true, start);
                }
                break;
              case "return":
                return parseReturnStatement();
              case "if":
                return parseIfStatement();
              case "for":
                return parseForStatement();
              case "while":
                return parseWhileStatement();
              case "switch":
                return parseSwitchStatement();
              case "next":
              case "continue":
                return parseLoopControlStatement("ContinueStatement");
              case "last":
                return parseLoopControlStatement("BreakStatement");
              case "throw":
                return parseThrowStatement();
              case "die":
                return parseDieStatement();
              case "warn":
                return parseWarnStatement();
              case "assert":
                return parseAssertStatement();
              case "debug":
                return parseDebugStatement();
              case "say":
                return parseSayStatement();
              case "try":
                return parseTryStatement();
              case "class":
                return parseClassDeclaration();
              case "trait":
                return parseTraitDeclaration();
              case "export":
                return parseExportDeclaration();
              case "catch":
              case "unless":
                throw new UnsupportedSyntaxError(
                  `Keyword ${token.value} is not supported by zuzu-js transpilation yet`,
                  token
                );
              case "fn":
                return parseFunctionDeclarationLikeFn();
              default:
                break;
            }
          }
          if (token.type === "punctuation" && token.value === "{") {
            return parseBlockStatement();
          }
          return parseExpressionStatement();
        }
        function parseExportDeclaration() {
          const start = expect("keyword", "export");
          const token = current();
          const allowed = /* @__PURE__ */ new Set(["let", "const", "function", "async", "fn", "class", "trait"]);
          if (token.type !== "keyword" || !allowed.has(token.value)) {
            throw new TranspilerSyntaxError("Expected declaration after export", token);
          }
          const declaration = parseStatement();
          declaration.exported = true;
          declaration.loc.start = {
            offset: start.start,
            line: start.line,
            column: start.column
          };
          return declaration;
        }
        function parseImportDeclaration() {
          const start = expect("keyword", "from");
          const moduleParts = [];
          while (!(current().type === "keyword" && (current().value === "import" || current().value === "try"))) {
            if (current().type === "identifier" || current().type === "keyword" || current().type === "operator" && current().value === "/" || current().type === "operator" && current().value === "." || current().type === "punctuation" && current().value === ".") {
              moduleParts.push(current().value);
              index++;
              continue;
            }
            if (current().type === "string") {
              moduleParts.push(current().value);
              index++;
              break;
            }
            throw new TranspilerSyntaxError("Invalid module path in import", current());
          }
          const tryMode = match("keyword", "try");
          expect("keyword", "import");
          let importAll = false;
          const specifiers = [];
          if (match("operator", "*")) {
            if (tryMode) {
              throw new TranspilerSyntaxError(
                "Wildcard import '*' cannot be combined with try import",
                previous()
              );
            }
            importAll = true;
          } else {
            do {
              const imported = expectIdentifier();
              let local = imported;
              if (match("keyword", "as")) {
                local = expectIdentifier("Expected alias name after as");
              }
              specifiers.push({
                type: "ImportSpecifier",
                imported: imported.value,
                local: local.value
              });
            } while (match("punctuation", ","));
          }
          let condition = null;
          if (current().type === "keyword" && ["if", "unless"].includes(current().value)) {
            const keyword = current();
            if (importAll) {
              throw new TranspilerSyntaxError(
                "Wildcard import '*' cannot be combined with postfix if/unless",
                keyword
              );
            }
            index++;
            condition = {
              type: "PostfixCondition",
              keyword: keyword.value,
              test: parseExpression()
            };
          }
          consumeStatementTerminator("Expected ; after import declaration");
          return withLoc({
            type: "ImportDeclaration",
            source: moduleParts.join(""),
            tryMode,
            importAll,
            specifiers,
            condition
          }, start, previous());
        }
        function parseVariableDeclaration() {
          const start = expect("keyword");
          if (current().type === "punctuation" && current().value === "{") {
            return parseVariableUnpackDeclaration(start);
          }
          const declaration = parseVariableDeclarationParts(start);
          consumeStatementTerminator("Expected ; after variable declaration");
          return withLoc({
            type: "VariableDeclaration",
            ...declaration
          }, start, previous());
        }
        function parseVariableDeclarationParts(start) {
          let declaredType = null;
          let id = expectIdentifier();
          if (current().type === "identifier" && ![":=", "=", ";", ",", ")"].includes(current().value)) {
            declaredType = id.value;
            id = expectIdentifier("Expected variable name after type");
          }
          let isWeakStorage = parseOptionalWeakModifier("declaration");
          let init = null;
          if (match("operator", ":=") || match("operator", "=")) {
            init = parseExpression();
            isWeakStorage = parseOptionalWeakModifier("declaration") || isWeakStorage;
          }
          return {
            kind: start.value,
            declaredType,
            id: withLoc({
              type: "Identifier",
              name: id.value
            }, id, id),
            init,
            isWeakStorage
          };
        }
        function parseVariableUnpackDeclaration(start) {
          const pattern = parseDeclarationBindingPattern();
          expect("operator", ":=", "Expected ':=' after declaration binding pattern");
          const init = parseExpression();
          consumeStatementTerminator("Expected ; after variable unpack declaration");
          return withLoc({
            type: "VariableUnpackDeclaration",
            kind: start.value,
            pattern,
            init
          }, start, previous());
        }
        function parseDeclarationBindingPattern() {
          const start = expect("punctuation", "{", "Expected '{' in declaration binding pattern");
          const entries = [];
          if (!match("punctuation", "}")) {
            while (true) {
              if (match("punctuation", ",")) {
                continue;
              }
              if (match("punctuation", "}")) {
                break;
              }
              entries.push(parseDeclarationBindingEntry());
              if (match("punctuation", "}")) {
                break;
              }
              match("punctuation", ",");
            }
          }
          return withLoc({
            type: "KeyedBindingPattern",
            entries
          }, start, previous());
        }
        function parseDeclarationBindingEntry() {
          const start = current();
          const binding = parseDeclarationBindingKeyAndName();
          let defaultValue = null;
          if (match("operator", ":=")) {
            defaultValue = parseExpression();
          }
          const isWeakStorage = parseOptionalWeakModifier("declaration");
          return withLoc({
            type: "DeclarationBindingEntry",
            key: binding.key,
            declaredType: binding.declaredType,
            name: binding.name,
            defaultValue,
            isWeakStorage
          }, start, previous() || start);
        }
        function parseDeclarationBindingKeyAndName() {
          if (current().type === "identifier") {
            const first = current();
            index++;
            if (match("operator", ":")) {
              const typed = parseTypedBindingName();
              return {
                key: bindingIdentifierKey(first),
                declaredType: typed.declaredType,
                name: typed.name
              };
            }
            if (current().type === "identifier" || current().type === "keyword") {
              const name2 = expectIdentifier("Expected unpacked binding name after type");
              return {
                key: bindingIdentifierKey(name2),
                declaredType: first.value,
                name: name2.value
              };
            }
            return {
              key: bindingIdentifierKey(first),
              declaredType: null,
              name: first.value
            };
          }
          if (current().type === "keyword" || current().type === "string") {
            const key = parseDeclarationBindingKey();
            expect("operator", ":", "Expected ':' after declaration binding key");
            const typed = parseTypedBindingName();
            return {
              key,
              declaredType: typed.declaredType,
              name: typed.name
            };
          }
          if (current().type === "template" || current().type === "punctuation" && current().value === "(") {
            const key = parseDeclarationBindingKey();
            expect("operator", ":", "Expected ':' after declaration binding key");
            const typed = parseTypedBindingName();
            return {
              key,
              declaredType: typed.declaredType,
              name: typed.name
            };
          }
          throw new TranspilerSyntaxError("Expected unpacked binding in declaration", current());
        }
        function parseTypedBindingName() {
          let declaredType = null;
          let name2 = expectIdentifier("Expected unpacked binding name");
          if (current().type === "identifier") {
            declaredType = name2.value;
            name2 = expectIdentifier("Expected unpacked binding name after type");
          }
          return {
            declaredType,
            name: name2.value
          };
        }
        function bindingIdentifierKey(token) {
          return withLoc({
            type: "BraceIdentifier",
            name: token.value
          }, token, token);
        }
        function parseDeclarationBindingKey() {
          const token = current();
          if (token.type === "identifier" || token.type === "keyword") {
            index++;
            return withLoc({
              type: "BraceIdentifier",
              name: token.value
            }, token, token);
          }
          if (token.type === "string") {
            index++;
            return withLoc({
              type: "StringLiteral",
              value: token.value
            }, token, token);
          }
          if (token.type === "template") {
            return parsePrimary();
          }
          if (match("punctuation", "(")) {
            const expr = parseExpression();
            expect("punctuation", ")", "Expected ) after declaration binding key");
            return expr;
          }
          throw new TranspilerSyntaxError("Expected declaration binding key", token);
        }
        function parseFunctionDeclaration() {
          let isAsync = false;
          let start = current();
          if (match("keyword", "async")) {
            isAsync = true;
            start = previous();
          }
          expect("keyword", "function");
          const id = expectIdentifier();
          if (match("punctuation", ";")) {
            return withLoc({
              type: "FunctionDeclaration",
              id: {
                type: "Identifier",
                name: id.value
              },
              params: [],
              returnType: null,
              isAsync,
              isPredeclared: true,
              body: withLoc({
                type: "BlockStatement",
                body: []
              }, id, id)
            }, start, previous());
          }
          const params = parseParameterList();
          const returnType = parseOptionalReturnType();
          const body = parseBlockInAsyncContext(isAsync);
          return withLoc({
            type: "FunctionDeclaration",
            id: {
              type: "Identifier",
              name: id.value
            },
            params,
            returnType,
            isAsync,
            isPredeclared: false,
            body
          }, start, previous());
        }
        function parseFunctionDeclarationLikeFn(isAsync = false, startOverride = null) {
          const start = startOverride || current();
          expect("keyword", "fn");
          const id = expectIdentifier();
          const params = parseParameterList();
          const returnType = parseOptionalReturnType();
          const body = parseBlockInAsyncContext(isAsync);
          return withLoc({
            type: "FunctionDeclaration",
            id: {
              type: "Identifier",
              name: id.value
            },
            params,
            returnType,
            isAsync,
            body
          }, start, previous());
        }
        function parseClassDeclaration() {
          const start = expect("keyword", "class");
          const id = expectIdentifier("Expected class name");
          let base = null;
          if (match("keyword", "extends")) {
            const baseId = expectIdentifier("Expected base class name after extends");
            base = withLoc({
              type: "Identifier",
              name: baseId.value
            }, baseId, baseId);
          }
          const traits = parseTraitCompositionList();
          if (match("punctuation", ";")) {
            return withLoc({
              type: "ClassDeclaration",
              id: withLoc({
                type: "Identifier",
                name: id.value
              }, id, id),
              base,
              traits,
              body: [],
              shorthand: true
            }, start, previous());
          }
          expect("punctuation", "{", "Expected { to start class body");
          const body = [];
          while (!(current().type === "punctuation" && current().value === "}")) {
            if (atEnd()) {
              throw new TranspilerSyntaxError("Unterminated class declaration", current());
            }
            if (current().type === "punctuation" && current().value === ";") {
              index++;
              continue;
            }
            body.push(parseClassMember());
          }
          expect("punctuation", "}");
          return withLoc({
            type: "ClassDeclaration",
            id: withLoc({
              type: "Identifier",
              name: id.value
            }, id, id),
            base,
            traits,
            body,
            shorthand: false
          }, start, previous());
        }
        function parseTraitDeclaration() {
          const start = expect("keyword", "trait");
          const id = expectIdentifier("Expected trait name");
          expect("punctuation", "{", "Expected { to start trait body");
          const body = [];
          while (!(current().type === "punctuation" && current().value === "}")) {
            if (atEnd()) {
              throw new TranspilerSyntaxError("Unterminated trait declaration", current());
            }
            if (current().type === "punctuation" && current().value === ";") {
              index++;
              continue;
            }
            body.push(parseMethodDeclaration({ allowStatic: false }));
          }
          expect("punctuation", "}");
          return withLoc({
            type: "TraitDeclaration",
            id: withLoc({
              type: "Identifier",
              name: id.value
            }, id, id),
            body
          }, start, previous());
        }
        function parseTraitCompositionList() {
          const traits = [];
          if (current().type === "keyword" && ["with", "but"].includes(current().value)) {
            index++;
            do {
              const traitId = expectIdentifier("Expected trait name");
              traits.push(withLoc({
                type: "Identifier",
                name: traitId.value
              }, traitId, traitId));
            } while (match("punctuation", ","));
          }
          return traits;
        }
        function parseOptionalWeakModifier(context) {
          if (current().type !== "keyword" || current().value !== "but") {
            return false;
          }
          index++;
          const modifier = current();
          if (!(modifier.type === "identifier" || modifier.type === "keyword") || modifier.value !== "weak") {
            throw new TranspilerSyntaxError(
              `Unknown but modifier '${modifier.value || ""}' in ${context}; expected 'but weak'`,
              modifier
            );
          }
          index++;
          return true;
        }
        function parseClassMember() {
          if (current().type === "keyword" && ["static", "async"].includes(current().value)) {
            return parseMethodDeclaration({ allowStatic: true });
          }
          if (current().type === "keyword" && current().value === "method") {
            return parseMethodDeclaration({ allowStatic: true });
          }
          if (current().type === "keyword" && ["let", "const"].includes(current().value)) {
            return parseFieldDeclaration();
          }
          if (current().type === "keyword" && current().value === "class") {
            return parseClassDeclaration();
          }
          if (current().type === "keyword" && current().value === "trait") {
            return parseTraitDeclaration();
          }
          throw new UnsupportedSyntaxError("Unsupported class member", current());
        }
        function parseMethodDeclaration({ allowStatic = true } = {}) {
          const start = current();
          let isStatic = false;
          let isAsync = false;
          while (current().type === "keyword" && ["static", "async"].includes(current().value)) {
            if (current().value === "static") {
              if (!allowStatic || isStatic) {
                break;
              }
              isStatic = true;
              index++;
              continue;
            }
            if (isAsync) {
              break;
            }
            isAsync = true;
            index++;
          }
          expect("keyword", "method", "Expected method declaration");
          const id = expectIdentifier("Expected method name");
          if (match("punctuation", ";")) {
            return withLoc({
              type: "MethodDeclaration",
              id: withLoc({
                type: "Identifier",
                name: id.value
              }, id, id),
              params: [],
              returnType: null,
              body: withLoc({
                type: "BlockStatement",
                body: []
              }, id, id),
              static: isStatic,
              isAsync,
              isPredeclared: true
            }, start, previous());
          }
          const params = parseParameterList();
          const returnType = parseOptionalReturnType();
          const body = parseBlockInAsyncContext(isAsync);
          return withLoc({
            type: "MethodDeclaration",
            id: withLoc({
              type: "Identifier",
              name: id.value
            }, id, id),
            params,
            returnType,
            body,
            static: isStatic,
            isAsync,
            isPredeclared: false
          }, start, previous());
        }
        function parseFieldDeclaration() {
          const start = expect("keyword");
          let typeName2 = null;
          let id = expectIdentifier("Expected field name");
          if (current().type === "identifier" && current().value !== "with" && !(current().type === "operator" && current().value === ":=") && !(current().type === "punctuation" && [";", "}"].includes(current().value))) {
            typeName2 = id.value;
            id = expectIdentifier("Expected field name after type");
          }
          const accessors = [];
          if (match("keyword", "with")) {
            do {
              accessors.push(expectIdentifier("Expected accessor name").value);
            } while (match("punctuation", ","));
          }
          let isWeakStorage = parseOptionalWeakModifier("field declaration");
          let defaultValue = null;
          if (match("operator", ":=")) {
            defaultValue = parseExpression();
            isWeakStorage = parseOptionalWeakModifier("field declaration") || isWeakStorage;
          }
          consumeStatementTerminator("Expected ; after field declaration");
          return withLoc({
            type: "FieldDeclaration",
            kind: start.value,
            typeName: typeName2,
            id: withLoc({
              type: "Identifier",
              name: id.value
            }, id, id),
            accessors,
            defaultValue,
            isWeakStorage
          }, start, previous());
        }
        function parseParameterList() {
          expect("punctuation", "(");
          const params = [];
          if (!match("punctuation", ")")) {
            while (true) {
              if (match("punctuation", ",")) {
                continue;
              }
              params.push(parseParameter());
              if (match("punctuation", ")")) {
                break;
              }
              if (match("punctuation", ",") && match("punctuation", ")")) {
                break;
              }
            }
          }
          return params;
        }
        function parseParameter() {
          const start = current();
          let rest = false;
          if (match("operator", "...")) {
            if (current().type === "identifier" && peekToken().type === "identifier") {
              const containerType = expectIdentifier("Expected parameter type after ...");
              const id2 = expectIdentifier("Expected parameter name");
              return withLoc({
                type: "SpecialParameter",
                special: "rest_only",
                leadName: null,
                containerType: containerType.value,
                name: id2.value
              }, start, previous() || start);
            }
            rest = true;
          }
          let typeName2 = null;
          let id = expectIdentifier("Expected parameter name");
          if (!rest && current().type === "operator" && current().value === "...") {
            index++;
            const first = expectIdentifier("Expected parameter type or name after ...");
            let containerType;
            let target;
            if (current().type === "identifier" && !["?", ":=", ",", ")"].includes(current().value)) {
              containerType = first.value;
              target = expectIdentifier("Expected parameter name after special variadic type");
            } else {
              containerType = "Array";
              target = first;
            }
            return withLoc({
              type: "SpecialParameter",
              special: "lead_rest",
              leadName: id.value,
              containerType,
              name: target.value
            }, start, previous() || start);
          }
          if (!rest && current().type === "identifier" && !["?", ":=", ",", ")"].includes(current().value) && peekToken().type !== "identifier") {
            typeName2 = id.value;
            id = expectIdentifier("Expected parameter name after type");
          }
          let optional = false;
          let defaultValue = null;
          if (match("operator", "?")) {
            optional = true;
          }
          if (match("operator", ":=")) {
            defaultValue = parseExpression();
          }
          return withLoc({
            type: "Parameter",
            name: id.value,
            typeName: typeName2,
            optional,
            defaultValue,
            rest
          }, start, previous() || start);
        }
        function parseOptionalReturnType() {
          if (current().type === "operator" && (current().value === "->" || current().value === "\u2192")) {
            index++;
            return expectIdentifier("Expected return type after ->").value;
          }
          return null;
        }
        function parseReturnStatement() {
          const start = expect("keyword", "return");
          let argument = null;
          if (!(current().type === "punctuation" && current().value === ";") && !(current().type === "keyword" && ["if", "unless"].includes(current().value))) {
            argument = parseExpression();
          }
          const stmt = withLoc({
            type: "ReturnStatement",
            argument
          }, start, previous() || start);
          return finishStatement(stmt, "Expected ; after return statement");
        }
        function parseIfStatement() {
          const start = expect("keyword", "if");
          expect("punctuation", "(");
          let declaration = null;
          let test = null;
          if (current().type === "keyword" && ["let", "const"].includes(current().value)) {
            declaration = parseInlineVariableDeclaration();
            test = declaration.id;
          } else {
            test = parseExpression();
          }
          expect("punctuation", ")", "Expected ) after if condition");
          const consequent = parseBlockStatement();
          let alternate = null;
          if (match("keyword", "else")) {
            if (current().type === "keyword" && current().value === "if") {
              alternate = parseIfStatement();
            } else {
              alternate = parseBlockStatement();
            }
          }
          return withLoc({
            type: "IfStatement",
            declaration,
            test,
            consequent,
            alternate
          }, start, previous());
        }
        function parseForStatement() {
          const start = expect("keyword", "for");
          expect("punctuation", "(");
          let decl = null;
          let id = null;
          let iterable;
          if (current().type === "keyword" && ["let", "const"].includes(current().value)) {
            decl = expect("keyword");
            id = expectIdentifier("Expected loop variable");
            expect("keyword", "in", "Expected in inside for loop");
            iterable = parseExpression();
          } else if (current().type === "identifier" && peekToken().type === "keyword" && peekToken().value === "in") {
            id = expectIdentifier("Expected loop variable");
            expect("keyword", "in", "Expected in inside for loop");
            iterable = parseExpression();
          } else {
            decl = { value: "const" };
            id = {
              value: "^^",
              start: current().start,
              end: current().end,
              line: current().line,
              column: current().column
            };
            iterable = parseExpression();
          }
          expect("punctuation", ")", "Expected ) after for loop header");
          const body = parseBlockStatement();
          let elseBlock = null;
          if (match("keyword", "else")) {
            elseBlock = parseBlockStatement();
          }
          return withLoc({
            type: "ForInStatement",
            kind: decl ? decl.value : null,
            left: {
              type: "Identifier",
              name: id.value
            },
            iterable,
            body,
            elseBlock
          }, start, previous());
        }
        function parseWhileStatement() {
          const start = expect("keyword", "while");
          expect("punctuation", "(");
          let declaration = null;
          let test = null;
          if (current().type === "keyword" && ["let", "const"].includes(current().value)) {
            declaration = parseInlineVariableDeclaration();
            test = declaration.id;
          } else {
            test = parseExpression();
          }
          expect("punctuation", ")", "Expected ) after while condition");
          const body = parseBlockStatement();
          return withLoc({
            type: "WhileStatement",
            declaration,
            test,
            body
          }, start, previous());
        }
        function parseSwitchStatement() {
          const start = expect("keyword", "switch");
          expect("punctuation", "(");
          const discriminant = parseExpression();
          let comparator = "==";
          if (match("operator", ":")) {
            const token = current();
            const operator = parseSwitchComparator();
            if (!operator) {
              throw new TranspilerSyntaxError("Expected switch comparator after :", token);
            }
            comparator = operator;
          }
          expect("punctuation", ")", "Expected ) after switch header");
          expect("punctuation", "{", "Expected { to start switch body");
          const cases = [];
          let defaultCase = null;
          while (!(current().type === "punctuation" && current().value === "}")) {
            if (atEnd()) {
              throw new TranspilerSyntaxError("Unterminated switch statement", current());
            }
            if (current().type === "keyword" && current().value === "case") {
              cases.push(parseSwitchCase());
              continue;
            }
            if (current().type === "keyword" && current().value === "default") {
              if (defaultCase) {
                throw new TranspilerSyntaxError("Duplicate default clause in switch statement", current());
              }
              defaultCase = parseSwitchDefaultCase();
              continue;
            }
            throw new TranspilerSyntaxError("Expected case or default inside switch statement", current());
          }
          expect("punctuation", "}");
          return withLoc({
            type: "SwitchStatement",
            discriminant,
            comparator,
            cases,
            defaultCase
          }, start, previous());
        }
        function parseSwitchCase() {
          const start = expect("keyword", "case");
          const first = parseSwitchCaseValue();
          const values = [first.value];
          const operators = [first.operator];
          while (match("punctuation", ",")) {
            const item = parseSwitchCaseValue();
            values.push(item.value);
            operators.push(item.operator);
          }
          expect("operator", ":", "Expected : after switch case");
          const consequent = parseSwitchConsequent(start);
          return withLoc({
            type: "SwitchCase",
            values,
            operators,
            consequent
          }, start, endLocFromNode(consequent));
        }
        function parseSwitchCaseValue() {
          const operator = parseSwitchComparator();
          return {
            operator,
            value: parseExpression()
          };
        }
        function parseSwitchComparator() {
          if (!isSwitchComparatorToken(current())) {
            return null;
          }
          const operator = current().value;
          index++;
          return operator;
        }
        function isSwitchComparatorToken(token) {
          if (!token) {
            return false;
          }
          if (token.type === "identifier" && token.value === "instanceof") {
            return true;
          }
          if (token.type !== "operator" && token.type !== "keyword") {
            return false;
          }
          return [
            ">",
            "<",
            ">=",
            "\u2264",
            "<=",
            "\u2265",
            "=",
            "!=",
            "\u2260",
            "==",
            "\u2261",
            "\u2262",
            "<=>",
            "\u2276",
            "\u2277",
            "eq",
            "ne",
            "gt",
            "ge",
            "lt",
            "le",
            "cmp",
            "eqi",
            "nei",
            "gti",
            "gei",
            "lti",
            "lei",
            "cmpi",
            "in",
            "\u2208",
            "not_in",
            "\u2209",
            "subsetof",
            "\u2282",
            "supersetof",
            "\u2283",
            "equivalentof",
            "\u2282\u2283",
            "does",
            "can",
            "~",
            "@?",
            "\u2223",
            "divides",
            "\u2224"
          ].includes(token.value);
        }
        function parseSwitchDefaultCase() {
          const start = expect("keyword", "default");
          expect("operator", ":", "Expected : after default");
          const consequent = parseSwitchConsequent(start);
          return withLoc({
            type: "SwitchCase",
            values: null,
            consequent
          }, start, endLocFromNode(consequent));
        }
        function parseSwitchConsequent(startToken) {
          const body = [];
          while (true) {
            if (atEnd()) {
              throw new TranspilerSyntaxError("Unterminated switch case body", current());
            }
            if (current().type === "punctuation" && current().value === "}") {
              break;
            }
            if (current().type === "keyword" && ["case", "default"].includes(current().value)) {
              break;
            }
            body.push(parseStatement());
          }
          return withLoc({
            type: "BlockStatement",
            body
          }, startToken, previous() || startToken);
        }
        function parseInlineVariableDeclaration() {
          const start = expect("keyword");
          const declaration = parseVariableDeclarationParts(start);
          return withLoc({
            type: "VariableDeclaration",
            ...declaration
          }, start, previous());
        }
        function parseLoopControlStatement(type) {
          const start = expect("keyword");
          const stmt = withLoc({ type }, start, previous() || start);
          return finishStatement(stmt, `Expected ; after ${start.value}`);
        }
        function parseThrowStatement() {
          const start = expect("keyword", "throw");
          const argument = parseExpression();
          const stmt = withLoc({
            type: "ThrowStatement",
            argument
          }, start, previous());
          return finishStatement(stmt, "Expected ; after throw statement");
        }
        function parseDieStatement() {
          const start = expect("keyword", "die");
          const argument = parseExpression();
          const stmt = withLoc({
            type: "DieStatement",
            argument
          }, start, previous());
          return finishStatement(stmt, "Expected ; after die statement");
        }
        function parseWarnStatement() {
          const start = expect("keyword", "warn");
          const argument = parseExpression();
          const stmt = withLoc({
            type: "WarnStatement",
            argument
          }, start, previous());
          return finishStatement(stmt, "Expected ; after warn statement");
        }
        function parseAssertStatement() {
          const start = expect("keyword", "assert");
          const argument = parseExpression();
          const stmt = withLoc({
            type: "AssertStatement",
            argument
          }, start, previous());
          return finishStatement(stmt, "Expected ; after assert statement");
        }
        function parseDebugStatement() {
          const start = expect("keyword", "debug");
          const argumentsList = [];
          if (!(current().type === "punctuation" && current().value === ";")) {
            argumentsList.push(parseExpression());
            while (match("punctuation", ",")) {
              argumentsList.push(parseExpression());
            }
          }
          const stmt = withLoc({
            type: "DebugStatement",
            arguments: argumentsList
          }, start, previous() || start);
          return finishStatement(stmt, "Expected ; after debug statement");
        }
        function parseSayStatement() {
          const start = expect("keyword", "say");
          const args = [];
          if (!(current().type === "punctuation" && current().value === ";")) {
            args.push(parseExpression());
            while (match("punctuation", ",")) {
              args.push(parseExpression());
            }
          }
          const stmt = withLoc({
            type: "ExpressionStatement",
            expression: withLoc({
              type: "CallExpression",
              callee: withLoc({
                type: "Identifier",
                name: "say"
              }, start, start),
              arguments: args
            }, start, previous() || start)
          }, start, previous() || start);
          return finishStatement(stmt, "Expected ; after say statement");
        }
        function parseTryStatement() {
          const parsed = parseTryLike();
          return withLoc({
            type: "TryStatement",
            block: parsed.block,
            handlers: parsed.handlers
          }, parsed.start, previous());
        }
        function parseTryLike() {
          const start = expect("keyword", "try");
          const block = parseBlockStatement();
          const handlers = [];
          while (current().type === "keyword" && current().value === "catch") {
            const catchTok = expect("keyword", "catch");
            let typeName2 = "Exception";
            let paramName = "e";
            if (match("punctuation", "(")) {
              if (current().type === "identifier") {
                const first = current();
                index++;
                if (current().type === "identifier") {
                  typeName2 = first.value;
                  paramName = current().value;
                  index++;
                } else {
                  paramName = first.value;
                }
              }
              expect("punctuation", ")", "Expected ) after catch clause");
            }
            const handlerBody = parseBlockStatement();
            handlers.push(withLoc({
              type: "CatchClause",
              typeName: typeName2,
              paramName,
              body: handlerBody
            }, catchTok, previous()));
          }
          return {
            start,
            block,
            handlers
          };
        }
        function parseBlockStatement() {
          const start = expect("punctuation", "{");
          const body = [];
          while (!(current().type === "punctuation" && current().value === "}")) {
            if (atEnd()) {
              throw new TranspilerSyntaxError("Unterminated block statement", current());
            }
            body.push(parseStatement());
          }
          expect("punctuation", "}");
          return withLoc({
            type: "BlockStatement",
            body
          }, start, previous());
        }
        function parseBlockInAsyncContext(isAsync) {
          const previousDepth = asyncContextDepth;
          asyncContextDepth = isAsync ? previousDepth + 1 : 0;
          try {
            return parseBlockStatement();
          } finally {
            asyncContextDepth = previousDepth;
          }
        }
        function parseExpressionStatement() {
          const start = current();
          const expression = parseExpression();
          const stmt = withLoc({
            type: "ExpressionStatement",
            expression
          }, start, previous());
          return finishStatement(stmt, "Expected ; after expression");
        }
        function finishStatement(stmt, semicolonMessage) {
          if (current().type === "keyword" && ["if", "unless"].includes(current().value)) {
            const keyword = current();
            index++;
            let test = parseExpression();
            if (keyword.value === "unless") {
              test = withLoc({
                type: "UnaryExpression",
                operator: "not",
                argument: test,
                prefix: true
              }, keyword, endLocFromNode(test));
            }
            consumeStatementTerminator(semicolonMessage);
            const consequent = withLoc({
              type: "BlockStatement",
              body: [stmt]
            }, startLocFromNode(stmt), endLocFromNode(stmt));
            return withLoc({
              type: "IfStatement",
              declaration: null,
              test,
              consequent,
              alternate: null
            }, startLocFromNode(stmt), endLocFromNode(consequent));
          }
          if (current().type === "keyword" && current().value === "for") {
            const keyword = current();
            index++;
            const iterable = parseExpression();
            consumeStatementTerminator(semicolonMessage);
            const body = withLoc({
              type: "BlockStatement",
              body: [stmt]
            }, startLocFromNode(stmt), endLocFromNode(stmt));
            return withLoc({
              type: "ForInStatement",
              kind: "const",
              left: {
                type: "Identifier",
                name: "^^"
              },
              iterable,
              body,
              elseBlock: null
            }, startLocFromNode(stmt), endLocFromNode(iterable) || keyword);
          }
          consumeStatementTerminator(semicolonMessage);
          return stmt;
        }
        function parseExpression() {
          return parseAssignment();
        }
        function parseConditional() {
          return parseConditionalTail(parseLogicalOr());
        }
        function parseConditionalTail(expr) {
          if (match("operator", "?:")) {
            const alternate = parseConditional();
            return withLoc({
              type: "ShortTernaryExpression",
              test: expr,
              alternate
            }, startLocFromNode(expr), endLocFromNode(alternate));
          }
          if (match("operator", "?")) {
            const consequent = parseExpression();
            expect("operator", ":", "Expected : in ternary expression");
            const alternate = parseConditional();
            return withLoc({
              type: "ConditionalExpression",
              test: expr,
              consequent,
              alternate
            }, startLocFromNode(expr), endLocFromNode(alternate));
          }
          return expr;
        }
        function parseAssignment() {
          const left = parseChain();
          if (current().type === "operator" && [":=", "+=", "-=", "*=", "/=", "%=", "**=", "_=", "?:=", "\xD7=", "\xF7="].includes(current().value)) {
            const op = current();
            index++;
            const right = parseAssignment();
            const isWeakWrite = parseOptionalWeakModifier("assignment");
            if (isWeakWrite && op.value !== ":=") {
              throw new TranspilerSyntaxError(
                "but weak is only valid on ':=' assignments",
                op
              );
            }
            if (isWeakWrite && left && left.type === "BinaryExpression" && left.operator === "@?") {
              throw new TranspilerSyntaxError(
                "but weak is not valid on @? path assignments",
                op
              );
            }
            return withLoc({
              type: "AssignmentExpression",
              operator: op.value,
              left,
              right,
              isWeakWrite
            }, startLocFromNode(left), endLocFromNode(right));
          }
          if (current().type === "operator" && current().value === "~=") {
            const op = current();
            index++;
            const pattern = parseChain();
            if (current().type !== "operator" || !(current().value === "->" || current().value === "\u2192")) {
              throw new TranspilerSyntaxError("Expected -> after regex replacement pattern", current());
            }
            index++;
            const replacement = parseAssignment();
            return withLoc({
              type: "RegexReplaceExpression",
              operator: op.value,
              left,
              pattern,
              replacement
            }, startLocFromNode(left), endLocFromNode(replacement));
          }
          return left;
        }
        function chainDirection(token) {
          if (token.type !== "operator") {
            return null;
          }
          if (token.value === "\u25B7" || token.value === "|>") {
            return "right";
          }
          if (token.value === "\u25C1" || token.value === "<|") {
            return "left";
          }
          return null;
        }
        function parseChain() {
          let expr = parseConditional();
          const firstDirection = chainDirection(current());
          if (!firstDirection) {
            return expr;
          }
          let op = current();
          index++;
          const right = firstDirection === "left" ? parseLeftwardChainRhs() : parseConditional();
          expr = withLoc({
            type: "BinaryExpression",
            operator: op.value,
            left: expr,
            right
          }, startLocFromNode(expr), endLocFromNode(right));
          while (firstDirection === "right") {
            const nextDirection = chainDirection(current());
            if (!nextDirection) {
              break;
            }
            if (nextDirection !== firstDirection) {
              throw new TranspilerSyntaxError("Mixed chain directions require parentheses", current());
            }
            op = current();
            index++;
            const nextRight = parseConditional();
            expr = withLoc({
              type: "BinaryExpression",
              operator: op.value,
              left: expr,
              right: nextRight
            }, startLocFromNode(expr), endLocFromNode(nextRight));
          }
          if (firstDirection === "left" && chainDirection(current())) {
            throw new TranspilerSyntaxError("Mixed chain directions require parentheses", current());
          }
          return expr;
        }
        function parseLeftwardChainRhs() {
          const left = parseConditional();
          const direction = chainDirection(current());
          if (!direction) {
            return left;
          }
          if (direction !== "left") {
            throw new TranspilerSyntaxError("Mixed chain directions require parentheses", current());
          }
          const op = current();
          index++;
          const right = parseLeftwardChainRhs();
          return withLoc({
            type: "BinaryExpression",
            operator: op.value,
            left,
            right
          }, startLocFromNode(left), endLocFromNode(right));
        }
        function parseLogicalOr() {
          return parseLeftAssociative(
            parseOnlyif,
            (token) => token.type === "keyword" && ["or", "or?"].includes(token.value) || token.type === "operator" && ["\u22C1", "\u22C1?"].includes(token.value)
          );
        }
        function parseOnlyif() {
          return parseRightAssociative(
            parseLogicalXor,
            (token) => token.type === "keyword" && ["onlyif", "onlyif?"].includes(token.value) || token.type === "operator" && ["\u22A8", "\u22A8?"].includes(token.value)
          );
        }
        function parseLogicalXor() {
          return parseLeftAssociative(
            parseLogicalAnd,
            (token) => token.type === "keyword" && ["xor", "xor?", "nor", "nor?", "xnor", "xnor?"].includes(token.value) || token.type === "operator" && ["\u22BB", "\u22BB?", "\u22BD", "\u22BD?", "\u2194", "\u2194?"].includes(token.value)
          );
        }
        function parseLogicalAnd() {
          return parseLeftAssociative(
            parseEquality,
            (token) => token.type === "keyword" && ["and", "and?", "nand", "nand?", "butnot", "butnot?"].includes(token.value) || token.type === "operator" && ["\u22C0", "\u22C0?", "\u22BC", "\u22BC?", "\u22AD", "\u22AD?"].includes(token.value)
          );
        }
        function parseEquality() {
          return parseLeftAssociative(
            parseBitwise,
            (token) => token.type === "operator" && ["==", "!=", "="].includes(token.value) || token.type === "operator" && ["\u2261", "\u2262", "\u2260"].includes(token.value) || token.type === "keyword" && ["eq", "ne", "default"].includes(token.value)
          );
        }
        function parseBitwise() {
          return parseLeftAssociative(
            parseShift,
            (token) => token.type === "operator" && ["&", "|", "^"].includes(token.value)
          );
        }
        function parseShift() {
          return parseLeftAssociative(
            parseComparison,
            (token) => token.type === "operator" && ["<<", ">>", "\xAB", "\xBB"].includes(token.value) && token.value !== pendingSetClosers[pendingSetClosers.length - 1]
          );
        }
        function parseComparison() {
          return parseLeftAssociative(
            parseRange,
            (token) => token.type === "operator" && ["<", "<=", ">", ">=", "\u2264", "\u2265", "~", "<=>", "@", "@@", "@?", "\\", "\u2208", "\u2209", "\u22C3", "\u22C2", "\u2216", "\u2282", "\u2283", "\u2282\u2283", "\u2276", "\u2277", "\u2223", "\u2224"].includes(token.value) || token.type === "keyword" && ["gt", "ge", "lt", "le", "cmp", "eqi", "nei", "gti", "gei", "lti", "lei", "cmpi", "in", "not_in", "union", "intersection", "difference", "subsetof", "supersetof", "equivalentof", "does", "can", "divides"].includes(token.value) || token.type === "identifier" && token.value === "instanceof"
          );
        }
        function parseRange() {
          return parseLeftAssociative(
            parseTerm,
            (token) => token.type === "operator" && token.value === "..."
          );
        }
        function parseTerm() {
          return parseLeftAssociative(
            parseFactor,
            (token) => token.type === "operator" && ["+", "-", "_"].includes(token.value)
          );
        }
        function parseFactor() {
          return parseLeftAssociative(
            parseUnary,
            (token) => token.type === "operator" && ["*", "/", "%", "**"].includes(token.value) || token.type === "operator" && ["\xD7", "\xF7"].includes(token.value) || token.type === "keyword" && token.value === "mod"
          );
        }
        function parseLeftAssociative(nextFn, predicate) {
          let expr = nextFn();
          while (predicate(current())) {
            const op = current();
            index++;
            const right = nextFn();
            expr = withLoc({
              type: "BinaryExpression",
              operator: op.value,
              left: expr,
              right
            }, startLocFromNode(expr), endLocFromNode(right));
          }
          return expr;
        }
        function parseRightAssociative(nextFn, predicate) {
          const left = nextFn();
          if (!predicate(current())) {
            return left;
          }
          const op = current();
          index++;
          const right = parseRightAssociative(nextFn, predicate);
          return withLoc({
            type: "BinaryExpression",
            operator: op.value,
            left,
            right
          }, startLocFromNode(left), endLocFromNode(right));
        }
        function parseUnary() {
          if (current().type === "operator" && ["-", "+", "++", "--", "!", "~", "\\", "\u221A", "\xAC"].includes(current().value) || current().type === "keyword" && ["not", "typeof", "abs", "sqrt", "floor", "ceil", "round", "int", "length", "uc", "lc"].includes(current().value)) {
            const op = current();
            index++;
            const argument = op.value === "\\" ? parseReferenceTarget() : parseUnary();
            let expr = withLoc({
              type: op.value === "\\" ? "RefExpression" : "UnaryExpression",
              operator: op.value,
              argument,
              prefix: true
            }, startLocFromToken(op), endLocFromNode(argument));
            if (op.value === "\\") {
              expr = parsePostfixSuffixes(expr);
            }
            return expr;
          }
          return parsePostfix();
        }
        function parseReferenceTarget() {
          let expr = parsePrimary();
          while (true) {
            const nextExpr = parseMemberAccess(expr);
            if (nextExpr === expr) {
              break;
            }
            expr = nextExpr;
          }
          return expr;
        }
        function parsePostfix() {
          return parsePostfixSuffixes(parsePrimary());
        }
        function parsePostfixSuffixes(expr) {
          while (true) {
            const nextExpr = parseMemberAccess(expr);
            if (nextExpr !== expr) {
              expr = nextExpr;
              continue;
            }
            if (current().type === "punctuation" && current().value === "(") {
              const args = parseCallArgumentsOnly();
              expr = withLoc({
                type: "CallExpression",
                callee: expr,
                arguments: args
              }, startLocFromNode(expr), endLocFromToken(previous()));
              continue;
            }
            if (current().type === "operator" && ["++", "--"].includes(current().value)) {
              const op = current();
              index++;
              expr = withLoc({
                type: "UpdateExpression",
                operator: op.value,
                argument: expr,
                prefix: false
              }, startLocFromNode(expr), endLocFromToken(op));
              continue;
            }
            break;
          }
          return expr;
        }
        function parseMemberAccess(expr) {
          if (match("punctuation", ".")) {
            if (match("punctuation", "(")) {
              const property2 = parseExpression();
              expect("punctuation", ")", "Expected ) after dynamic member name");
              return withLoc({
                type: "MemberExpression",
                object: expr,
                property: property2,
                computed: true
              }, startLocFromNode(expr), endLocFromToken(previous()));
            }
            const property = expectIdentifier("Expected property name after .");
            return withLoc({
              type: "MemberExpression",
              object: expr,
              property: {
                type: "Identifier",
                name: property.value
              },
              computed: false
            }, startLocFromNode(expr), endLocFromToken(property));
          }
          if (match("punctuation", "[")) {
            const closeBracket = current().type === "punctuation" && current().value === "]";
            const startsWithColon = current().type === "operator" && current().value === ":";
            let first = null;
            if (!closeBracket && !startsWithColon) {
              first = parseExpression();
            }
            if (match("operator", ":")) {
              let second = null;
              if (!(current().type === "punctuation" && current().value === "]")) {
                second = parseExpression();
              }
              expect("punctuation", "]");
              return withLoc({
                type: "SliceExpression",
                object: expr,
                start: first,
                length: second
              }, startLocFromNode(expr), endLocFromToken(previous()));
            }
            if (first == null) {
              throw new TranspilerSyntaxError("Expected index or slice expression", current());
            }
            expect("punctuation", "]");
            return withLoc({
              type: "MemberExpression",
              object: expr,
              property: first,
              computed: true
            }, startLocFromNode(expr), endLocFromToken(previous()));
          }
          if (match("punctuation", "{")) {
            let property;
            if ((current().type === "identifier" || current().type === "keyword") && peekToken().type === "punctuation" && peekToken().value === "}") {
              const key = current();
              index++;
              property = withLoc(
                key.type === "identifier" ? {
                  type: "BraceIdentifier",
                  name: key.value
                } : {
                  type: "StringLiteral",
                  value: key.value
                },
                key,
                key
              );
            } else {
              property = parseExpression();
            }
            expect("punctuation", "}");
            return withLoc({
              type: "MemberExpression",
              object: expr,
              property,
              computed: true
            }, startLocFromNode(expr), endLocFromToken(previous()));
          }
          return expr;
        }
        function parseCallArgumentsOnly() {
          expect("punctuation", "(");
          const args = [];
          let closed = false;
          if (!match("punctuation", ")")) {
            while (true) {
              if (match("punctuation", ",")) {
                if (current().type === "punctuation" && current().value === ")") {
                  break;
                }
                continue;
              }
              if (current().type === "punctuation" && current().value === ")") {
                break;
              }
              args.push(parseCallArgument());
              if (match("punctuation", ")")) {
                closed = true;
                break;
              }
              match("punctuation", ",");
            }
            if (!closed && current().type === "punctuation" && current().value === ")") {
              expect("punctuation", ")", "Expected ) after call arguments");
            }
          }
          return args;
        }
        function parseCallArgument() {
          const start = current();
          if (match("operator", "...")) {
            const argument = parseExpression();
            return withLoc({
              type: "SpreadArgument",
              argument
            }, start, endLocFromNode(argument));
          }
          if (startsNamedKeyBeforeColon()) {
            const normalized = parseNamedKeyBeforeColon();
            expect("operator", ":", "Expected : in named argument");
            const value = parseExpression();
            return withLoc({
              type: "NamedArgument",
              key: normalized.key,
              keyExpr: normalized.keyExpr,
              value
            }, startLocFromNode(normalized.keyExpr), previous());
          }
          const expr = parseExpression();
          if (current().type === "keyword" && current().value === "but") {
            throw new TranspilerSyntaxError(
              "but weak is not valid as a function argument marker",
              current()
            );
          }
          if (current().type === "operator" && current().value === ":") {
            const normalized = normalizeNamedArgumentKey(expr);
            expect("operator", ":", "Expected : in named argument");
            const value = parseExpression();
            return withLoc({
              type: "NamedArgument",
              key: normalized.key,
              keyExpr: normalized.keyExpr,
              value
            }, startLocFromNode(expr), previous());
          }
          return expr;
        }
        function startsNamedKeyBeforeColon() {
          return ["identifier", "keyword", "string"].includes(current().type) && peekToken().type === "operator" && peekToken().value === ":";
        }
        function parseNamedKeyBeforeColon() {
          const token = current();
          index++;
          return {
            key: token.value,
            keyExpr: withLoc({
              type: "StringLiteral",
              value: token.value
            }, token, token)
          };
        }
        function normalizeNamedArgumentKey(expr) {
          if (expr.type === "Identifier") {
            return {
              key: expr.name,
              keyExpr: withLoc({
                type: "StringLiteral",
                value: expr.name
              }, startLocFromNode(expr), endLocFromNode(expr))
            };
          }
          if (expr.type === "StringLiteral") {
            return {
              key: expr.value,
              keyExpr: expr
            };
          }
          if (expr.type === "GroupedExpression") {
            return normalizeNamedArgumentKey(expr.expression);
          }
          if (expr.type === "MemberExpression") {
            if (expr.computed && expr.property.type === "StringLiteral") {
              return {
                key: expr.property.value,
                keyExpr: withLoc({
                  type: "StringLiteral",
                  value: expr.property.value
                }, startLocFromNode(expr.property), endLocFromNode(expr.property))
              };
            }
            if (!expr.computed && expr.property.type === "Identifier") {
              return {
                key: expr.property.name,
                keyExpr: withLoc({
                  type: "StringLiteral",
                  value: expr.property.name
                }, startLocFromNode(expr.property), endLocFromNode(expr.property))
              };
            }
          }
          return {
            key: null,
            keyExpr: expr
          };
        }
        function parsePrimary() {
          const token = current();
          if (match("number")) {
            return withLoc({
              type: "NumericLiteral",
              value: Number(token.value)
            }, token, token);
          }
          if (match("string")) {
            return withLoc({
              type: "StringLiteral",
              value: token.value
            }, token, token);
          }
          if (match("binary_string")) {
            return withLoc({
              type: "BinaryStringLiteral",
              value: token.value
            }, token, token);
          }
          if (match("template")) {
            const parts = parseInterpolationParts(token.value, token);
            return withLoc({
              type: "TemplateLiteral",
              parts
            }, token, token);
          }
          if (match("regexp")) {
            return withLoc({
              type: "RegExpLiteral",
              pattern: token.value.pattern,
              parts: parseInterpolationParts(token.value.parts || [], token),
              flags: token.value.flags
            }, token, token);
          }
          if (token.type === "keyword" && ["true", "false", "null"].includes(token.value)) {
            index++;
            return withLoc({
              type: "Literal",
              value: token.value === "null" ? null : token.value === "true"
            }, token, token);
          }
          if (token.type === "keyword" && token.value === "super") {
            index++;
            return withLoc({
              type: "Super"
            }, token, token);
          }
          if (match("identifier")) {
            return withLoc({
              type: "Identifier",
              name: token.value
            }, token, token);
          }
          if (token.type === "keyword" && token.value === "say") {
            index++;
            return withLoc({
              type: "Identifier",
              name: token.value
            }, token, token);
          }
          if (token.type === "keyword" && token.value === "function") {
            index++;
            const params = parseParameterList();
            const body = parseBlockInAsyncContext(false);
            return withLoc({
              type: "FunctionExpression",
              params,
              isAsync: false,
              body
            }, token, previous());
          }
          if (token.type === "keyword" && token.value === "async") {
            index++;
            if (current().type === "keyword" && current().value === "function") {
              const functionToken = current();
              index++;
              const params = parseParameterList();
              const body = parseBlockInAsyncContext(true);
              return withLoc({
                type: "FunctionExpression",
                params,
                isAsync: true,
                body
              }, token, previous() || functionToken);
            }
            if (current().type === "keyword" && current().value === "fn") {
              return parseFnExpression(token, true);
            }
            throw new TranspilerSyntaxError("Expected function or fn after async", current());
          }
          if (token.type === "keyword" && token.value === "fn") {
            return parseFnExpression(token, false);
          }
          if (token.type === "operator" && (token.value === "->" || token.value === "\u2192")) {
            return parseArrowLambdaExpression(token);
          }
          if (token.type === "keyword" && token.value === "await") {
            if (asyncContextDepth <= 0) {
              throw new TranspilerSyntaxError("await may only be used inside async code", token);
            }
            index++;
            const block = parseBlockStatement();
            return withLoc({
              type: "AwaitExpression",
              block
            }, token, previous());
          }
          if (token.type === "keyword" && token.value === "spawn") {
            if (asyncContextDepth <= 0) {
              throw new TranspilerSyntaxError("spawn may only be used inside async code", token);
            }
            index++;
            const block = parseBlockStatement();
            return withLoc({
              type: "SpawnExpression",
              block
            }, token, previous());
          }
          if (token.type === "keyword" && token.value === "try") {
            const parsed = parseTryLike();
            return withLoc({
              type: "TryExpression",
              block: parsed.block,
              handlers: parsed.handlers
            }, parsed.start, previous());
          }
          if (token.type === "keyword" && token.value === "do") {
            index++;
            const block = parseBlockStatement();
            return withLoc({
              type: "DoExpression",
              block
            }, token, previous());
          }
          if (token.type === "keyword" && token.value === "new") {
            index++;
            let callee = parsePrimary();
            while (true) {
              const nextExpr = parseMemberAccess(callee);
              if (nextExpr === callee) {
                break;
              }
              callee = nextExpr;
            }
            const traits = parseTraitCompositionList();
            if (current().type === "punctuation" && current().value === "(") {
              const args = parseCallArgumentsOnly();
              callee = withLoc({
                type: "CallExpression",
                callee,
                arguments: args
              }, startLocFromNode(callee), endLocFromToken(previous()));
            }
            return withLoc({
              type: "NewExpression",
              callee,
              traits
            }, token, previous());
          }
          if (token.type === "keyword" && ["let", "const"].includes(token.value) && peekToken().type === "punctuation" && peekToken().value === "{") {
            throw new TranspilerSyntaxError(
              "Expected name after let or const in expression",
              peekToken()
            );
          }
          if (token.type === "keyword" && ["let", "const"].includes(token.value)) {
            return parseLetExpression();
          }
          if (token.type === "keyword") {
            index++;
            return withLoc({
              type: "Identifier",
              name: token.value
            }, token, token);
          }
          if (match("operator", "\u230A")) {
            return parseCircumfixUnary(token, "floor", "\u230B", "Expected closing floor operator");
          }
          if (match("operator", "\u2308")) {
            return parseCircumfixUnary(token, "ceil", "\u2309", "Expected closing ceil operator");
          }
          if (match("punctuation", "(")) {
            const expr = parseExpression();
            expect("punctuation", ")", "Expected ) after grouped expression");
            return withLoc({
              type: "GroupedExpression",
              expression: expr
            }, token, previous());
          }
          if (match("punctuation", "[")) {
            const elements = [];
            if (!match("punctuation", "]")) {
              while (true) {
                if (match("punctuation", ",")) {
                  continue;
                }
                if (match("punctuation", "]")) {
                  break;
                }
                elements.push(parseExpression());
                if (match("punctuation", "]")) {
                  break;
                }
                match("punctuation", ",");
              }
            }
            return withLoc({
              type: "ArrayExpression",
              elements
            }, token, previous());
          }
          if (match("operator", "{{")) {
            const opener = previous();
            const entries = [];
            if (!matchPairListClose()) {
              while (true) {
                if (match("punctuation", ",")) {
                  continue;
                }
                if (matchPairListClose()) {
                  break;
                }
                const start = current();
                const literalKey = startsNamedKeyBeforeColon() ? parseNamedKeyBeforeColon() : null;
                const keyExpr = literalKey ? literalKey.keyExpr : parseExpression();
                if (current().type === "operator" && current().value === ":") {
                  const normalized = literalKey || normalizeNamedArgumentKey(keyExpr);
                  expect("operator", ":", "Expected : in pairlist literal");
                  const value = parseExpression();
                  entries.push(withLoc({
                    type: "PairListEntry",
                    key: normalized.key,
                    keyExpr: normalized.keyExpr,
                    value
                  }, startLocFromNode(keyExpr), endLocFromNode(value)));
                } else {
                  entries.push(keyExpr);
                }
                if (matchPairListClose()) {
                  break;
                }
                match("punctuation", ",");
              }
            }
            return withLoc({
              type: "PairListLiteral",
              entries
            }, opener, previous());
          }
          if (match("operator", "<<") || match("operator", "<<<") || match("operator", "\xAB")) {
            const opener = previous();
            const closer = opener.value === "<<<" ? ">>>" : opener.value === "\xAB" ? "\xBB" : ">>";
            const elements = parseDelimitedCollection(closer);
            return withLoc({
              type: opener.value === "<<<" ? "BagLiteral" : "SetLiteral",
              elements
            }, opener, previous());
          }
          if (match("punctuation", "{")) {
            const properties = [];
            if (!match("punctuation", "}")) {
              while (true) {
                if (match("punctuation", ",")) {
                  continue;
                }
                if (match("punctuation", "}")) {
                  break;
                }
                let key;
                if (current().type === "identifier" || current().type === "keyword") {
                  key = current().value;
                  index++;
                } else if (current().type === "string") {
                  key = current().value;
                  index++;
                } else {
                  throw new TranspilerSyntaxError("Expected object literal key", current());
                }
                expect("operator", ":", "Expected : in object literal");
                const value = parseExpression();
                properties.push({ key, value });
                if (match("punctuation", "}")) {
                  break;
                }
                match("punctuation", ",");
              }
            }
            return withLoc({
              type: "ObjectExpression",
              properties
            }, token, previous());
          }
          throw new TranspilerSyntaxError("Unexpected token in expression", token);
        }
        function parseFnExpression(token, isAsync) {
          index++;
          let params;
          if (current().type === "punctuation" && current().value === "(") {
            params = parseParameterList();
          } else {
            params = [parseParameter()];
          }
          if (current().type === "operator" && (current().value === "->" || current().value === "\u2192")) {
            index++;
          } else {
            throw new TranspilerSyntaxError("Expected -> after fn parameters", current());
          }
          const previousDepth = asyncContextDepth;
          asyncContextDepth = isAsync ? previousDepth + 1 : 0;
          let expr;
          try {
            expr = parseExpression();
          } finally {
            asyncContextDepth = previousDepth;
          }
          const returnStmt = withLoc({
            type: "ReturnStatement",
            argument: expr
          }, token, token);
          const body = withLoc({
            type: "BlockStatement",
            body: [returnStmt]
          }, token, token);
          return withLoc({
            type: "FunctionExpression",
            params,
            isAsync,
            body
          }, token, previous() || token);
        }
        function parseArrowLambdaExpression(token) {
          index++;
          const expr = parseExpression();
          const returnStmt = withLoc({
            type: "ReturnStatement",
            argument: expr
          }, token, token);
          const body = withLoc({
            type: "BlockStatement",
            body: [returnStmt]
          }, token, token);
          return withLoc({
            type: "FunctionExpression",
            params: [{
              type: "Parameter",
              name: "^^",
              typeName: null,
              optional: true,
              defaultValue: null,
              rest: false
            }],
            isAsync: false,
            body
          }, token, previous() || token);
        }
        function parseDelimitedCollection(closer) {
          const elements = [];
          if (match("operator", closer)) {
            return elements;
          }
          pendingSetClosers.push(closer);
          try {
            while (true) {
              if (match("punctuation", ",")) {
                continue;
              }
              if (match("operator", closer)) {
                break;
              }
              elements.push(parseExpression());
              if (match("operator", closer)) {
                break;
              }
              match("punctuation", ",");
            }
          } finally {
            pendingSetClosers.pop();
          }
          return elements;
        }
        function parseLetExpression() {
          const start = expect("keyword");
          if (current().type === "punctuation" && current().value === "{") {
            throw new TranspilerSyntaxError(
              "Expected name after let or const in expression",
              current()
            );
          }
          return withLoc({
            type: "LetExpression",
            ...parseVariableDeclarationParts(start)
          }, start, previous());
        }
        function parseCircumfixUnary(start, operator, close, message) {
          const argument = parseExpression();
          expect("operator", close, message);
          return withLoc({
            type: "UnaryExpression",
            operator,
            argument,
            prefix: true
          }, start, previous());
        }
        function parseTemplateExpression(source, token) {
          try {
            return parse(tokenize(source), { expression: true });
          } catch (err) {
            if (err instanceof TranspilerSyntaxError || err instanceof UnsupportedSyntaxError) {
              throw new TranspilerSyntaxError("Invalid template interpolation", token);
            }
            throw err;
          }
        }
        function parseInterpolationParts(parts, token) {
          return parts.map((part) => {
            if (part.type === "text") {
              return withLoc({
                type: "StringLiteral",
                value: part.value
              }, token, token);
            }
            return parseTemplateExpression(part.value, token);
          });
        }
        if (options.expression) {
          return parseExpressionRoot();
        }
        return parseProgram();
      }
      module2.exports = {
        parse
      };
    }
  });

  // lib/transpiler-new/codegen.js
  var require_codegen = __commonJS({
    "lib/transpiler-new/codegen.js"(exports2, module2) {
      "use strict";
      var { UnsupportedSyntaxError } = require_errors();
      var loopCounter = 0;
      var chainCounter = 0;
      var emitContextStack = [];
      function currentEmitContext() {
        return emitContextStack.length > 0 ? emitContextStack[emitContextStack.length - 1] : {};
      }
      function withEmitContext(options, fn2) {
        emitContextStack.push(options || {});
        try {
          return fn2();
        } finally {
          emitContextStack.pop();
        }
      }
      function emitProgram(ast, options = {}) {
        loopCounter = 0;
        chainCounter = 0;
        const syncEval = options.syncEval === true;
        const needsAsyncWrapper = programNeedsAsyncWrapper(ast) || options.asyncImports === true && !syncEval && programContainsImport(ast);
        const expressionDeclaredNames = collectExpressionDeclaredNames(ast.body);
        const sharedOptions = {
          ...options,
          asyncContext: needsAsyncWrapper && !syncEval,
          asyncNames: new Set(collectAsyncFunctionNames(ast.body)),
          evalNames: /* @__PURE__ */ new Set(["eval", ...collectEvalImportNames(ast.body)]),
          weakStorageNames: new Set(collectWeakDeclaredNames(ast.body)),
          scopeNames: /* @__PURE__ */ new Set([
            ...expressionDeclaredNames
          ]),
          bodylessFunctionNames: /* @__PURE__ */ new Set(),
          syncEval,
          topLevel: !syncEval
        };
        if (syncEval) {
          return `( () => {
${emitExpressionBlock({ body: ast.body }, sharedOptions)}
} )()`;
        }
        const body = ast.body.map((stmt) => emitStatement(stmt, {
          ...sharedOptions,
          topLevel: true
        })).join("\n");
        const prelude = emitPredeclaredNames(expressionDeclaredNames);
        const source = [prelude, body].filter(Boolean).join("\n");
        if (needsAsyncWrapper && !syncEval && options.deferAsyncWrapper !== true) {
          return `( async () => {
${source}
} )()`;
        }
        return source;
      }
      function marshalSourceSlice(node, options = currentEmitContext()) {
        if (!options.marshalSource || !node.loc || !node.loc.start || !node.loc.end) {
          return null;
        }
        return options.marshalSource.slice(node.loc.start.offset, node.loc.end.offset);
      }
      function marshalFunctionSource(node, options = currentEmitContext()) {
        const source = marshalSourceSlice(node, options);
        if (!source) {
          return null;
        }
        return source.replace(/^\s*async\s+function\s+[A-Za-z_][A-Za-z0-9_]*/u, "async function").replace(/^\s*function\s+[A-Za-z_][A-Za-z0-9_]*/u, "function");
      }
      function marshalCaptureNames(node, options = currentEmitContext()) {
        const names = /* @__PURE__ */ new Set();
        const declared = new Set([
          ...options.scopeNames || [],
          ...extractDeclaredParamNames(node.params || []),
          node.id && node.id.name,
          "self",
          "true",
          "false",
          "null",
          "__argc__",
          "__file__",
          "__global__",
          "__system__",
          ...options.evalNames || []
        ].filter(Boolean));
        const localKinds = /* @__PURE__ */ new Set([
          "FunctionDeclaration",
          "VariableDeclaration",
          "ClassDeclaration",
          "TraitDeclaration"
        ]);
        function visit(value, parent = null) {
          if (!value || typeof value !== "object") {
            return;
          }
          if (Array.isArray(value)) {
            for (const item of value) {
              visit(item, parent);
            }
            return;
          }
          if (value.type === "Identifier") {
            if (parent && (parent.type === "MemberExpression" && parent.property === value && !parent.computed || parent.type === "FieldDeclaration" && parent.id === value || parent.type === "MethodDeclaration" && parent.id === value)) {
              return;
            }
            if (!declared.has(value.name)) {
              names.add(value.name);
            }
            return;
          }
          if (value.type === "TryStatement") {
            visit(value.block, value);
            for (const handler of value.handlers || []) {
              const paramName = handler.paramName;
              const hadParam = paramName ? declared.has(paramName) : false;
              if (paramName) {
                declared.add(paramName);
              }
              visit(handler.body, handler);
              if (paramName && !hadParam) {
                declared.delete(paramName);
              }
            }
            return;
          }
          if (value.type === "VariableUnpackDeclaration") {
            visit(value.init, value);
            for (const entry of bindingEntriesForPattern(value.pattern)) {
              visit(entry.key, entry);
              visit(entry.defaultValue, entry);
            }
            for (const name2 of declaredNamesForStatement(value)) {
              declared.add(name2);
            }
            return;
          }
          if (localKinds.has(value.type)) {
            for (const name2 of declaredNamesForStatement(value)) {
              declared.add(name2);
            }
          }
          for (const [key, child] of Object.entries(value)) {
            if (key === "loc") {
              continue;
            }
            visit(child, value);
          }
        }
        visit(node.body || node);
        return [...names].filter((name2) => /^[A-Za-z_][A-Za-z0-9_]*$/u.test(name2));
      }
      function marshalMetaExpression(kind, name2, source, captureNames = []) {
        return `{ kind: ${JSON.stringify(kind)}, name: ${JSON.stringify(name2 || null)}, source: ${JSON.stringify(source || "")}, captures: ${marshalCapturesExpression(captureNames)} }`;
      }
      function marshalCapturesExpression(captureNames = []) {
        const captures = captureNames.map((capture) => `${JSON.stringify(capture)}: typeof ${capture} !== "undefined" ? ${capture} : null`).join(", ");
        return `{ ${captures} }`;
      }
      function marshalClassCaptureNames(node, options = currentEmitContext()) {
        const names = new Set(marshalCaptureNames(node, options));
        for (const trait of node.traits || []) {
          if (trait && trait.type === "Identifier") {
            names.add(trait.name);
          }
        }
        for (const field of node.body.filter((entry) => entry.type === "FieldDeclaration")) {
          names.delete(field.id.name);
        }
        for (const entry of node.body) {
          if (entry.id && entry.id.name) {
            names.delete(entry.id.name);
          }
          if (entry.type === "MethodDeclaration") {
            for (const param of extractDeclaredParamNames(entry.params || [])) {
              names.delete(param);
            }
          }
        }
        return [...names];
      }
      function marshalTraitCaptureNames(node, options = currentEmitContext()) {
        const names = new Set(marshalCaptureNames(node, options));
        for (const method of node.body || []) {
          if (method.id && method.id.name) {
            names.delete(method.id.name);
          }
          for (const param of extractDeclaredParamNames(method.params || [])) {
            names.delete(param);
          }
        }
        return [...names];
      }
      function nestedFunctionOptions(options = {}) {
        return {
          marshalSource: options.marshalSource,
          syncEval: options.syncEval,
          asyncContext: options.asyncContext,
          asyncNames: options.asyncNames,
          evalNames: options.evalNames,
          weakStorageNames: options.weakStorageNames,
          scopeNames: options.scopeNames,
          bodylessFunctionNames: options.bodylessFunctionNames,
          chainHereName: options.chainHereName
        };
      }
      function emitStatement(node, options = {}) {
        return withEmitContext(options, () => {
          if (node.exported) {
            return emitExportedStatement(node, options);
          }
          switch (node.type) {
            case "EmptyStatement":
              return ";";
            case "ImportDeclaration":
              return emitImportDeclaration(node, options);
            case "VariableDeclaration": {
              const value = emitVariableDeclarationValue(node);
              return `${node.kind} ${emitExpression(node.id)} = ${value};`;
            }
            case "VariableUnpackDeclaration":
              return emitVariableUnpackDeclaration(node, options);
            case "FunctionDeclaration": {
              const name2 = emitExpression(node.id);
              if (node.isPredeclared) {
                if (options.bodylessFunctionNames) {
                  options.bodylessFunctionNames.add(node.id.name);
                }
                const declaration2 = `let ${name2} = __zuzu_bodyless_function( ${JSON.stringify(node.id.name)} );`;
                return options.topLevel ? `${declaration2}
globalThis[${JSON.stringify(node.id.name)}] = ${name2};` : declaration2;
              }
              const fn2 = emitFunctionLike(node, `${node.isAsync ? "async " : ""}function ${name2}()`, {
                ...nestedFunctionOptions(options),
                returnTypeName: node.returnType,
                callableName: node.id.name,
                asyncContext: node.isAsync === true,
                syncEval: options.syncEval === true
              });
              const meta = marshalMetaExpression(
                "function",
                node.id.name,
                marshalFunctionSource(node, options),
                marshalCaptureNames(node, options)
              );
              if (options.bodylessFunctionNames && options.bodylessFunctionNames.has(node.id.name)) {
                options.bodylessFunctionNames.delete(node.id.name);
                return `${name2} = __zuzu_complete_function( ${name2}, ${fn2}, ${meta} );`;
              }
              const declaration = `const ${name2} = __zuzu_with_marshal_meta( ${fn2}, ${meta} );`;
              return options.topLevel ? `${declaration}
globalThis[${JSON.stringify(node.id.name)}] = ${name2};` : declaration;
            }
            case "ReturnStatement": {
              if (node.argument == null && !options.returnTypeName) {
                return options.inSwitchSection ? "return { __zuzu_return: true, value: undefined };" : "return;";
              }
              const value = node.argument ? emitReturnValue(node.argument, options) : emitReturnValue(null, options);
              if (options.inSwitchSection) {
                return `return { __zuzu_return: true, value: ${value} };`;
              }
              if (options.returnSlotName) {
                return `return (${options.returnSlotName} = ${value});`;
              }
              return node.argument ? `return ${value};` : `return ${value};`;
            }
            case "IfStatement":
              return [
                node.declaration ? emitStatement(node.declaration, options) : "",
                `if ( __zuzu_truthy( ${emitExpression(node.test)} ) ) ${emitBlock(node.consequent, options)}`,
                node.alternate ? `else ${node.alternate.type === "BlockStatement" ? emitBlock(node.alternate, options) : emitStatement(node.alternate, options)}` : ""
              ].filter(Boolean).join(" ");
            case "BlockStatement":
              return emitBlock(node, options);
            case "ExpressionStatement":
              return `${emitExpression(node.expression)};`;
            case "ForInStatement":
              return emitForInStatement(node, options);
            case "WhileStatement":
              return [
                node.declaration ? emitStatement(node.declaration, options) : "",
                `while ( __zuzu_truthy( ${emitExpression(node.test)} ) ) ${emitBlock(node.body, {
                  ...options,
                  loopDepth: (options.loopDepth || 0) + 1
                })}`
              ].filter(Boolean).join("\n");
            case "ContinueStatement":
              if (options.inSwitchSection && (options.loopDepth || 0) === 0) {
                return "return true;";
              }
              return "continue;";
            case "BreakStatement":
              return "break;";
            case "ThrowStatement":
              return `__zuzu_throw( ${emitExpression(node.argument)}, ${JSON.stringify(node.loc.start.line)} );`;
            case "DieStatement":
              return `__zuzu_die( ${emitExpression(node.argument)} );`;
            case "WarnStatement":
              return `__zuzu_warn( ${emitExpression(node.argument)} );`;
            case "AssertStatement":
              return `__zuzu_assert( () => ${emitExpression(node.argument)} );`;
            case "DebugStatement":
              return emitDebugStatement(node);
            case "TryStatement":
              return emitTryStatement(node, options);
            case "SwitchStatement":
              return emitSwitchStatement(node, options);
            case "ClassDeclaration":
              return emitClassDeclaration(node, options);
            case "TraitDeclaration":
              return emitTraitDeclaration(node, options);
            default:
              throw new UnsupportedSyntaxError(`Unsupported statement node ${node.type}`);
          }
        });
      }
      function emitExportedStatement(node, options = {}) {
        if (node.type === "VariableUnpackDeclaration") {
          const unexported2 = {
            ...node,
            exported: false
          };
          return [
            emitStatement(unexported2, options),
            ...declaredNamesForStatement(node).map((name3) => `module.exports[${JSON.stringify(name3)}] = ${name3};`)
          ].join("\n");
        }
        if (!node.id || !node.id.name) {
          throw new UnsupportedSyntaxError(`Cannot export statement node ${node.type}`);
        }
        const unexported = {
          ...node,
          exported: false
        };
        const name2 = node.id.name;
        return [
          emitStatement(unexported, options),
          `module.exports[${JSON.stringify(name2)}] = ${name2};`
        ].join("\n");
      }
      function emitDebugStatement(node) {
        const args = node.arguments || [];
        const level = args[0] ? emitExpression(args[0]) : "0";
        const message = args[1] ? emitExpression(args[1]) : '""';
        return `__zuzu_debug( () => ${level}, () => ${message} );`;
      }
      function emitFunctionLike(node, header, options = {}) {
        const signature = analyzeSpecialSignature(node.params);
        const cleanupNames = collectCleanupNames(node.body);
        const returnSlotName = cleanupNames.length > 0 ? "__zuzu_returning" : null;
        const functionOptions = {
          ...createFunctionOptions(node, options),
          returnSlotName
        };
        const bodySource = withEmitContext(
          functionOptions,
          () => emitFunctionBlock(node.body, cleanupNames, functionOptions)
        );
        const cleanup = cleanupNames.map((name2) => `__zuzu_maybe_demolish( ${name2}, ${returnSlotName} );`).join("\n");
        const bodyWrapper = [
          returnSlotName ? `let ${returnSlotName} = null;` : "",
          "try {",
          bodySource,
          "} catch ( __zuzu_nonlocal ) {",
          returnSlotName ? `if ( __zuzu_nonlocal && __zuzu_nonlocal.__zuzu_nonlocal_return ) { ${returnSlotName} = __zuzu_nonlocal.value; return ${returnSlotName}; }` : "if ( __zuzu_nonlocal && __zuzu_nonlocal.__zuzu_nonlocal_return ) { return __zuzu_nonlocal.value; }",
          "throw __zuzu_nonlocal;",
          "}",
          cleanupNames.length > 0 ? "finally {" : "",
          cleanupNames.length > 0 ? cleanup : "",
          cleanupNames.length > 0 ? "}" : ""
        ].filter(Boolean).join("\n");
        if (node.isAsync === true) {
          const taskName = options.callableName || (node.id ? node.id.name : null) || "<async>";
          const line = node.loc && node.loc.start ? node.loc.start.line : null;
          const syncHeader = header.replace(/^async\s+/u, "");
          const taskHelper = options.syncEval ? "__zuzu_task_sync" : "__zuzu_task";
          const executorPrefix = options.syncEval ? "()" : "async ()";
          return [
            `${syncHeader} {`,
            `return ${taskHelper}( ${executorPrefix} => {`,
            emitFunctionPreamble(node.params, signature),
            options.extraPreamble || "",
            ...cleanupNames.map((name2) => `let ${name2} = null;`),
            bodyWrapper,
            `}, { name: ${JSON.stringify(taskName)}, line: ${JSON.stringify(line)} } );`,
            "}"
          ].filter(Boolean).join("\n");
        }
        return [
          `${header} {`,
          emitFunctionPreamble(node.params, signature),
          options.extraPreamble || "",
          ...cleanupNames.map((name2) => `let ${name2} = null;`),
          bodyWrapper,
          "}"
        ].filter(Boolean).join("\n");
      }
      function emitFunctionBodyStatement(node, cleanupNames, options = {}) {
        if (node.type === "VariableDeclaration" && node.id && cleanupNames.includes(node.id.name)) {
          return `${emitExpression(node.id)} = ${emitVariableDeclarationValue(node)};`;
        }
        if (node.type === "VariableUnpackDeclaration" && bindingEntriesForPattern(node.pattern).some((entry) => cleanupNames.includes(entry.name))) {
          return emitVariableUnpackAssignments(node);
        }
        return emitStatement(node, options);
      }
      function emitFunctionBlock(block, cleanupNames, options = {}) {
        if (!block || !Array.isArray(block.body) || block.body.length === 0) {
          return "";
        }
        return emitFunctionStatements(block.body, cleanupNames, options);
      }
      function emitFunctionStatements(statements, cleanupNames, options = {}) {
        const lines = [];
        const lastIndex = statements.length - 1;
        for (let i = 0; i < statements.length; i++) {
          const stmt = statements[i];
          if (stmt.type === "VariableUnpackDeclaration") {
            const unpack = emitVariableUnpackParts(stmt);
            const rest = emitFunctionStatements(
              statements.slice(i + 1),
              cleanupNames,
              {
                ...options,
                scopeNames: /* @__PURE__ */ new Set([
                  ...options.scopeNames || [],
                  ...declaredNamesForStatement(stmt)
                ])
              }
            );
            lines.push(...unpack.prelude);
            lines.push("{");
            lines.push(...unpack.declarations);
            lines.push(emitUnpackScopedRest(stmt, rest));
            lines.push("}");
            return lines.filter((line) => line !== "").join("\n");
          }
          if (i === lastIndex) {
            lines.push(emitFunctionTailStatement(stmt, cleanupNames, options));
          } else {
            lines.push(emitFunctionBodyStatement(stmt, cleanupNames, options));
          }
        }
        return lines.join("\n");
      }
      function emitFunctionTailStatement(stmt, cleanupNames, options = {}) {
        if (stmt.type === "ExpressionStatement") {
          return `return ${emitExpression(stmt.expression)};`;
        }
        if (stmt.type === "BlockStatement") {
          return emitBlock(stmt, options);
        }
        if (stmt.type === "IfStatement") {
          const prefix = stmt.declaration ? `${emitStatement(stmt.declaration, options)}
` : "";
          const alternate = stmt.alternate ? emitFunctionTailStatement(stmt.alternate, cleanupNames, options) : "return null;";
          return `${prefix}if ( __zuzu_truthy( ${emitExpression(stmt.test, options)} ) ) { ${emitFunctionBlock(stmt.consequent, cleanupNames, options)} } else { ${alternate} }`;
        }
        return emitFunctionBodyStatement(stmt, cleanupNames, options);
      }
      function collectCleanupNames(block) {
        const names = [];
        for (const stmt of block.body) {
          if (["VariableDeclaration", "ClassDeclaration", "TraitDeclaration"].includes(stmt.type)) {
            for (const name2 of declaredNamesForStatement(stmt)) {
              if (name2 !== "self") {
                names.push(name2);
              }
            }
          }
        }
        names.push(...collectExpressionDeclaredNames(block.body));
        return [...new Set(names)];
      }
      function collectWeakDeclaredNames(statements = []) {
        const names = [];
        for (const stmt of statements || []) {
          if (stmt.type === "VariableDeclaration" && stmt.isWeakStorage && stmt.id && stmt.id.name) {
            names.push(stmt.id.name);
          } else if (stmt.type === "VariableUnpackDeclaration") {
            for (const entry of bindingEntriesForPattern(stmt.pattern)) {
              if (entry.isWeakStorage && entry.name) {
                names.push(entry.name);
              }
            }
          }
        }
        names.push(...collectExpressionDeclaredEntries(statements).filter((entry) => entry.isWeakStorage).map((entry) => entry.name));
        return [...new Set(names)];
      }
      function createFunctionOptions(node, options = {}) {
        const signature = analyzeSpecialSignature(node.params);
        const paramNames = extractDeclaredParamNames(node.params);
        const body = node.body ? node.body.body : [];
        const expressionDeclaredNames = collectExpressionDeclaredNames(body);
        const hereParamName = (node.params || []).some((param) => param.type === "Parameter" && param.name === "^^") ? "__zuzu_here" : null;
        return {
          ...options,
          returnTypeName: options.returnTypeName || node.returnType || null,
          callableName: options.callableName || (node.id ? node.id.name : null),
          asyncContext: node.isAsync === true || options.asyncContext === true,
          asyncNames: /* @__PURE__ */ new Set([...options.asyncNames || [], ...collectAsyncFunctionNames(body)]),
          weakStorageNames: /* @__PURE__ */ new Set([
            ...options.weakStorageNames || [],
            ...collectWeakDeclaredNames(body)
          ]),
          scopeNames: /* @__PURE__ */ new Set([
            ...options.scopeNames || [],
            ...paramNames,
            ...hereParamName ? [hereParamName] : [],
            ...extractSpecialPreludeNames(signature),
            ...expressionDeclaredNames
          ]),
          bodylessFunctionNames: /* @__PURE__ */ new Set(),
          chainHereName: hereParamName || options.chainHereName,
          returnSlotName: null
        };
      }
      function extractDeclaredParamNames(params) {
        const names = [];
        for (const param of params) {
          if (param.type === "Parameter") {
            names.push(param.name);
          } else if (param.type === "SpecialParameter") {
            if (param.leadName) {
              names.push(param.leadName);
            }
            names.push(param.name);
          }
        }
        return names;
      }
      function extractSpecialPreludeNames(signature) {
        if (!signature) {
          return [];
        }
        switch (signature.kind) {
          case "pairlist_only":
            return ["__zuzu_call_args", signature.namedName];
          case "pairlist_rest_array":
          case "rest_array_pairlist":
            return ["__zuzu_call_args", signature.namedName, signature.restName, "__a"];
          case "lead_pairlist":
            return ["__zuzu_call_args", signature.headName, signature.namedName, signature.restName, "__i", "__a"];
          case "trail_pairlist":
            return ["__zuzu_call_args", signature.headName, signature.restName, signature.namedName, "__i", "__a"];
          case "scalar_pairlist":
            return ["__zuzu_call_args", signature.headName, signature.namedName, "__i", "__a"];
          case "scalar_pairlist_array":
            return ["__zuzu_call_args", signature.headName, signature.namedName, signature.restName, "__i", "__a"];
          case "variadic":
            return ["__zuzu_call_args", signature.headName, signature.restName, "__i", "__a"];
          default:
            return [];
        }
      }
      function analyzeSpecialSignature(params) {
        if (params.length === 1 && params[0].type === "SpecialParameter" && params[0].special === "rest_only" && params[0].containerType === "PairList") {
          return {
            kind: "pairlist_only",
            namedName: params[0].name
          };
        }
        if (params.length === 2 && params[0].type === "SpecialParameter" && params[0].special === "rest_only" && params[0].containerType === "Array" && params[1].type === "Parameter" && params[1].typeName === "PairList") {
          return {
            kind: "rest_array_pairlist",
            restName: params[0].name,
            namedName: params[1].name
          };
        }
        if (params.length === 2 && params[0].type === "SpecialParameter" && params[0].special === "rest_only" && params[0].containerType === "PairList" && params[1].type === "Parameter" && (params[1].typeName === "Array" || params[1].typeName == null)) {
          return {
            kind: "pairlist_rest_array",
            namedName: params[0].name,
            restName: params[1].name
          };
        }
        if (params.length === 2 && params[0].type === "SpecialParameter" && params[0].special === "lead_rest" && params[0].containerType === "PairList" && params[1].type === "Parameter" && (params[1].typeName === "Array" || params[1].typeName == null)) {
          return {
            kind: "lead_pairlist",
            headName: params[0].leadName,
            namedName: params[0].name,
            restName: params[1].name
          };
        }
        if (params.length === 2 && params[0].type === "SpecialParameter" && params[0].special === "lead_rest" && params[0].containerType === "Array" && params[1].type === "Parameter" && params[1].typeName === "PairList") {
          return {
            kind: "trail_pairlist",
            headName: params[0].leadName,
            restName: params[0].name,
            namedName: params[1].name
          };
        }
        if (params.length === 2 && params[0].type === "Parameter" && params[1].type === "SpecialParameter" && params[1].special === "rest_only" && params[1].containerType === "PairList") {
          return {
            kind: "scalar_pairlist",
            headName: params[0].name,
            namedName: params[1].name
          };
        }
        if (params.length === 3 && params[0].type === "Parameter" && params[1].type === "SpecialParameter" && params[1].special === "rest_only" && params[1].containerType === "PairList" && params[2].type === "Parameter" && (params[2].typeName === "Array" || params[2].typeName == null)) {
          return {
            kind: "scalar_pairlist_array",
            headName: params[0].name,
            namedName: params[1].name,
            restName: params[2].name
          };
        }
        if (params.length === 1 && params[0].type === "SpecialParameter" && params[0].special === "lead_rest" && params[0].containerType === "Array") {
          return {
            kind: "variadic",
            headName: params[0].leadName,
            restName: params[0].name
          };
        }
        return null;
      }
      function emitFunctionPreamble(params, signature = null) {
        if (signature) {
          return emitSpecialFunctionPreamble(signature);
        }
        const lines = [];
        const required = params.reduce((count, param) => {
          if (param.type === "Parameter") {
            return count + (!param.optional && param.defaultValue == null && !param.rest ? 1 : 0);
          }
          if (param.type === "SpecialParameter" && param.special === "lead_rest") {
            return count + 1;
          }
          return count;
        }, 0);
        lines.push("const __argc__ = arguments.length;");
        lines.push(`if ( arguments.length < ${required} ) { throw new Error( "Wrong number of arguments" ); }`);
        let argIndex = 0;
        for (const param of params) {
          if (param.type === "SpecialParameter") {
            if (param.special === "lead_rest") {
              lines.push(`const ${param.leadName} = arguments[${argIndex}];`);
              argIndex++;
              lines.push(`const ${param.name} = Array.prototype.slice.call( arguments, ${argIndex} );`);
              continue;
            }
            if (param.special === "rest_only") {
              if (param.containerType === "PairList") {
                lines.push(`let ${param.name} = __zuzu_pairlist_literal( [] );`);
                lines.push(`for ( let __i = ${argIndex}; __i < arguments.length; __i++ ) {`);
                lines.push("const __a = arguments[__i];");
                lines.push(`if ( __zuzu_is_pairlist( __a ) ) { ${param.name} = __a; } else { throw new Exception( "named PairList parameter only accepts named arguments" ); }`);
                lines.push("}");
              } else {
                lines.push(`const ${param.name} = Array.prototype.slice.call( arguments, ${argIndex} );`);
              }
              continue;
            }
          }
          if (param.type !== "Parameter") {
            continue;
          }
          const paramName = param.name === "^^" ? "__zuzu_here" : param.name;
          if (param.rest) {
            lines.push(`const ${paramName} = Array.prototype.slice.call( arguments, ${argIndex} );`);
            continue;
          }
          if (param.defaultValue) {
            lines.push(`const ${paramName} = __argc__ > ${argIndex} ? arguments[${argIndex}] : ${emitExpression(param.defaultValue)};`);
          } else if (param.optional) {
            lines.push(`const ${paramName} = __argc__ > ${argIndex} ? arguments[${argIndex}] : null;`);
          } else {
            lines.push(`const ${paramName} = arguments[${argIndex}];`);
          }
          if (param.typeName) {
            lines.push(
              `if ( ${paramName} != null && !__zuzu_type_matches( ${paramName}, ${JSON.stringify(param.typeName)} ) ) { throw new Error( \`TypeException: '${param.name}' must be ${param.typeName}, got \${ __zuzu_typeof( ${paramName} ) }\` ); }`
            );
          }
          argIndex++;
        }
        return lines.join("\n");
      }
      function emitSpecialFunctionPreamble(signature) {
        switch (signature.kind) {
          case "pairlist_only":
            return [
              `const __zuzu_call_args = Array.prototype.slice.call( arguments );`,
              "let __zuzu_named_args = __zuzu_pairlist_literal( [] );",
              "for ( const __a of __zuzu_call_args ) {",
              'if ( __zuzu_is_pairlist( __a ) ) { __zuzu_named_args = __a; } else { throw new Exception( "named PairList parameter only accepts named arguments" ); }',
              "}",
              `const ${signature.namedName} = __zuzu_named_args;`
            ].join("\n");
          case "pairlist_rest_array":
          case "rest_array_pairlist":
            return [
              `const __zuzu_call_args = Array.prototype.slice.call( arguments );`,
              "let __zuzu_named_args = __zuzu_pairlist_literal( [] );",
              "const __zuzu_rest_args = [];",
              "for ( const __a of __zuzu_call_args ) {",
              "if ( __zuzu_is_pairlist( __a ) ) { __zuzu_named_args = __a; } else { __zuzu_rest_args.push( __a ); }",
              "}",
              `const ${signature.namedName} = __zuzu_named_args;`,
              `const ${signature.restName} = __zuzu_rest_args;`
            ].join("\n");
          case "lead_pairlist":
            return [
              "const __zuzu_call_args = Array.prototype.slice.call( arguments );",
              `const ${signature.headName} = __zuzu_call_args[0];`,
              "let __zuzu_named_args = __zuzu_pairlist_literal( [] );",
              "const __zuzu_rest_args = [];",
              "for ( let __i = 1; __i < __zuzu_call_args.length; __i++ ) {",
              "const __a = __zuzu_call_args[__i];",
              "if ( __zuzu_is_pairlist( __a ) ) { __zuzu_named_args = __a; } else { __zuzu_rest_args.push( __a ); }",
              "}",
              `const ${signature.namedName} = __zuzu_named_args;`,
              `const ${signature.restName} = __zuzu_rest_args;`
            ].join("\n");
          case "trail_pairlist":
            return [
              "const __zuzu_call_args = Array.prototype.slice.call( arguments );",
              `const ${signature.headName} = __zuzu_call_args[0];`,
              "const __zuzu_rest_args = [];",
              "let __zuzu_named_args = __zuzu_pairlist_literal( [] );",
              "for ( let __i = 1; __i < __zuzu_call_args.length; __i++ ) {",
              "const __a = __zuzu_call_args[__i];",
              "if ( __zuzu_is_pairlist( __a ) ) { __zuzu_named_args = __a; } else { __zuzu_rest_args.push( __a ); }",
              "}",
              `const ${signature.restName} = __zuzu_rest_args;`,
              `const ${signature.namedName} = __zuzu_named_args;`
            ].join("\n");
          case "scalar_pairlist":
            return [
              "const __zuzu_call_args = Array.prototype.slice.call( arguments );",
              `const ${signature.headName} = __zuzu_call_args[0];`,
              "let __zuzu_named_args = __zuzu_pairlist_literal( [] );",
              "for ( let __i = 1; __i < __zuzu_call_args.length; __i++ ) {",
              "const __a = __zuzu_call_args[__i];",
              'if ( __zuzu_is_pairlist( __a ) ) { __zuzu_named_args = __a; } else { throw new Exception( "named arguments not allowed for this function" ); }',
              "}",
              `const ${signature.namedName} = __zuzu_named_args;`
            ].join("\n");
          case "scalar_pairlist_array":
            return [
              "const __zuzu_call_args = Array.prototype.slice.call( arguments );",
              `const ${signature.headName} = __zuzu_call_args[0];`,
              "let __zuzu_named_args = __zuzu_pairlist_literal( [] );",
              "const __zuzu_rest_args = [];",
              "for ( let __i = 1; __i < __zuzu_call_args.length; __i++ ) {",
              "const __a = __zuzu_call_args[__i];",
              "if ( __zuzu_is_pairlist( __a ) ) { __zuzu_named_args = __a; } else { __zuzu_rest_args.push( __a ); }",
              "}",
              `const ${signature.restName} = __zuzu_rest_args;`,
              `const ${signature.namedName} = __zuzu_named_args;`
            ].join("\n");
          case "variadic":
            return [
              "const __zuzu_call_args = Array.prototype.slice.call( arguments );",
              `const ${signature.headName} = __zuzu_call_args[0];`,
              "const __zuzu_rest_args = [];",
              "for ( let __i = 1; __i < __zuzu_call_args.length; __i++ ) {",
              "const __a = __zuzu_call_args[__i];",
              'if ( __zuzu_is_pairlist( __a ) ) { throw new Exception( "named arguments not allowed for this function" ); } __zuzu_rest_args.push( __a );',
              "}",
              `const ${signature.restName} = __zuzu_rest_args;`
            ].join("\n");
          default:
            return "";
        }
      }
      function emitReturnValue(argument, options = {}) {
        let value;
        if (argument == null) {
          value = "undefined";
        } else {
          value = emitExpression(argument);
        }
        if (options.returnTypeName && options.returnTypeName !== "Any") {
          return `__zuzu_checked_return( ${JSON.stringify(options.callableName || "")}, ${JSON.stringify(options.returnTypeName)}, ${value} )`;
        }
        return value;
      }
      function emitForInStatement(node, options = {}) {
        const loopId = loopCounter++;
        const implicitHere = node.left.name === "^^";
        const loopName = implicitHere ? `__zuzu_loop_here_${loopId}` : node.left.name;
        const iterName = `__zuzu_iterated_${implicitHere ? "here" : node.left.name}_${loopId}`;
        const elsePart = node.elseBlock ? `if ( !${iterName} ) ${emitBlock(node.elseBlock, options)}` : "";
        const loopKeyword = node.kind ? `${node.kind} ` : "";
        const bodyOptions = implicitHere ? {
          ...options,
          chainHereName: loopName
        } : options;
        return [
          `let ${iterName} = 0;`,
          `for ( ${loopKeyword}${loopName} of __zuzu_iter( ${emitExpression(node.iterable)} ) ) {`,
          `${iterName} = 1;`,
          node.body.body.map((stmt) => emitStatement(stmt, {
            ...bodyOptions,
            loopDepth: (options.loopDepth || 0) + 1
          })).join("\n"),
          "}",
          elsePart
        ].filter(Boolean).join("\n");
      }
      function emitTryStatement(node, options = {}) {
        const handlers = node.handlers || [];
        let catchBody = "throw __zuzu_err;";
        if (handlers.length > 0) {
          const branches = handlers.map((handler, index) => {
            const cond = handler.typeName === "Exception" || handler.typeName === "Any" ? "true" : `__zuzu_instanceof( __zuzu_err, ${handler.typeName} )`;
            const prefix = index === 0 ? `if ( ${cond} )` : `else if ( ${cond} )`;
            return `${prefix} { let ${handler.paramName} = __zuzu_err; ${handler.body.body.map((stmt) => emitStatement(stmt, options)).join("\n")} }`;
          });
          catchBody = `if ( __zuzu_err && __zuzu_err.__zuzu_nonlocal_return ) { throw __zuzu_err; } __zuzu_err = __zuzu_normalize_exception( __zuzu_err ); ${branches.join(" ")} else { throw __zuzu_err; }`;
        }
        return `try ${emitBlock(node.block, options)} catch ( __zuzu_err ) { ${catchBody} }`;
      }
      function emitImportDeclaration(node, options = {}) {
        const asyncImport = options.asyncImports === true && options.syncEval !== true;
        const importModule = () => {
          const call = `__zuzu_import( ${JSON.stringify(node.source)} )`;
          return asyncImport ? `await ${call}` : call;
        };
        if (node.importAll) {
          if (options.syncEval) {
            return `{ const __zuzu_star = __zuzu_import( ${JSON.stringify(node.source)} ); }`;
          }
          if (node.source === "std/eval") {
            return `{ const __zuzu_star = ${importModule()}; for ( const __zuzu_key of Object.keys( __zuzu_star ) ) { if ( __zuzu_key === "eval" ) { continue; } const __zuzu_desc = Object.create( null ); __zuzu_desc.configurable = true; __zuzu_desc.enumerable = true; __zuzu_desc.get = function() { return __zuzu_star[ __zuzu_key ] ?? null; }; __zuzu_desc.set = function( value ) { __zuzu_star[ __zuzu_key ] = value; }; Object.defineProperty( globalThis, __zuzu_key, __zuzu_desc ); } }`;
          }
          return `{ const __zuzu_star = ${importModule()}; if ( Object.prototype.hasOwnProperty.call( __zuzu_star, "done_testing" ) ) { var done_testing = __zuzu_star.done_testing ?? null; } for ( const __zuzu_key of Object.keys( __zuzu_star ) ) { if ( __zuzu_key === "done_testing" ) { continue; } const __zuzu_desc = Object.create( null ); __zuzu_desc.configurable = true; __zuzu_desc.enumerable = true; __zuzu_desc.get = function() { return __zuzu_star[ __zuzu_key ] ?? null; }; __zuzu_desc.set = function( value ) { __zuzu_star[ __zuzu_key ] = value; }; Object.defineProperty( globalThis, __zuzu_key, __zuzu_desc ); } }`;
        }
        const moduleName = `__zuzu_imported_${Math.abs(hashString(node.source))}_${node.specifiers.length}_${options.syncEval ? loopCounter++ : 0}`;
        const defineImports = node.specifiers.map((specifier) => {
          const importedName = normalizeImportedName(node.source, specifier.imported);
          if (node.source === "std/eval" && importedName === "eval") {
            return "";
          }
          return defineLiveImport(specifier.local, moduleName, importedName, options);
        }).filter(Boolean);
        const legacyImports = node.specifiers.map((specifier) => {
          const importedName = normalizeImportedName(node.source, specifier.imported);
          const mapped = importedName === specifier.local ? importedName : `${importedName}: ${specifier.local}`;
          return node.tryMode ? `${mapped} = null` : mapped;
        });
        const legacyShape = `/* const { ${legacyImports.join(", ")} } = __zuzu_import( ${JSON.stringify(node.source)} ); */`;
        const importCondition = node.condition ? node.condition.keyword === "unless" ? `!__zuzu_truthy( ${emitExpression(node.condition.test)} )` : `__zuzu_truthy( ${emitExpression(node.condition.test)} )` : null;
        const disabledImports = `{ ${node.specifiers.map((specifier) => {
          const importedName = normalizeImportedName(node.source, specifier.imported);
          return `${importedName}: null`;
        }).join(", ")} }`;
        if (options.syncEval) {
          if (node.tryMode) {
            return [
              `const ${moduleName} = ( () => {`,
              "try {",
              importCondition ? `if ( !( ${importCondition} ) ) { return {}; }` : "",
              `return __zuzu_import( ${JSON.stringify(node.source)} );`,
              "}",
              "catch ( __zuzu_err ) {",
              "if ( __zuzu_err && __zuzu_err.__zuzu_nonlocal_return ) { throw __zuzu_err; }",
              "return {};",
              "}",
              "} )();",
              ...defineImports
            ].filter(Boolean).join(" ");
          }
          if (importCondition) {
            return [
              `const ${moduleName} = ( () => {`,
              `if ( !( ${importCondition} ) ) { return ${disabledImports}; }`,
              `return __zuzu_import( ${JSON.stringify(node.source)} );`,
              "} )();",
              ...defineImports
            ].join(" ");
          }
          return `const ${moduleName} = __zuzu_import( ${JSON.stringify(node.source)} ); ${defineImports.join(" ")}`;
        }
        if (node.tryMode) {
          if (asyncImport) {
            return [
              `{ ${legacyShape} const ${moduleName} = await ( async () => {`,
              "try {",
              importCondition ? `if ( !( ${importCondition} ) ) { return {}; }` : "",
              `return ${importModule()};`,
              "}",
              "catch ( __zuzu_err ) {",
              "if ( __zuzu_err && __zuzu_err.__zuzu_nonlocal_return ) { throw __zuzu_err; }",
              "return {};",
              "}",
              "} )();",
              ...defineImports,
              "}"
            ].filter(Boolean).join(" ");
          }
          return [
            `{ ${legacyShape} const ${moduleName} = ( () => {`,
            "try {",
            importCondition ? `if ( !( ${importCondition} ) ) { return {}; }` : "",
            `return __zuzu_import( ${JSON.stringify(node.source)} );`,
            "}",
            "catch ( __zuzu_err ) {",
            "if ( __zuzu_err && __zuzu_err.__zuzu_nonlocal_return ) { throw __zuzu_err; }",
            "return {};",
            "}",
            "} )();",
            ...defineImports,
            "}"
          ].filter(Boolean).join(" ");
        }
        if (importCondition) {
          if (asyncImport) {
            return [
              `{ ${legacyShape} const ${moduleName} = await ( async () => {`,
              `if ( !( ${importCondition} ) ) { return ${disabledImports}; }`,
              `return ${importModule()};`,
              "} )();",
              ...defineImports,
              "}"
            ].join(" ");
          }
          return [
            `{ ${legacyShape} const ${moduleName} = ( () => {`,
            `if ( !( ${importCondition} ) ) { return ${disabledImports}; }`,
            `return __zuzu_import( ${JSON.stringify(node.source)} );`,
            "} )();",
            ...defineImports,
            "}"
          ].join(" ");
        }
        return `{ ${legacyShape} const ${moduleName} = ${importModule()}; ${defineImports.join(" ")} }`;
      }
      function normalizeImportedName(source, imported) {
        return source === "std/math" && imported === "pi" ? "\u03C0" : imported;
      }
      function hashString(value) {
        let hash = 0;
        for (let i = 0; i < value.length; i++) {
          hash = (hash << 5) - hash + value.charCodeAt(i);
          hash |= 0;
        }
        return hash;
      }
      function defineLiveImport(localName, moduleName, importedName, options = {}) {
        if (options.syncEval) {
          return `const ${localName} = ${moduleName}[${JSON.stringify(importedName)}] ?? null;`;
        }
        if (localName === "done_testing") {
          return `var done_testing = ${moduleName}[${JSON.stringify(importedName)}] ?? null;`;
        }
        return [
          "{",
          "const __zuzu_desc = Object.create( null );",
          "__zuzu_desc.configurable = true;",
          "__zuzu_desc.enumerable = true;",
          `__zuzu_desc.get = function() { return ${moduleName}[${JSON.stringify(importedName)}] ?? null; };`,
          `__zuzu_desc.set = function( value ) { ${moduleName}[${JSON.stringify(importedName)}] = value; };`,
          "Object.defineProperty( globalThis,",
          `${JSON.stringify(localName)},`,
          "__zuzu_desc );",
          "}"
        ].join(" ");
      }
      function emitBlock(node, options = {}) {
        const expressionDeclaredNames = collectExpressionDeclaredNames(node.body);
        const scopedOptions = {
          ...options,
          asyncNames: /* @__PURE__ */ new Set([...options.asyncNames || [], ...collectAsyncFunctionNames(node.body)]),
          weakStorageNames: /* @__PURE__ */ new Set([
            ...options.weakStorageNames || [],
            ...collectWeakDeclaredNames(node.body)
          ]),
          bodylessFunctionNames: /* @__PURE__ */ new Set(),
          scopeNames: /* @__PURE__ */ new Set([
            ...options.scopeNames || [],
            ...collectDeclaredNames(node.body),
            ...expressionDeclaredNames
          ])
        };
        const cleanupNames = collectCleanupNames(node);
        const body = emitBlockBodyStatements(node.body, cleanupNames, scopedOptions);
        if (cleanupNames.length === 0) {
          return `{
${body}
}`;
        }
        const cleanup = cleanupNames.map((name2) => options.returnSlotName ? `__zuzu_maybe_demolish( ${name2}, ${options.returnSlotName} );` : `__zuzu_maybe_demolish( ${name2} );`).join("\n");
        return `{
${cleanupNames.map((name2) => `let ${name2} = null;`).join("\n")}
try {
${body}
} finally {
${cleanup}
}
}`;
      }
      function emitBlockBodyStatements(statements, cleanupNames, options = {}) {
        const lines = [];
        for (let i = 0; i < statements.length; i++) {
          const stmt = statements[i];
          if (stmt.type === "VariableUnpackDeclaration") {
            const unpack = emitVariableUnpackParts(stmt);
            const rest = emitBlockBodyStatements(
              statements.slice(i + 1),
              cleanupNames,
              {
                ...options,
                scopeNames: /* @__PURE__ */ new Set([
                  ...options.scopeNames || [],
                  ...declaredNamesForStatement(stmt)
                ])
              }
            );
            lines.push(...unpack.prelude);
            lines.push("{");
            lines.push(...unpack.declarations);
            lines.push(emitUnpackScopedRest(stmt, rest));
            lines.push("}");
            return lines.filter((line) => line !== "").join("\n");
          }
          lines.push(emitBlockStatement(stmt, cleanupNames, options));
        }
        return lines.join("\n");
      }
      function emitUnpackScopedRest(stmt, rest) {
        const cleanupNames = declaredNamesForStatement(stmt).filter((name2) => name2 !== "self");
        if (cleanupNames.length === 0) {
          return rest;
        }
        const cleanup = cleanupNames.map((name2) => `__zuzu_maybe_demolish( ${name2} );`).join("\n");
        return `try {
${rest}
} finally {
${cleanup}
}`;
      }
      function collectAsyncFunctionNames(statements = []) {
        const names = [];
        for (const stmt of statements) {
          if (stmt.type === "FunctionDeclaration" && stmt.isAsync && stmt.id && stmt.id.name) {
            names.push(stmt.id.name);
          } else if (stmt.type === "VariableDeclaration" && stmt.init && stmt.init.type === "FunctionExpression" && stmt.init.isAsync && stmt.id && stmt.id.name) {
            names.push(stmt.id.name);
          }
        }
        return names;
      }
      function collectEvalImportNames(statements = []) {
        const names = [];
        for (const stmt of statements) {
          if (stmt.type !== "ImportDeclaration" || stmt.source !== "std/eval") {
            continue;
          }
          for (const specifier of stmt.specifiers || []) {
            const importedName = normalizeImportedName(stmt.source, specifier.imported);
            if (importedName === "eval" && specifier.local) {
              names.push(specifier.local);
            }
          }
        }
        return names;
      }
      function collectDeclaredNames(statements) {
        const names = [];
        for (const stmt of statements || []) {
          names.push(...declaredNamesForStatement(stmt));
        }
        return names;
      }
      function declaredNamesForStatement(stmt) {
        if (!stmt) {
          return [];
        }
        if (["VariableDeclaration", "FunctionDeclaration", "ClassDeclaration", "TraitDeclaration"].includes(stmt.type) && stmt.id && stmt.id.name) {
          return [stmt.id.name];
        }
        if (stmt.type === "VariableUnpackDeclaration") {
          return bindingEntriesForPattern(stmt.pattern).map((entry) => entry.name).filter(Boolean);
        }
        return [];
      }
      function emitPredeclaredNames(names) {
        const unique = [...new Set(names || [])].filter(Boolean);
        return unique.length > 0 ? `let ${unique.map((name2) => `${name2} = null`).join(", ")};` : "";
      }
      function collectExpressionDeclaredNames(statements = []) {
        return collectExpressionDeclaredEntries(statements).map((entry) => entry.name).filter(Boolean);
      }
      function collectExpressionDeclaredEntries(statements = []) {
        const entries = [];
        for (const stmt of statements || []) {
          collectExpressionDeclaredEntriesFromNode(stmt, entries);
        }
        return entries;
      }
      function collectExpressionDeclaredEntriesFromNode(node, entries) {
        if (!node || typeof node !== "object") {
          return;
        }
        if (Array.isArray(node)) {
          for (const item of node) {
            collectExpressionDeclaredEntriesFromNode(item, entries);
          }
          return;
        }
        if (node.type === "LetExpression") {
          if (node.id && node.id.name) {
            entries.push({
              name: node.id.name,
              isWeakStorage: node.isWeakStorage === true
            });
          }
          collectExpressionDeclaredEntriesFromNode(node.init, entries);
          return;
        }
        if ([
          "BlockStatement",
          "ClassDeclaration",
          "DoExpression",
          "FunctionDeclaration",
          "FunctionExpression",
          "MethodDeclaration",
          "TraitDeclaration",
          "TryExpression",
          "AwaitExpression",
          "SpawnExpression"
        ].includes(node.type)) {
          return;
        }
        for (const [key, value] of Object.entries(node)) {
          if (key === "loc") {
            continue;
          }
          collectExpressionDeclaredEntriesFromNode(value, entries);
        }
      }
      function bindingEntriesForPattern(pattern) {
        return pattern && Array.isArray(pattern.entries) ? pattern.entries : [];
      }
      function scopeHasName(options, name2) {
        return !!(options.scopeNames && options.scopeNames.has(name2));
      }
      function emitStoredValue(value, isWeakStorage) {
        return isWeakStorage ? `__zuzu_make_weak_value( ${value} )` : `__zuzu_retain_value( ${value} )`;
      }
      function expressionRetainsCollectionValues(node) {
        return [
          "ArrayExpression",
          "BagLiteral",
          "ObjectExpression",
          "PairListLiteral",
          "SetLiteral"
        ].includes(node.type);
      }
      function emitVariableDeclarationValue(node) {
        let value = node.init ? emitExpression(node.init) : "null";
        if (node.init && node.declaredType && node.declaredType !== "Any") {
          value = `__zuzu_checked_declaration( ${JSON.stringify(node.id.name)}, ${JSON.stringify(node.declaredType)}, ${value} )`;
        }
        return emitStoredValue(value, node.isWeakStorage);
      }
      function emitLetExpression(node) {
        const name2 = emitExpression(node.id);
        const value = emitVariableDeclarationValue(node);
        return `( ${name2} = ${value}, __zuzu_resolve_weak_value( ${name2} ) )`;
      }
      function emitVariableUnpackDeclaration(node) {
        const parts = emitVariableUnpackParts(node);
        return [...parts.prelude, ...parts.declarations].join("\n");
      }
      function emitVariableUnpackParts(node) {
        const sourceName = `__zuzu_unpack_source_${loopCounter++}`;
        const entries = bindingEntriesForPattern(node.pattern);
        const prelude = [
          `const ${sourceName} = __zuzu_unpack_source( ${emitExpression(node.init)} );`
        ];
        const valueNames = entries.map(() => `__zuzu_unpack_value_${loopCounter++}`);
        for (let i = 0; i < entries.length; i++) {
          prelude.push(
            `const ${valueNames[i]} = ${emitUnpackEntryValue(sourceName, entries[i])};`
          );
        }
        if (node.init && expressionRetainsCollectionValues(node.init)) {
          prelude.push(`__zuzu_release_collection_values( ${sourceName} );`);
        }
        const declarations = [];
        for (let i = 0; i < entries.length; i++) {
          const entry = entries[i];
          declarations.push(
            `${node.kind} ${entry.name} = ${valueNames[i]};`
          );
        }
        return { prelude, declarations, entries, valueNames };
      }
      function emitVariableUnpackAssignments(node) {
        const sourceName = `__zuzu_unpack_source_${loopCounter++}`;
        const lines = [
          `const ${sourceName} = __zuzu_unpack_source( ${emitExpression(node.init)} );`
        ];
        const entries = bindingEntriesForPattern(node.pattern);
        const valueNames = entries.map(() => `__zuzu_unpack_value_${loopCounter++}`);
        for (let i = 0; i < entries.length; i++) {
          lines.push(
            `const ${valueNames[i]} = ${emitUnpackEntryValue(sourceName, entries[i])};`
          );
        }
        if (node.init && expressionRetainsCollectionValues(node.init)) {
          lines.push(`__zuzu_release_collection_values( ${sourceName} );`);
        }
        for (let i = 0; i < entries.length; i++) {
          lines.push(`${entries[i].name} = ${valueNames[i]};`);
        }
        return lines.join("\n");
      }
      function emitUnpackEntryValue(sourceName, entry) {
        const defaultThunk = entry.defaultValue ? `() => ${emitExpression(entry.defaultValue)}` : "null";
        return `__zuzu_unpack_value( ${sourceName}, ${emitExpression(entry.key)}, ${defaultThunk}, ${JSON.stringify(entry.name)}, ${entry.declaredType ? JSON.stringify(entry.declaredType) : "null"}, ${entry.isWeakStorage ? "true" : "false"} )`;
      }
      function emitBlockStatement(node, cleanupNames, options = {}) {
        if (node.type === "VariableDeclaration" && node.id && cleanupNames.includes(node.id.name)) {
          return `${emitExpression(node.id)} = ${emitVariableDeclarationValue(node)};`;
        }
        if (node.type === "VariableUnpackDeclaration" && bindingEntriesForPattern(node.pattern).some((entry) => cleanupNames.includes(entry.name))) {
          return emitVariableUnpackAssignments(node);
        }
        return emitStatement(node, options);
      }
      function emitSwitchStatement(node, options = {}) {
        if (options.asyncContext && !options.syncEval) {
          const cases2 = node.cases.map((section) => `{ tests: [ ${section.values.map((value, index) => `async function( __zuzu_switch_value ) { return __zuzu_truthy( ${emitSwitchTestExpression(section, index, node.comparator)} ); }`).join(", ")} ], body: async function() ${emitBlock(section.consequent, {
            ...options,
            inSwitchSection: true,
            loopDepth: 0
          })} }`);
          const defaultBody2 = node.defaultCase ? `async function() ${emitBlock(node.defaultCase.consequent, {
            ...options,
            inSwitchSection: true,
            loopDepth: 0
          })}` : "null";
          const tail2 = switchStatementContainsReturn(node) ? options.inSwitchSection ? "if ( __zuzu_switch_result && __zuzu_switch_result.__zuzu_return ) { return __zuzu_switch_result; }" : "if ( __zuzu_switch_result && __zuzu_switch_result.__zuzu_return ) { return __zuzu_switch_result.value; }" : "";
          return `{ let __zuzu_switch_result = await __zuzu_switch_async( ${emitExpression(node.discriminant)}, ${JSON.stringify(node.comparator)}, [ ${cases2.join(", ")} ], ${defaultBody2} ); ${tail2} }`;
        }
        const cases = node.cases.map((section) => `{ tests: [ ${section.values.map((value, index) => `function( __zuzu_switch_value ) { return __zuzu_truthy( ${emitSwitchTestExpression(section, index, node.comparator)} ); }`).join(", ")} ], body: function() ${emitBlock(section.consequent, {
          ...options,
          inSwitchSection: true,
          loopDepth: 0
        })} }`);
        const defaultBody = node.defaultCase ? `function() ${emitBlock(node.defaultCase.consequent, {
          ...options,
          inSwitchSection: true,
          loopDepth: 0
        })}` : "null";
        const tail = switchStatementContainsReturn(node) ? options.inSwitchSection ? "if ( __zuzu_switch_result && __zuzu_switch_result.__zuzu_return ) { return __zuzu_switch_result; }" : "if ( __zuzu_switch_result && __zuzu_switch_result.__zuzu_return ) { return __zuzu_switch_result.value; }" : "";
        return `{ let __zuzu_switch_result = __zuzu_switch( ${emitExpression(node.discriminant)}, ${JSON.stringify(node.comparator)}, [ ${cases.join(", ")} ], ${defaultBody} ); ${tail} }`;
      }
      function emitSwitchTestExpression(section, index, defaultComparator) {
        const right = section.values[index];
        const operator = section.operators && section.operators[index] || defaultComparator || "==";
        return emitBinaryExpression({
          type: "BinaryExpression",
          operator,
          left: {
            type: "Identifier",
            name: "__zuzu_switch_value"
          },
          right
        });
      }
      function emitTraitDeclaration(node, options = {}) {
        const methods = completeMethodDeclarations(node.body || []).map((method) => {
          const value = emitMethodFunction(method, {
            ...options,
            callableName: method.id.name,
            returnTypeName: method.returnType,
            fieldNames: [],
            className: null,
            isStatic: false,
            methodSelfName: "self"
          });
          return `${JSON.stringify(method.id.name)}: ${value}`;
        });
        return `let ${emitExpression(node.id)} = __zuzu_trait( ${JSON.stringify(node.id.name)}, { ${methods.join(", ")} }, ${JSON.stringify(marshalSourceSlice(node, options) || "")}, ${marshalCapturesExpression(marshalTraitCaptureNames(node, options))} );`;
      }
      function emitClassDeclaration(node, options = {}) {
        return emitClassDeclarationWithName(node, node.id.name, options);
      }
      function emitFieldSpec(node) {
        return `{ kind: ${JSON.stringify(node.kind || "let")}, name: ${JSON.stringify(node.id.name)}, typeName: ${node.typeName ? JSON.stringify(node.typeName) : "null"}, isWeakStorage: ${node.isWeakStorage ? "true" : "false"}, accessors: [ ${node.accessors.map((item) => JSON.stringify(item)).join(", ")} ], defaultValue: ${node.defaultValue ? `function() { return ${emitExpression(node.defaultValue)}; }` : "null"} }`;
      }
      function emitNestedDeclarationEntry(node, parentName, options = {}) {
        if (node.type === "ClassDeclaration") {
          const qualified = `${parentName}{${JSON.stringify(node.id.name)}}`;
          return `${JSON.stringify(node.id.name)}: ( function() { ${emitClassDeclarationWithName(node, qualified, options)} return ${node.id.name}; } )()`;
        }
        return `${JSON.stringify(node.id.name)}: ( function() { ${emitStatement(node, options)} return ${node.id.name}; } )()`;
      }
      function emitMethodFunction(node, meta) {
        if (node.isPredeclared) {
          return `__zuzu_bodyless_function( ${JSON.stringify(node.id.name)} )`;
        }
        return `( ${emitFunctionLike(node, `${node.isAsync ? "async " : ""}function()`, {
          ...meta,
          asyncContext: node.isAsync === true,
          extraPreamble: [
            "let self = this;",
            `let __zuzu_super_class__ = ${meta.className ? meta.className : "null"};`,
            `let __zuzu_super_method__ = ${JSON.stringify(node.id.name)};`,
            `let __zuzu_super_static__ = ${meta.isStatic ? 1 : 0};`,
            ...(meta.nestedNames || []).map((name2) => `let ${name2} = self[${JSON.stringify(name2)}];`)
          ].join("\n"),
          scopeNames: /* @__PURE__ */ new Set(["self", "__zuzu_super_class__", "__zuzu_super_method__", "__zuzu_super_static__"]),
          fieldNames: meta.fieldNames || [],
          methodSelfName: meta.methodSelfName || "self"
        })} )`;
      }
      function emitClassDeclarationWithName(node, runtimeName, options = {}) {
        if (node.shorthand && node.traits.length === 0) {
          return `let ${emitExpression(node.id)} = __zuzu_make_class( ${JSON.stringify(runtimeName)}, ${node.base ? emitExpression(node.base) : "Object"} );`;
        }
        const fields = node.body.filter((entry) => entry.type === "FieldDeclaration");
        const methodEntries = completeMethodDeclarations(node.body.filter((entry) => entry.type === "MethodDeclaration"));
        const methods = methodEntries.filter((entry) => !entry.static);
        const statics = methodEntries.filter((entry) => entry.static);
        const nested = node.body.filter((entry) => ["ClassDeclaration", "TraitDeclaration"].includes(entry.type));
        const fieldNames = fields.map((field) => field.id.name);
        const nestedNames = nested.map((entry) => entry.id.name);
        return `let ${emitExpression(node.id)} = __zuzu_define_class( ${JSON.stringify(runtimeName)}, ${node.base ? emitExpression(node.base) : "Object"}, { "marshalSource": ${JSON.stringify(marshalSourceSlice(node, options) || "")}, "marshalCaptures": ${marshalCapturesExpression(marshalClassCaptureNames(node, options))}, "traits": [ ${node.traits.map(emitExpression).join(", ")} ], "fields": [ ${fields.map(emitFieldSpec).join(", ")} ], "methods": { ${methods.map((method) => `${JSON.stringify(method.id.name)}: ${emitMethodFunction(method, {
          ...options,
          callableName: method.id.name,
          returnTypeName: method.returnType,
          fieldNames,
          className: node.id.name,
          isStatic: false,
          methodSelfName: "self",
          nestedNames
        })}`).join(", ")} }, "statics": { ${statics.map((method) => `${JSON.stringify(method.id.name)}: ${emitMethodFunction(method, {
          ...options,
          callableName: method.id.name,
          returnTypeName: method.returnType,
          fieldNames: [],
          className: node.id.name,
          isStatic: true,
          methodSelfName: "self",
          nestedNames
        })}`).join(", ")} }, "nested": { ${nested.map((entry) => emitNestedDeclarationEntry(entry, runtimeName, options)).join(", ")} } } );`;
      }
      function completeMethodDeclarations(entries) {
        const ordered = [];
        const indexes = /* @__PURE__ */ new Map();
        for (const entry of entries || []) {
          if (entry.type !== "MethodDeclaration") {
            continue;
          }
          const key = `${entry.static ? "static:" : "instance:"}${entry.id.name}`;
          if (indexes.has(key)) {
            const index = indexes.get(key);
            if (ordered[index].isPredeclared && !entry.isPredeclared) {
              ordered[index] = entry;
            }
            continue;
          }
          indexes.set(key, ordered.length);
          ordered.push(entry);
        }
        return ordered;
      }
      function switchStatementContainsReturn(node) {
        return node.cases.some((section) => blockContainsReturn(section.consequent)) || node.defaultCase && blockContainsReturn(node.defaultCase.consequent);
      }
      function blockContainsReturn(block) {
        return block.body.some(statementContainsReturn);
      }
      function statementContainsReturn(stmt) {
        switch (stmt.type) {
          case "ReturnStatement":
            return true;
          case "BlockStatement":
            return blockContainsReturn(stmt);
          case "IfStatement":
            return blockContainsReturn(stmt.consequent) || (stmt.alternate ? stmt.alternate.type === "BlockStatement" ? blockContainsReturn(stmt.alternate) : statementContainsReturn(stmt.alternate) : false);
          case "ForInStatement":
            return blockContainsReturn(stmt.body) || (stmt.elseBlock ? blockContainsReturn(stmt.elseBlock) : false);
          case "WhileStatement":
            return blockContainsReturn(stmt.body);
          case "TryStatement":
            return blockContainsReturn(stmt.block) || (stmt.handlers || []).some((handler) => blockContainsReturn(handler.body));
          case "SwitchStatement":
            return switchStatementContainsReturn(stmt);
          default:
            return false;
        }
      }
      function emitExpression(node) {
        const options = currentEmitContext();
        switch (node.type) {
          case "Identifier":
            if (node.name === "^^") {
              return options.chainHereName || `( () => { throw new Error( "Undeclared variable '^^'" ); } )()`;
            }
            if (options.fieldNames && options.fieldNames.includes(node.name) && !scopeHasName(options, node.name)) {
              return `${options.methodSelfName || "self"}[${JSON.stringify(node.name)}]`;
            }
            return node.name === "__argc__" ? "__argc__" : node.name;
          case "NumericLiteral":
            return String(node.value);
          case "StringLiteral":
            return JSON.stringify(node.value);
          case "BinaryStringLiteral":
            return `__zuzu_binary_literal( ${JSON.stringify(node.value)} )`;
          case "TemplateLiteral":
            return emitTemplateLiteral(node);
          case "RegExpLiteral":
            return `new RegExp( ${emitRegExpPattern(node)}, ${JSON.stringify(node.flags)} )`;
          case "Literal":
            if (node.value === null) {
              return "null";
            }
            return node.value ? "true" : "false";
          case "Super":
            throw new UnsupportedSyntaxError("super must be called like a method");
          case "GroupedExpression":
            return `( ${emitExpression(node.expression)} )`;
          case "ArrayExpression":
            return `__zuzu_array( [ ${node.elements.map((element) => {
              if (element.type === "BinaryExpression" && element.operator === "...") {
                return `...${emitExpression(element)}`;
              }
              return emitExpression(element);
            }).join(", ")} ] )`;
          case "SetLiteral":
            return `__zuzu_set( [ ${emitCollectionElements(node.elements)} ] )`;
          case "BagLiteral":
            return `__zuzu_bag( [ ${emitCollectionElements(node.elements)} ] )`;
          case "PairListLiteral":
            return `__zuzu_pairlist_literal( [ ${emitPairListEntries(node.entries)} ] )`;
          case "ObjectExpression":
            return `( () => { const __zuzu_obj = {}; ${node.properties.map(
              (prop) => `__zuzu_obj[${JSON.stringify(prop.key)}] = __zuzu_retain_collection_value( __zuzu_obj, ${emitExpression(prop.value)} );`
            ).join(" ")} return __zuzu_obj; } )()`;
          case "NamedArgument":
            return `[ ${emitExpression(node.keyExpr || { type: "StringLiteral", value: node.key })}, ${emitExpression(node.value)} ]`;
          case "BraceIdentifier":
            return JSON.stringify(node.name);
          case "SliceExpression":
            return emitSliceExpression(node);
          case "MemberExpression":
            if (node.computed) {
              if (node.property.type === "BraceIdentifier") {
                return `__zuzu_get_brace_member( ${emitExpression(node.object)}, ${JSON.stringify(node.property.name)}, () => ${node.property.name} )`;
              }
              return `__zuzu_get_index( ${emitExpression(node.object)}, ${emitExpression(node.property)} )`;
            }
            if (node.property.name === "length") {
              return `__zuzu_length( ${emitExpression(node.object)} )`;
            }
            return `__zuzu_call_member( ${emitExpression(node.object)}, ${JSON.stringify(node.property.name)} )`;
          case "CallExpression":
            return emitCallExpression(node, options);
          case "RegexReplaceExpression":
            return emitRegexReplaceExpression(node);
          case "RefExpression":
            return emitRefExpression(node);
          case "AssignmentExpression":
            return emitAssignmentExpression(node);
          case "LetExpression":
            return emitLetExpression(node);
          case "ConditionalExpression":
            return `( __zuzu_truthy( ${emitExpression(node.test)} ) ? ${emitExpression(node.consequent)} : ${emitExpression(node.alternate)} )`;
          case "ShortTernaryExpression":
            return `( () => { const __zuzu_left = ${emitExpression(node.test)}; return __zuzu_resolve_weak_value( __zuzu_left ) != null ? __zuzu_left : ${emitExpression(node.alternate)}; } )()`;
          case "TryExpression":
            return emitTryExpression(node);
          case "DoExpression":
            return emitDoExpression(node);
          case "UnaryExpression":
            return emitUnaryExpression(node);
          case "BinaryExpression":
            return emitBinaryExpression(node);
          case "UpdateExpression":
            {
              const target = unwrapGroupedExpression(node.argument);
              if (target && target.type === "BinaryExpression" && ["@", "@@", "@?"].includes(target.operator)) {
                const mode = target.operator === "@@" ? "all" : target.operator === "@?" ? "maybe" : "first";
                return `__zuzu_path_update( ${emitExpression(target.left)}, ${emitExpression(target.right)}, "${mode}", ${JSON.stringify(node.operator)}, ${node.prefix ? "true" : "false"} )`;
              }
            }
            return node.prefix ? `( ${emitAssignmentTarget(node.argument)} = __zuzu_${node.operator === "++" ? "add" : "sub"}( ${emitAssignmentTarget(node.argument)}, 1 ) )` : `( () => { const __zuzu_old = __zuzu_num( ${emitAssignmentTarget(node.argument)} ); ${emitAssignmentTarget(node.argument)} = __zuzu_${node.operator === "++" ? "add" : "sub"}( __zuzu_old, 1 ); return __zuzu_old; } )()`;
          case "FunctionExpression": {
            const fn2 = emitFunctionLike(node, `${node.isAsync ? "async " : ""}function()`, {
              ...nestedFunctionOptions(options),
              asyncContext: node.isAsync === true,
              syncEval: options.syncEval === true
            });
            const meta = marshalMetaExpression(
              "function",
              node.id && node.id.name,
              marshalFunctionSource(node),
              marshalCaptureNames(node)
            );
            return `__zuzu_with_marshal_meta( ( ${fn2} ), ${meta} )`;
          }
          case "AwaitExpression":
            if (currentEmitContext().syncEval) {
              return `__zuzu_await_block_sync( ( () => { ${emitExpressionBlock(node.block, {
                ...options,
                asyncContext: false,
                nonLocalReturn: true,
                boxResult: true,
                syncEval: true
              })} } )() )`;
            }
            return `await __zuzu_await_block( ( async () => { ${emitExpressionBlock(node.block, {
              ...options,
              asyncContext: true,
              nonLocalReturn: true,
              boxResult: true
            })} } )() )`;
          case "SpawnExpression":
            return `__zuzu_spawn( async () => { ${emitExpressionBlock(node.block, {
              ...options,
              asyncContext: true,
              nonLocalReturn: true
            })} }, { name: "<spawn>", line: ${JSON.stringify(node.loc.start.line)} } )`;
          case "NewExpression":
            return emitNewExpression(node);
          default:
            throw new UnsupportedSyntaxError(`Unsupported expression node ${node.type}`);
        }
      }
      function emitNewExpression(node) {
        const traitList = Array.isArray(node.traits) && node.traits.length > 0 ? `[ ${node.traits.map(emitExpression).join(", ")} ]` : null;
        if (node.callee.type === "CallExpression") {
          const callee = emitExpression(node.callee.callee);
          const constructor = traitList ? `__zuzu_class_with_traits( ${callee}, ${traitList} )` : callee;
          const args = emitCallArgumentList(node.callee.arguments);
          if (traitList) {
            return `new (${constructor})( ${args} )`;
          }
          if (node.callee.callee.type === "Identifier" || node.callee.callee.type === "MemberExpression" && !node.callee.callee.computed) {
            return `new ${constructor}( ${args} )`;
          }
          return `new (${constructor})( ${args} )`;
        }
        if (traitList) {
          return `new (__zuzu_class_with_traits( ${emitExpression(node.callee)}, ${traitList} ))`;
        }
        return `new ${emitExpression(node.callee)}`;
      }
      function emitCallExpression(node, options = {}) {
        let source;
        if (node.callee.type === "Super") {
          const argArray = emitCallArgumentArray(node.arguments);
          source = `__zuzu_super_dispatch( __zuzu_super_static__, self, __zuzu_super_class__, __zuzu_super_method__, ${argArray} )`;
        } else if (node.callee.type === "Identifier" && (options.evalNames || /* @__PURE__ */ new Set(["eval"])).has(node.callee.name) && node.arguments.length > 0) {
          source = emitEvalCall(node.arguments);
        } else if (node.callee.type === "MemberExpression" && !node.callee.computed && node.callee.property.type === "Identifier" && node.callee.property.name === "length" && node.arguments.length === 0) {
          source = `__zuzu_length( ${emitExpression(node.callee.object)} )`;
        } else if (callReleasesTemporaryCollectionReceiver(node)) {
          const object = emitExpression(node.callee.object);
          const property = JSON.stringify(node.callee.property.name);
          source = `( () => { const __zuzu_receiver = ${object}; const __zuzu_result = __zuzu_call_member( __zuzu_receiver, ${property} ); __zuzu_release_collection_values( __zuzu_receiver ); return __zuzu_result; } )()`;
        } else if (node.callee.type === "MemberExpression") {
          const args = emitCallArgumentList(node.arguments);
          if (options.asyncContext && !options.syncEval && !node.callee.computed && node.callee.property.type === "Identifier" && ["map", "grep", "reduce"].includes(node.callee.property.name) && node.arguments.length > 0) {
            const object = emitExpression(node.callee.object);
            const method = node.callee.property.name;
            source = `await __zuzu_collection_${method}_async( ${object}, ${args} )`;
          } else if (node.arguments.length === 0) {
            const object = emitExpression(node.callee.object);
            if (node.callee.computed) {
              const property = node.callee.property.type === "BraceIdentifier" ? `__zuzu_resolve_brace_key( __zuzu_receiver, ${JSON.stringify(node.callee.property.name)}, () => ${node.callee.property.name} )` : emitExpression(node.callee.property);
              source = `( () => { const __zuzu_receiver = ${object}; return __zuzu_call_member( __zuzu_receiver, ${property} ); } )()`;
            } else {
              source = `__zuzu_call_member( ${object}, ${JSON.stringify(node.callee.property.name)} )`;
            }
          } else {
            const object = emitExpression(node.callee.object);
            if (node.callee.computed) {
              const property = node.callee.property.type === "BraceIdentifier" ? `__zuzu_resolve_brace_key( __zuzu_receiver, ${JSON.stringify(node.callee.property.name)}, () => ${node.callee.property.name} )` : emitExpression(node.callee.property);
              source = `( () => { const __zuzu_receiver = ${object}; return __zuzu_call_member( __zuzu_receiver, ${property}, ${args} ); } )()`;
            } else {
              source = `__zuzu_call_member( ${object}, ${JSON.stringify(node.callee.property.name)}, ${args} )`;
            }
          }
        } else {
          source = `${emitExpression(node.callee)}( ${emitCallArgumentList(node.arguments)} )`;
        }
        if (!callNeedsTraceMetadata(node, options) || /\bawait\b/u.test(source)) {
          return source;
        }
        const line = node.loc && node.loc.start ? node.loc.start.line : null;
        return `__zuzu_callsite( { line: ${JSON.stringify(line)} }, () => ${source} )`;
      }
      function callReleasesTemporaryCollectionReceiver(node) {
        return node.callee.type === "MemberExpression" && !node.callee.computed && node.callee.property.type === "Identifier" && node.arguments.length === 0 && node.callee.object.type === "ArrayExpression" && ["copy", "to_Array", "to_Bag", "to_List", "to_Set"].includes(node.callee.property.name);
      }
      function callNeedsTraceMetadata(node, options = {}) {
        if (node.callee.type === "Identifier") {
          if (options.asyncNames && options.asyncNames.has(node.callee.name)) {
            return true;
          }
          return [
            "all",
            "failed",
            "race",
            "resolved",
            "sleep",
            "timeout",
            "yield"
          ].includes(node.callee.name);
        }
        if (node.callee.type === "MemberExpression" && !node.callee.computed && node.callee.property.type === "Identifier") {
          return [
            "append_async",
            "append_utf8_async",
            "each_line",
            "lines",
            "lines_async",
            "lines_utf8",
            "lines_utf8_async",
            "next_line",
            "pipeline",
            "pipeline_async",
            "recv",
            "request",
            "request_async",
            "run",
            "run_async",
            "send",
            "send_async",
            "sleep_async",
            "slurp",
            "slurp_async",
            "slurp_utf8",
            "slurp_utf8_async",
            "spew",
            "spew_async",
            "spew_utf8",
            "spew_utf8_async"
          ].includes(node.callee.property.name);
        }
        return false;
      }
      function emitUnaryExpression(node) {
        const target = unwrapGroupedExpression(node.argument);
        if ((node.operator === "++" || node.operator === "--") && target && target.type === "BinaryExpression" && ["@", "@@", "@?"].includes(target.operator)) {
          const mode = target.operator === "@@" ? "all" : target.operator === "@?" ? "maybe" : "first";
          return `__zuzu_path_update( ${emitExpression(target.left)}, ${emitExpression(target.right)}, "${mode}", ${JSON.stringify(node.operator)}, true )`;
        }
        if (node.operator === "not") {
          return `__zuzu_not( ${emitExpression(node.argument)} )`;
        }
        if (node.operator === "\xAC") {
          return `__zuzu_not( ${emitExpression(node.argument)} )`;
        }
        if (node.operator === "!") {
          return `__zuzu_not( ${emitExpression(node.argument)} )`;
        }
        if (node.operator === "~") {
          return `__zuzu_bit_not( ${emitExpression(node.argument)} )`;
        }
        if (node.operator === "typeof") {
          return `__zuzu_typeof( ${emitExpression(node.argument)} )`;
        }
        if (node.operator === "abs") {
          return `__zuzu_abs( ${emitExpression(node.argument)} )`;
        }
        if (node.operator === "sqrt") {
          return `__zuzu_sqrt( ${emitExpression(node.argument)} )`;
        }
        if (node.operator === "\u221A") {
          return `__zuzu_sqrt( ${emitExpression(node.argument)} )`;
        }
        if (node.operator === "floor") {
          return `__zuzu_floor( ${emitExpression(node.argument)} )`;
        }
        if (node.operator === "ceil") {
          return `__zuzu_ceil( ${emitExpression(node.argument)} )`;
        }
        if (node.operator === "round") {
          return `__zuzu_round( ${emitExpression(node.argument)} )`;
        }
        if (node.operator === "int") {
          return `__zuzu_int( ${emitExpression(node.argument)} )`;
        }
        if (node.operator === "length") {
          return `__zuzu_length( ${emitExpression(node.argument)} )`;
        }
        if (node.operator === "uc") {
          return `__zuzu_uc( ${emitExpression(node.argument)} )`;
        }
        if (node.operator === "lc") {
          return `__zuzu_lc( ${emitExpression(node.argument)} )`;
        }
        if (node.operator === "+") {
          return `__zuzu_num( ${emitExpression(node.argument)} )`;
        }
        if (node.operator === "-") {
          return `( -__zuzu_num( ${emitExpression(node.argument)} ) )`;
        }
        return `${node.operator}${emitExpression(node.argument)}`;
      }
      function emitTemplateLiteral(node) {
        if (!node.parts || node.parts.length === 0) {
          return '""';
        }
        let out = emitExpression(node.parts[0]);
        for (let i = 1; i < node.parts.length; i++) {
          out = `__zuzu_concat( ${out}, ${emitExpression(node.parts[i])} )`;
        }
        return out;
      }
      function emitRegExpPattern(node) {
        if (!node.parts || node.parts.length === 0) {
          return JSON.stringify(node.pattern);
        }
        return emitTemplateLiteral({
          type: "TemplateLiteral",
          parts: node.parts
        });
      }
      function emitCollectionElements(elements) {
        return elements.map((element) => {
          if (element.type === "BinaryExpression" && element.operator === "...") {
            return `...${emitExpression(element)}`;
          }
          return emitExpression(element);
        }).join(", ");
      }
      function emitPairListEntries(entries) {
        return entries.map((entry) => {
          if (entry.type === "PairListEntry") {
            const keyExpr = entry.keyExpr || { type: "StringLiteral", value: entry.key };
            return `[ ${emitExpression(keyExpr)}, ${emitExpression(entry.value)} ]`;
          }
          return emitExpression(entry);
        }).join(", ");
      }
      function emitBinaryExpression(node) {
        if (node.operator === "\u25B7" || node.operator === "|>") {
          const input = emitExpression(node.left);
          const hereName = `__zuzu_chain_${chainCounter++}`;
          const right2 = withEmitContext({
            ...currentEmitContext(),
            chainHereName: hereName
          }, () => emitExpression(node.right));
          return `( () => { const ${hereName} = ${input}; return ${right2}; } )()`;
        }
        if (node.operator === "\u25C1" || node.operator === "<|") {
          const input = emitExpression(node.right);
          const hereName = `__zuzu_chain_${chainCounter++}`;
          const left2 = withEmitContext({
            ...currentEmitContext(),
            chainHereName: hereName
          }, () => emitExpression(node.left));
          return `( () => { const ${hereName} = ${input}; return ${left2}; } )()`;
        }
        const left = emitExpression(node.left);
        const right = emitExpression(node.right);
        switch (node.operator) {
          case "and":
          case "\u22C0":
            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? __zuzu_truthy( ${right} ) : false; } )()`;
          case "and?":
          case "\u22C0?":
            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? ${right} : __zuzu_left; } )()`;
          case "or":
          case "\u22C1":
            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? true : __zuzu_truthy( ${right} ); } )()`;
          case "or?":
          case "\u22C1?":
            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? __zuzu_left : ${right}; } )()`;
          case "nor":
          case "\u22BD":
            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? false : !__zuzu_truthy( ${right} ); } )()`;
          case "nor?":
          case "\u22BD?":
            return `( () => { const __zuzu_left = ${left}; const __zuzu_right = ${right}; return __zuzu_truthy( __zuzu_left ) ? ( __zuzu_truthy( __zuzu_right ) ? false : __zuzu_right ) : ( __zuzu_truthy( __zuzu_right ) ? __zuzu_left : true ); } )()`;
          case "xor":
          case "\u22BB":
            return `__zuzu_xor( ${left}, ${right} )`;
          case "xor?":
          case "\u22BB?":
            return `( () => { const __zuzu_left = ${left}; const __zuzu_right = ${right}; return __zuzu_truthy( __zuzu_left ) ? ( __zuzu_truthy( __zuzu_right ) ? false : __zuzu_left ) : ( __zuzu_truthy( __zuzu_right ) ? __zuzu_right : false ); } )()`;
          case "xnor":
          case "\u2194":
            return `( __zuzu_truthy( ${left} ) === __zuzu_truthy( ${right} ) )`;
          case "xnor?":
          case "\u2194?":
            return `( () => { const __zuzu_left = ${left}; const __zuzu_right = ${right}; return __zuzu_truthy( __zuzu_left ) ? __zuzu_right : ( __zuzu_truthy( __zuzu_right ) ? __zuzu_left : true ); } )()`;
          case "nand":
          case "\u22BC":
            return `__zuzu_nand( ${left}, ${right} )`;
          case "nand?":
          case "\u22BC?":
            return `( () => { const __zuzu_left = ${left}; const __zuzu_right = ${right}; return __zuzu_truthy( __zuzu_left ) ? ( __zuzu_truthy( __zuzu_right ) ? false : true ) : ( __zuzu_truthy( __zuzu_right ) ? __zuzu_right : true ); } )()`;
          case "onlyif":
          case "\u22A8":
            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? __zuzu_truthy( ${right} ) : true; } )()`;
          case "onlyif?":
          case "\u22A8?":
            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? ${right} : true; } )()`;
          case "butnot":
          case "\u22AD":
            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? !__zuzu_truthy( ${right} ) : false; } )()`;
          case "butnot?":
          case "\u22AD?":
            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? ( __zuzu_truthy( ${right} ) ? false : __zuzu_left ) : __zuzu_left; } )()`;
          case "eq":
            return `__zuzu_str_eq( ${left}, ${right} )`;
          case "ne":
            return `( __zuzu_str_eq( ${left}, ${right} ) ? 0 : 1 )`;
          case "default":
            return `__zuzu_default( ${left}, ${right} )`;
          case "==":
            return `__zuzu_eq( ${left}, ${right} )`;
          case "=":
            return `__zuzu_num_eq( ${left}, ${right} )`;
          case "\u2261":
            return `__zuzu_eq( ${left}, ${right} )`;
          case "\u2262":
            return `__zuzu_ne( ${left}, ${right} )`;
          case "!=":
          case "\u2260":
            return `__zuzu_ne( ${left}, ${right} )`;
          case "~":
            return `__zuzu_match( ${left}, ${right} )`;
          case "_":
            return `__zuzu_concat( ${left}, ${right} )`;
          case "+":
            return `__zuzu_add( ${left}, ${right} )`;
          case "-":
            return `__zuzu_sub( ${left}, ${right} )`;
          case "*":
          case "\xD7":
            return `__zuzu_mul( ${left}, ${right} )`;
          case "/":
          case "\xF7":
            return `__zuzu_div( ${left}, ${right} )`;
          case "**":
            return `__zuzu_pow( ${left}, ${right} )`;
          case "mod":
            return `( __zuzu_num( ${left} ) % __zuzu_num( ${right} ) )`;
          case "...":
            return `__zuzu_range( ${left}, ${right} )`;
          case "<=>":
          case "\u2276":
          case "\u2277":
            return `__zuzu_cmp( ${left}, ${right} )`;
          case "cmp":
            return `__zuzu_str_cmp( ${left}, ${right} )`;
          case "gt":
            return `__zuzu_str_gt( ${left}, ${right} )`;
          case "ge":
            return `__zuzu_str_ge( ${left}, ${right} )`;
          case "lt":
            return `__zuzu_str_lt( ${left}, ${right} )`;
          case "le":
            return `__zuzu_str_le( ${left}, ${right} )`;
          case "eqi":
            return `__zuzu_str_eqi( ${left}, ${right} )`;
          case "nei":
            return `__zuzu_str_nei( ${left}, ${right} )`;
          case "gti":
            return `__zuzu_str_gti( ${left}, ${right} )`;
          case "gei":
            return `__zuzu_str_gei( ${left}, ${right} )`;
          case "lti":
            return `__zuzu_str_lti( ${left}, ${right} )`;
          case "lei":
            return `__zuzu_str_lei( ${left}, ${right} )`;
          case "cmpi":
            return `__zuzu_str_cmpi( ${left}, ${right} )`;
          case "\u2264":
            return `__zuzu_num_lte( ${left}, ${right} )`;
          case "\u2265":
            return `__zuzu_num_gte( ${left}, ${right} )`;
          case "<":
            return `__zuzu_num_lt( ${left}, ${right} )`;
          case "<=":
            return `__zuzu_num_lte( ${left}, ${right} )`;
          case ">":
            return `__zuzu_num_gt( ${left}, ${right} )`;
          case ">=":
            return `__zuzu_num_gte( ${left}, ${right} )`;
          case "union":
          case "\u22C3":
            return `__zuzu_union( ${left}, ${right} )`;
          case "intersection":
          case "\u22C2":
            return `__zuzu_intersection( ${left}, ${right} )`;
          case "\\":
          case "\u2216":
          case "difference":
            return `__zuzu_difference( ${left}, ${right} )`;
          case "subsetof":
          case "\u2282":
            return `__zuzu_subsetof( ${left}, ${right} )`;
          case "supersetof":
          case "\u2283":
            return `__zuzu_supersetof( ${left}, ${right} )`;
          case "equivalentof":
          case "\u2282\u2283":
            return `__zuzu_equivalentof( ${left}, ${right} )`;
          case "instanceof":
            return `__zuzu_instanceof( ${left}, ${right} )`;
          case "does":
            return `__zuzu_does( ${left}, ${right} )`;
          case "can":
            if (node.right.type === "Identifier") {
              return `__zuzu_can( ${left}, ${JSON.stringify(node.right.name)} )`;
            }
            return `__zuzu_can( ${left}, ${right} )`;
          case "in":
          case "\u2208":
            return `__zuzu_contains( ${right}, ${left} )`;
          case "not_in":
          case "\u2209":
            return `( __zuzu_contains( ${right}, ${left} ) ? 0 : 1 )`;
          case "@":
            return `__zuzu_path_op( ${left}, ${right}, "first" )`;
          case "@@":
            return `__zuzu_path_op( ${left}, ${right}, "all" )`;
          case "@?":
            return `__zuzu_path_op( ${left}, ${right}, "exists" )`;
          case "&":
            return `__zuzu_bit_and( ${left}, ${right} )`;
          case "|":
            return `__zuzu_bit_or( ${left}, ${right} )`;
          case "^":
            return `__zuzu_bit_xor( ${left}, ${right} )`;
          case "<<":
          case "\xAB":
            return `__zuzu_shift_left( ${left}, ${right} )`;
          case "\u2223":
          case "divides":
            return `__zuzu_divides( ${left}, ${right} )`;
          case "\u2224":
            return `__zuzu_ndivides( ${left}, ${right} )`;
          case ">>":
          case "\xBB":
            return `__zuzu_shift_right( ${left}, ${right} )`;
          default:
            return `( ${left} ${node.operator} ${right} )`;
        }
      }
      function emitAssignmentExpression(node) {
        const options = currentEmitContext();
        if (node.left && node.left.type === "BinaryExpression" && ["@", "@@", "@?"].includes(node.left.operator)) {
          const target = emitExpression(node.left.left);
          const path = emitExpression(node.left.right);
          const right2 = emitExpression(node.right);
          const mode = node.left.operator === "@@" ? "all" : node.left.operator === "@?" ? "maybe" : "first";
          return `__zuzu_path_assign( ${target}, ${path}, ${right2}, "${mode}", ${JSON.stringify(node.operator)}, ${node.isWeakWrite ? "true" : "false"} )`;
        }
        if (node.left && node.left.type === "SliceExpression" && node.operator === ":=") {
          const objectTarget = emitAssignmentTarget(node.left.object);
          const objectValue = emitExpression(node.left.object);
          const start = node.left.start ? emitExpression(node.left.start) : "0";
          const length = node.left.length == null ? "null" : emitExpression(node.left.length);
          const right2 = emitExpression(node.right);
          return `${objectTarget} = __zuzu_assign_slice( ${objectValue}, ${start}, ${length}, ${right2} )`;
        }
        const left = emitAssignmentTarget(node.left);
        const right = emitExpression(node.right);
        switch (node.operator) {
          case ":=":
            if (node.left && node.left.type === "Identifier") {
              const weakStorage = options.weakStorageNames && options.weakStorageNames.has(node.left.name);
              return weakStorage || node.isWeakWrite ? `${left} = __zuzu_assign_weak( ${left}, ${right} )` : `${left} = __zuzu_assign_strong( ${left}, ${right} )`;
            }
            if (node.left && node.left.type === "MemberExpression") {
              if (!node.left.computed) {
                throw new UnsupportedSyntaxError("Invalid assignment target");
              }
              const object = emitExpression(node.left.object);
              const objectTarget = emitAssignmentTarget(node.left.object);
              const key = node.left.computed ? node.left.property.type === "BraceIdentifier" ? `__zuzu_resolve_brace_key( ${object}, ${JSON.stringify(node.left.property.name)}, () => ${node.left.property.name} )` : emitExpression(node.left.property) : JSON.stringify(node.left.property.name);
              return `__zuzu_assign_index( ${object}, ${key}, ${right}, ${node.isWeakWrite ? "true" : "false"}, ( __zuzu_updated ) => ( ${objectTarget} = __zuzu_updated ) )`;
            }
            return `${left} = ${right}`;
          case "+=":
            return `${left} = __zuzu_add( ${left}, ${right} )`;
          case "-=":
            return `${left} = __zuzu_sub( ${left}, ${right} )`;
          case "*=":
          case "\xD7=":
            return `${left} = __zuzu_mul( ${left}, ${right} )`;
          case "/=":
          case "\xF7=":
            return `${left} = __zuzu_div( ${left}, ${right} )`;
          case "%=":
            return `${left} = __zuzu_mod( ${left}, ${right} )`;
          case "**=":
            return `${left} = __zuzu_pow( ${left}, ${right} )`;
          case "_=":
            return `${left} = __zuzu_concat( ${left}, ${right} )`;
          case "?:=":
            return `( ${left} == null ? ( ${left} = ${right} ) : ${left} )`;
          default:
            throw new UnsupportedSyntaxError(`Unsupported assignment operator ${node.operator}`);
        }
      }
      function emitAssignmentTarget(node) {
        if (node && node.type === "MemberExpression" && node.computed && node.property) {
          if (node.property.type === "BraceIdentifier") {
            const object = emitExpression(node.object);
            return `${object}[__zuzu_resolve_brace_key( ${object}, ${JSON.stringify(node.property.name)}, () => ${node.property.name} )]`;
          }
          return `${emitExpression(node.object)}[${emitExpression(node.property)}]`;
        }
        return emitExpression(node);
      }
      function emitSliceExpression(node) {
        const object = emitExpression(node.object);
        const start = node.start ? emitExpression(node.start) : "0";
        const length = node.length == null ? "null" : emitExpression(node.length);
        return `__zuzu_get_slice( ${object}, ${start}, ${length} )`;
      }
      function unwrapGroupedExpression(node) {
        let current = node;
        while (current && current.type === "GroupedExpression") {
          current = current.expression;
        }
        return current;
      }
      function emitRegexReplaceExpression(node) {
        const leftTarget = unwrapGroupedExpression(node.left);
        if (leftTarget && leftTarget.type === "BinaryExpression" && ["@", "@@", "@?"].includes(leftTarget.operator)) {
          const mode = leftTarget.operator === "@@" ? "all" : leftTarget.operator === "@?" ? "maybe" : "first";
          const pattern2 = node.pattern.type === "RegExpLiteral" ? emitExpression(node.pattern) : `__zuzu_to_regexp( ${emitExpression(node.pattern)} )`;
          return `__zuzu_path_assign( ${emitExpression(leftTarget.left)}, ${emitExpression(leftTarget.right)}, [ ${pattern2}, ( m ) => ${emitExpression(node.replacement)} ], "${mode}", "~=" )`;
        }
        const left = emitExpression(node.left);
        const pattern = node.pattern.type === "RegExpLiteral" ? emitExpression(node.pattern) : `__zuzu_to_regexp( ${emitExpression(node.pattern)} )`;
        const replacement = emitExpression(node.replacement);
        return `${left} = __zuzu_regex_replace( ${left}, ${pattern}, ( ...__zuzu_match_args ) => { const m = __zuzu_match_args; return ${replacement}; } )`;
      }
      function emitRefExpression(node) {
        const arg = unwrapGroupedExpression(node.argument);
        if (arg && arg.type === "BinaryExpression" && ["@", "@@", "@?"].includes(arg.operator)) {
          const mode = arg.operator === "@@" ? "all" : arg.operator === "@?" ? "maybe" : "first";
          return `__zuzu_path_ref( ${emitExpression(arg.left)}, ${emitExpression(arg.right)}, "${mode}" )`;
        }
        if (arg.type === "SliceExpression") {
          return `__zuzu_ref_slice( ${emitExpression(arg.object)}, ${arg.start ? emitExpression(arg.start) : "0"}, ${arg.length == null ? "null" : emitExpression(arg.length)} )`;
        }
        if (arg.type === "MemberExpression") {
          if (arg.computed) {
            if (arg.property.type === "BraceIdentifier") {
              return `__zuzu_ref_index( ${emitExpression(arg.object)}, ${JSON.stringify(arg.property.name)} )`;
            }
            return `__zuzu_ref_index( ${emitExpression(arg.object)}, ${emitExpression(arg.property)} )`;
          }
          return `__zuzu_ref_key( ${emitExpression(arg.object)}, ${JSON.stringify(arg.property.name)} )`;
        }
        throw new UnsupportedSyntaxError("Unsupported reference target");
      }
      function emitExpressionBlock(block, options = {}) {
        return withEmitContext(options, () => {
          if (!block || !Array.isArray(block.body) || block.body.length === 0) {
            return options.boxResult ? "return { __zuzu_await_block_value: null };" : "return null;";
          }
          const expressionDeclaredNames = collectExpressionDeclaredNames(block.body);
          const scopedOptions = {
            ...options,
            weakStorageNames: /* @__PURE__ */ new Set([
              ...options.weakStorageNames || [],
              ...collectWeakDeclaredNames(block.body)
            ]),
            scopeNames: /* @__PURE__ */ new Set([
              ...options.scopeNames || [],
              ...expressionDeclaredNames
            ])
          };
          return withEmitContext(scopedOptions, () => {
            const lines = [];
            const prelude = emitPredeclaredNames(expressionDeclaredNames);
            if (prelude) {
              lines.push(prelude);
            }
            const lastIndex = block.body.length - 1;
            for (let i = 0; i < block.body.length; i++) {
              const stmt = block.body[i];
              if (i === lastIndex) {
                lines.push(emitExpressionTail(stmt, scopedOptions));
              } else {
                lines.push(emitExpressionInnerStatement(stmt, scopedOptions));
              }
            }
            return lines.join("\n");
          });
        });
      }
      function emitExpressionInnerStatement(stmt, options = {}) {
        if (options.nonLocalReturn && stmt.type === "ReturnStatement") {
          return emitDoReturnStatement(stmt);
        }
        return emitStatement(stmt, options);
      }
      function emitExpressionTail(stmt, options = {}) {
        if (stmt.type === "ExpressionStatement") {
          const value = emitExpression(stmt.expression);
          return options.boxResult ? `return { __zuzu_await_block_value: ${value} };` : `return ${value};`;
        }
        if (stmt.type === "ReturnStatement") {
          return options.nonLocalReturn ? emitDoReturnStatement(stmt) : emitStatement(stmt);
        }
        if (stmt.type === "BlockStatement") {
          return emitExpressionBlock(stmt, options);
        }
        if (stmt.type === "IfStatement") {
          const prefix = stmt.declaration ? `${emitStatement(stmt.declaration, options)}
` : "";
          const alternate = stmt.alternate ? emitExpressionTail(stmt.alternate, options) : options.boxResult ? "return { __zuzu_await_block_value: null };" : "return null;";
          return `${prefix}if ( __zuzu_truthy( ${emitExpression(stmt.test)} ) ) { ${emitExpressionBlock(stmt.consequent, options)} } else { ${alternate} }`;
        }
        return emitStatement(stmt, options);
      }
      function emitDoReturnStatement(stmt) {
        return `throw { __zuzu_nonlocal_return: true, value: ${stmt.argument ? emitExpression(stmt.argument) : "null"} };`;
      }
      function emitTryExpression(node) {
        const options = currentEmitContext();
        const handlers = node.handlers || [];
        let catchBody = "throw __zuzu_err;";
        if (handlers.length > 0) {
          const branches = handlers.map((handler, index) => {
            const cond = handler.typeName === "Exception" || handler.typeName === "Any" ? "true" : `__zuzu_instanceof( __zuzu_err, ${handler.typeName} )`;
            const prefix = index === 0 ? `if ( ${cond} )` : `else if ( ${cond} )`;
            return `${prefix} { let ${handler.paramName} = __zuzu_err; ${emitExpressionBlock(handler.body, options)} }`;
          });
          catchBody = `if ( __zuzu_err && __zuzu_err.__zuzu_nonlocal_return ) { throw __zuzu_err; } __zuzu_err = __zuzu_normalize_exception( __zuzu_err ); ${branches.join(" ")} else { throw __zuzu_err; }`;
        }
        return `( ${options.asyncContext ? "async " : ""}() => { try { ${emitExpressionBlock(node.block, options)} } catch ( __zuzu_err ) { ${catchBody} } } )()`;
      }
      function emitDoExpression(node) {
        return `( () => { ${emitExpressionBlock(node.block, {
          ...currentEmitContext(),
          nonLocalReturn: true
        })} } )()`;
      }
      function emitCallArguments(args) {
        const positional = [];
        const named = [];
        for (const arg of args) {
          if (arg.type === "NamedArgument") {
            named.push(arg);
          } else {
            positional.push(emitExpression(arg));
          }
        }
        if (named.length > 0) {
          positional.push(`__zuzu_temp_pairlist( [ ${named.map((arg) => emitExpression(arg)).join(", ")} ] )`);
        }
        return positional;
      }
      function emitCallArgumentList(args) {
        if (!callArgumentsHaveSpread(args)) {
          return emitCallArguments(args).join(", ");
        }
        return `...${emitSpreadCallArguments(args)}`;
      }
      function emitCallArgumentArray(args) {
        if (args.length === 0) {
          return "[]";
        }
        if (!callArgumentsHaveSpread(args)) {
          return `[ ${emitCallArguments(args).join(", ")} ]`;
        }
        return emitSpreadCallArguments(args);
      }
      function callArgumentsHaveSpread(args) {
        return args.some((arg) => arg.type === "SpreadArgument");
      }
      function emitSpreadCallArguments(args) {
        return `__zuzu_spread_call_args( [ ${args.map(emitSpreadCallArgumentPart).join(", ")} ] )`;
      }
      function emitSpreadCallArgumentPart(arg) {
        if (arg.type === "SpreadArgument") {
          return `__zuzu_snapshot_spread_arg( ${emitExpression(arg.argument)} )`;
        }
        if (arg.type === "NamedArgument") {
          return `{ type: "named", value: ${emitExpression(arg)} }`;
        }
        return `{ type: "positional", value: ${emitExpression(arg)} }`;
      }
      function emitEvalCall(args) {
        if (callArgumentsHaveSpread(args)) {
          return `eval( __zuzu_prepare_eval_call_args( ${emitSpreadCallArguments(args)} ) )`;
        }
        const positional = [];
        const named = [];
        for (const arg of args) {
          if (arg.type === "NamedArgument") {
            named.push(arg);
          } else {
            positional.push(arg);
          }
        }
        const source = positional.length > 0 ? emitExpression(positional[0]) : '""';
        const namedArgs = named.length > 0 ? `__zuzu_pairlist_literal( [ ${named.map((arg) => emitExpression(arg)).join(", ")} ] )` : "null";
        return `eval( __zuzu_prepare_eval( ${source}, ${namedArgs} ) )`;
      }
      module2.exports = {
        emitProgram
      };
      function programNeedsAsyncWrapper(ast) {
        return ast.body.some((stmt) => nodeContainsAsyncControl(stmt));
      }
      function programContainsImport(ast) {
        return ast.body.some((stmt) => stmt && stmt.type === "ImportDeclaration");
      }
      function nodeContainsAsyncControl(node) {
        if (!node || typeof node !== "object") {
          return false;
        }
        if (node.type === "AwaitExpression" || node.type === "SpawnExpression") {
          return true;
        }
        if (["FunctionDeclaration", "FunctionExpression", "MethodDeclaration"].includes(node.type)) {
          return false;
        }
        for (const value of Object.values(node)) {
          if (Array.isArray(value)) {
            if (value.some(nodeContainsAsyncControl)) {
              return true;
            }
          } else if (nodeContainsAsyncControl(value)) {
            return true;
          }
        }
        return false;
      }
    }
  });

  // lib/transpiler-new/validate-bindings.js
  var require_validate_bindings = __commonJS({
    "lib/transpiler-new/validate-bindings.js"(exports2, module2) {
      "use strict";
      var { TranspilerSyntaxError } = require_errors();
      var Scope = class {
        constructor(parent = null) {
          this.parent = parent;
          this.bindings = /* @__PURE__ */ new Map();
        }
        declare(name2, mutable, node) {
          if (!name2) {
            return;
          }
          if (this.bindings.has(name2)) {
            throw syntaxError(`Redeclaration of '${name2}' in the same scope`, node);
          }
          this.bindings.set(name2, { mutable, bodylessFunction: false });
        }
        declareFunction(node) {
          const name2 = node.id && node.id.name;
          if (!name2) {
            return;
          }
          const existing = this.bindings.get(name2);
          if (existing && existing.bodylessFunction && !node.isPredeclared) {
            existing.bodylessFunction = false;
            return;
          }
          if (existing) {
            throw syntaxError(`Redeclaration of '${name2}' in the same scope`, node);
          }
          this.bindings.set(name2, {
            mutable: false,
            bodylessFunction: node.isPredeclared === true
          });
        }
        lookup(name2) {
          if (this.bindings.has(name2)) {
            return this.bindings.get(name2);
          }
          return this.parent ? this.parent.lookup(name2) : null;
        }
      };
      function tokenFor(node) {
        const start = node && node.loc && node.loc.start;
        if (!start) {
          return null;
        }
        return {
          line: start.line,
          column: start.column
        };
      }
      function syntaxError(message, node) {
        return new TranspilerSyntaxError(message, tokenFor(node));
      }
      function validateBindings(ast) {
        const scope = new Scope();
        for (const name2 of [
          "__argc__",
          "__file__",
          "__global__",
          "__system__"
        ]) {
          scope.declare(name2, false, null);
        }
        validateStatements(ast.body || [], scope);
        return ast;
      }
      function validateStatements(statements, scope) {
        for (const statement of statements || []) {
          validateStatement(statement, scope);
        }
      }
      function validateStatement(node, scope) {
        if (!node) {
          return;
        }
        switch (node.type) {
          case "BlockStatement":
            validateStatements(node.body, new Scope(scope));
            return;
          case "VariableDeclaration":
            validateExpression(node.init, scope);
            scope.declare(node.id && node.id.name, node.kind !== "const", node);
            return;
          case "VariableUnpackDeclaration":
            validateVariableUnpackDeclaration(node, scope);
            return;
          case "FunctionDeclaration":
            scope.declareFunction(node);
            if (!node.isPredeclared) {
              validateFunctionBody(node, scope);
            }
            return;
          case "ClassDeclaration":
            scope.declare(node.id && node.id.name, false, node);
            validateClassBody(node, scope);
            return;
          case "TraitDeclaration":
            scope.declare(node.id && node.id.name, false, node);
            validateTraitBody(node, scope);
            return;
          case "ForInStatement":
            validateExpression(node.iterable, scope);
            validateForBody(node, scope);
            return;
          case "ExpressionStatement":
            validateExpression(node.expression, scope);
            return;
          default:
            validateChildNodes(node, scope);
        }
      }
      function validateVariableUnpackDeclaration(node, scope) {
        validateExpression(node.init, scope);
        const names = /* @__PURE__ */ new Set();
        for (const entry of bindingEntriesForPattern(node.pattern)) {
          if (names.has(entry.name)) {
            throw syntaxError(
              `Duplicate unpacked binding '${entry.name}' in declaration`,
              entry
            );
          }
          names.add(entry.name);
        }
        for (const entry of bindingEntriesForPattern(node.pattern)) {
          validateExpression(entry.key, scope);
          validateExpression(entry.defaultValue, scope);
        }
        for (const entry of bindingEntriesForPattern(node.pattern)) {
          scope.declare(entry.name, node.kind !== "const", entry);
        }
      }
      function bindingEntriesForPattern(pattern) {
        return pattern && Array.isArray(pattern.entries) ? pattern.entries : [];
      }
      function validateForBody(node, scope) {
        const loopScope = new Scope(scope);
        loopScope.declare(
          node.left && node.left.name,
          node.kind !== "const",
          node.left || node
        );
        validateStatement(node.body, loopScope);
        validateStatement(node.elseBlock, new Scope(scope));
      }
      function validateFunctionBody(node, parentScope) {
        const scope = new Scope(parentScope);
        for (const param of node.params || []) {
          if (param.type === "Parameter") {
            scope.declare(param.name, true, param);
          } else if (param.type === "SpecialParameter") {
            scope.declare(param.leadName, true, param);
            scope.declare(param.name, true, param);
          }
        }
        validateStatements(node.body && node.body.body, scope);
      }
      function validateClassBody(node, scope) {
        const classScope = new Scope(scope);
        const methodNames = /* @__PURE__ */ new Map();
        validateExpression(node.base, scope);
        for (const trait of node.traits || []) {
          validateExpression(trait, scope);
        }
        for (const entry of node.body || []) {
          if (entry.type === "FieldDeclaration") {
            validateExpression(entry.defaultValue, classScope);
          } else if (entry.type === "MethodDeclaration") {
            recordMethodDeclaration(methodNames, entry);
            if (!entry.isPredeclared) {
              validateFunctionBody(entry, classScope);
            }
          } else {
            validateStatement(entry, classScope);
          }
        }
      }
      function validateTraitBody(node, scope) {
        const methodNames = /* @__PURE__ */ new Map();
        for (const entry of node.body || []) {
          recordMethodDeclaration(methodNames, entry);
          if (!entry.isPredeclared) {
            validateFunctionBody(entry, scope);
          }
        }
      }
      function recordMethodDeclaration(methodNames, node) {
        const name2 = node.id && node.id.name;
        const existing = methodNames.get(name2);
        if (existing && existing.bodyless && !node.isPredeclared) {
          existing.bodyless = false;
          return;
        }
        if (existing) {
          throw syntaxError(`Redeclaration of '${name2}' in the same scope`, node);
        }
        methodNames.set(name2, { bodyless: node.isPredeclared === true });
      }
      function validateExpression(node, scope) {
        if (!node) {
          return;
        }
        switch (node.type) {
          case "AssignmentExpression":
            validateExpression(node.right, scope);
            requireValidAssignmentTarget(node.left);
            if (node.left && node.left.type === "Identifier") {
              requireMutable(node.left, scope);
            } else {
              validateExpression(node.left, scope);
            }
            return;
          case "UpdateExpression":
            requireValidAssignmentTarget(node.argument);
            if (node.argument && node.argument.type === "Identifier") {
              requireMutable(node.argument, scope);
            } else {
              validateExpression(node.argument, scope);
            }
            return;
          case "UnaryExpression":
            if (node.operator === "++" || node.operator === "--") {
              requireValidAssignmentTarget(node.argument);
              if (node.argument && node.argument.type === "Identifier") {
                requireMutable(node.argument, scope);
              } else {
                validateExpression(node.argument, scope);
              }
              return;
            }
            validateChildNodes(node, scope);
            return;
          case "RefExpression":
            requireValidAssignmentTarget(node.argument);
            validateExpression(node.argument, scope);
            return;
          case "FunctionExpression":
            validateFunctionBody(node, scope);
            return;
          case "LetExpression":
            validateExpression(node.init, scope);
            scope.declare(node.id && node.id.name, node.kind !== "const", node);
            return;
          default:
            validateChildNodes(node, scope);
        }
      }
      function requireValidAssignmentTarget(node) {
        const target = unwrapGroupedExpression(node);
        if (!target) {
          throw syntaxError("Invalid assignment target", node);
        }
        if (target.type === "Identifier" || target.type === "SliceExpression") {
          return;
        }
        if (target.type === "MemberExpression" && target.computed) {
          return;
        }
        if (target.type === "BinaryExpression" && ["@", "@@", "@?"].includes(target.operator)) {
          return;
        }
        throw syntaxError("Invalid assignment target", node);
      }
      function unwrapGroupedExpression(node) {
        let current = node;
        while (current && current.type === "GroupedExpression") {
          current = current.expression;
        }
        return current;
      }
      function requireMutable(node, scope) {
        const binding = scope.lookup(node.name);
        if (binding && !binding.mutable) {
          throw syntaxError(`Cannot assign to const '${node.name}' (compile-time)`, node);
        }
      }
      function validateChildNodes(node, scope) {
        if (!node || typeof node !== "object") {
          return;
        }
        for (const value of Object.values(node)) {
          if (!value) {
            continue;
          }
          if (Array.isArray(value)) {
            for (const item of value) {
              validateChildNode(item, scope);
            }
          } else {
            validateChildNode(value, scope);
          }
        }
      }
      function validateChildNode(node, scope) {
        if (!node || typeof node !== "object" || typeof node.type !== "string") {
          return;
        }
        if (node.type.endsWith("Statement") || node.type.endsWith("Declaration")) {
          validateStatement(node, scope);
        } else {
          validateExpression(node, scope);
        }
      }
      module2.exports = {
        validateBindings
      };
    }
  });

  // lib/transpiler-new/index.js
  var require_transpiler_new = __commonJS({
    "lib/transpiler-new/index.js"(exports2, module2) {
      "use strict";
      var { stripPod } = require_transpiler_utils();
      var { tokenize } = require_lexer();
      var { parse } = require_parser();
      var { emitProgram } = require_codegen();
      var { validateBindings } = require_validate_bindings();
      function transpileWithoutFallback(source, options = {}) {
        const preprocessed = stripPod(String(source ?? ""));
        const tokens = tokenize(preprocessed);
        const ast = parse(tokens);
        validateBindings(ast);
        return emitProgram(ast, { ...options, marshalSource: preprocessed });
      }
      function transpile(source, options = {}) {
        return transpileWithoutFallback(source, options);
      }
      module2.exports = {
        tokenize,
        parse,
        transpileWithoutFallback,
        transpile
      };
    }
  });

  // lib/transpiler.js
  var require_transpiler = __commonJS({
    "lib/transpiler.js"(exports2, module2) {
      "use strict";
      var { stripPod } = require_transpiler_utils();
      var { transpile: transpileNew } = require_transpiler_new();
      var DEFAULT_TRANSPILER = "new-only";
      var VALID_TRANSPILERS = /* @__PURE__ */ new Set([DEFAULT_TRANSPILER]);
      function normalizeTranspilerName(value) {
        if (value == null || value === "") {
          return DEFAULT_TRANSPILER;
        }
        const name2 = String(value).trim().toLowerCase();
        if (!VALID_TRANSPILERS.has(name2)) {
          throw new Error(
            `Unknown transpiler: ${value}. Expected: ${DEFAULT_TRANSPILER}`
          );
        }
        return name2;
      }
      function transpile(source, options = {}) {
        normalizeTranspilerName(options.transpiler);
        return transpileNew(source, options);
      }
      module2.exports = {
        DEFAULT_TRANSPILER,
        VALID_TRANSPILERS,
        normalizeTranspilerName,
        transpile,
        stripPod
      };
    }
  });

  // lib/host/capabilities.js
  var require_capabilities = __commonJS({
    "lib/host/capabilities.js"(exports2, module2) {
      "use strict";
      var MODULE_CAPABILITIES = {
        "std/io": ["fs"],
        "std/io/socks": ["fs", "net"],
        "std/proc": ["proc"],
        "std/db": ["db"],
        "std/clib": ["clib"],
        "std/gui/objects": ["gui"],
        "std/net/dns": ["net"],
        "std/net/http": ["http"],
        "std/worker": ["worker"],
        "perl": ["perl"],
        "javascript": ["js"]
      };
      var BROWSER_SAFE_MODULES = /* @__PURE__ */ new Set([
        "std/string",
        "std/time",
        "std/data/json",
        "std/data/xml",
        "std/net/http",
        "std/net/smtp",
        "std/secure",
        "std/math",
        "std/eval",
        "std/colour",
        "std/gui",
        "std/gui/dialogue",
        "std/gui/objects",
        "std/tui"
      ]);
      function capabilitiesForModule(moduleName) {
        for (const [prefix, capabilities2] of Object.entries(MODULE_CAPABILITIES)) {
          if (moduleName === prefix || moduleName.startsWith(`${prefix}/`)) {
            return capabilities2.slice();
          }
        }
        return [];
      }
      module2.exports = {
        MODULE_CAPABILITIES,
        BROWSER_SAFE_MODULES,
        capabilitiesForModule
      };
    }
  });

  // lib/execution-metadata.js
  var require_execution_metadata = __commonJS({
    "lib/execution-metadata.js"(exports2, module2) {
      "use strict";
      var compiledSources = /* @__PURE__ */ new Map();
      function setCompiledSource(filename, source) {
        if (typeof filename === "string" && typeof source === "string") {
          compiledSources.set(filename, source);
        }
      }
      function getCompiledSource(filename) {
        return compiledSources.get(filename) || null;
      }
      module2.exports = {
        getCompiledSource,
        setCompiledSource
      };
    }
  });

  // modules/std/task.js
  var require_task = __commonJS({
    "modules/std/task.js"(exports2, module2) {
      "use strict";
      var AsyncLocalStorage = null;
      try {
        AsyncLocalStorage = __require("node:async_hooks").AsyncLocalStorage;
      } catch (_err) {
      }
      var Exception = class extends Error {
        constructor(message = "") {
          super(String(message ?? ""));
          this.name = "Exception";
        }
        to_String() {
          const name2 = this.name || this.constructor.name || "Exception";
          const message = String(this.message ?? "");
          if (message === name2 || message.startsWith(`${name2}:`)) {
            return message;
          }
          return message === "" ? name2 : `${name2}: ${message}`;
        }
      };
      var CancelledException = class extends Exception {
        constructor(message = "Task cancelled") {
          super(message);
          this.name = "CancelledException";
        }
      };
      var TimeoutException = class extends Exception {
        constructor(message = "timeout") {
          super(message);
          this.name = "TimeoutException";
        }
      };
      var ChannelClosedException = class extends Exception {
        constructor(message = "send on closed channel") {
          super(message);
          this.name = "ChannelClosedException";
        }
      };
      var taskStorage = AsyncLocalStorage ? new AsyncLocalStorage() : null;
      var fallbackCurrentTask = null;
      var debugLevel = 0;
      var nextTaskId = 1;
      var activeTasks = /* @__PURE__ */ new Map();
      var traceEvents = [];
      var callsiteStack = [];
      function globalTimerRoot() {
        if (typeof globalThis !== "undefined") {
          return globalThis;
        }
        if (typeof global !== "undefined") {
          return global;
        }
        return {};
      }
      function safeSetTimeout(callback, delay) {
        const root = globalTimerRoot();
        return root.setTimeout.call(root, callback, delay);
      }
      function safeClearTimeout(timer) {
        const root = globalTimerRoot();
        return root.clearTimeout.call(root, timer);
      }
      function safeQueueMicrotask(callback) {
        const root = globalTimerRoot();
        if (typeof root.queueMicrotask === "function") {
          return root.queueMicrotask.call(root, callback);
        }
        return safeSetTimeout(callback, 0);
      }
      function currentTask() {
        return taskStorage ? taskStorage.getStore() : fallbackCurrentTask;
      }
      function runWithTask(task2, fn2) {
        if (taskStorage) {
          return taskStorage.run(task2, fn2);
        }
        const previous = fallbackCurrentTask;
        fallbackCurrentTask = task2;
        try {
          return fn2();
        } finally {
          fallbackCurrentTask = previous;
        }
      }
      function normalizeException(value, ExceptionClass = Exception) {
        if (value instanceof Error) {
          return value;
        }
        return new ExceptionClass(value == null ? "" : String(value));
      }
      function currentCallsite() {
        return callsiteStack.length > 0 ? callsiteStack[callsiteStack.length - 1] : null;
      }
      function withCallsite(metadata, fn2) {
        callsiteStack.push(metadata || null);
        try {
          return fn2();
        } finally {
          callsiteStack.pop();
        }
      }
      function traceTask(event, task2 = null, extra = null) {
        if (debugLevel <= 0) {
          return null;
        }
        const record = {
          event,
          task_id: task2 ? task2._id : null,
          parent_task_id: task2 ? task2._parentId : null,
          name: task2 ? task2._name : null,
          status: task2 ? task2._status : null,
          file: task2 ? task2._file : null,
          line: task2 ? task2._line : null
        };
        if (extra && typeof extra === "object") {
          Object.assign(record, extra);
        }
        traceEvents.push(record);
        return record;
      }
      function cleanupTask(task2) {
        if (!task2 || !task2.done()) {
          return;
        }
        activeTasks.delete(task2._id);
        traceTask("cleanup", task2);
      }
      var Task = class _Task {
        constructor(executor = null, options = {}) {
          const parent = currentTask();
          const callsite = currentCallsite();
          this._id = nextTaskId++;
          this._parentId = options.parentTaskId != null ? options.parentTaskId : parent ? parent._id : null;
          this._name = options.name || "<task>";
          this._file = options.file || (callsite ? callsite.file : null) || null;
          this._line = options.line || (callsite ? callsite.line : null) || null;
          this._status = options.status || "pending";
          this._value = void 0;
          this._reason = null;
          this._children = /* @__PURE__ */ new Set();
          this._cancelHook = typeof options.cancel === "function" ? options.cancel : null;
          this._pollHook = typeof options.poll === "function" ? options.poll : null;
          activeTasks.set(this._id, this);
          traceTask("schedule", this);
          this._promise = new Promise((resolve, reject) => {
            this._resolve = (value) => {
              if (this.done()) {
                return;
              }
              this._status = "fulfilled";
              this._value = value;
              traceTask("fulfill", this);
              resolve(value);
              cleanupTask(this);
            };
            this._reject = (err, forcedStatus = null) => {
              if (this.done()) {
                return;
              }
              this._status = forcedStatus || (err instanceof CancelledException ? "cancelled" : "rejected");
              this._reason = err;
              traceTask(this._status === "cancelled" ? "cancel" : "reject", this);
              reject(err);
              cleanupTask(this);
            };
          });
          this._promise.catch(() => {
          });
          if (executor) {
            safeQueueMicrotask(() => {
              if (this.done()) {
                return;
              }
              this._status = options.status || "running";
              traceTask("start", this);
              runWithTask(this, async () => {
                try {
                  this._resolve(await executor());
                } catch (err) {
                  this._reject(err);
                }
              });
            });
          }
        }
        static resolved(value = null) {
          const task2 = new _Task();
          task2._resolve(value);
          return task2;
        }
        static failed(value) {
          const task2 = new _Task();
          task2._reject(normalizeException(value));
          return task2;
        }
        static from(value) {
          if (value instanceof _Task) {
            return value;
          }
          if (value && typeof value.then === "function") {
            const task2 = new _Task();
            Promise.resolve(value).then(
              (result) => task2._resolve(result),
              (err) => task2._reject(err)
            );
            return task2;
          }
          return _Task.resolved(value);
        }
        then(resolve, reject) {
          return this._promise.then(resolve, reject);
        }
        catch(reject) {
          return this._promise.catch(reject);
        }
        finally(callback) {
          return this._promise.finally(callback);
        }
        status() {
          return this._status;
        }
        id() {
          return this._id;
        }
        parent_id() {
          return this._parentId;
        }
        name() {
          return this._name;
        }
        is_done() {
          return this.done();
        }
        done() {
          return ["fulfilled", "rejected", "cancelled"].includes(this._status) ? 1 : 0;
        }
        poll() {
          if (!this.done() && this._pollHook) {
            try {
              this._pollHook();
            } catch (err) {
              this._reject(err);
            }
          }
          return this.done();
        }
        to_String() {
          return `[Task ${this._status}]`;
        }
        cancel(reason = null) {
          if (this.done()) {
            return this;
          }
          const err = normalizeException(
            reason == null ? "Task cancelled" : reason,
            CancelledException
          );
          this._reason = err;
          for (const child of this._children) {
            if (child && typeof child.cancel === "function") {
              child.cancel(err);
            }
          }
          if (this._cancelHook) {
            try {
              this._cancelHook(err);
            } catch (_err) {
            }
          }
          this._reject(err, "cancelled");
          return this;
        }
        _track(child) {
          if (child instanceof _Task) {
            this._children.add(child);
          }
        }
        _untrack(child) {
          if (child instanceof _Task) {
            this._children.delete(child);
          }
        }
      };
      Object.defineProperty(Task.prototype, "__zuzu_type_name", {
        value: "Task",
        enumerable: false,
        configurable: true,
        writable: true
      });
      async function awaitValueWithParent(value, parent) {
        if (parent && parent.status() === "cancelled") {
          throw parent._reason || new CancelledException();
        }
        const task2 = Task.from(value);
        if (parent) {
          parent._track(task2);
        }
        try {
          return await task2;
        } finally {
          if (parent) {
            parent._untrack(task2);
            if (parent.status() === "cancelled") {
              throw parent._reason || new CancelledException();
            }
          }
        }
      }
      async function awaitValue(value) {
        return awaitValueWithParent(value, currentTask());
      }
      async function awaitBlock(value) {
        const parent = currentTask();
        const boxedValue = value && typeof value.then === "function" ? await value : value;
        const resolvedValue = boxedValue && typeof boxedValue === "object" && Object.prototype.hasOwnProperty.call(boxedValue, "__zuzu_await_block_value") ? boxedValue.__zuzu_await_block_value : boxedValue;
        if (!(resolvedValue instanceof Task)) {
          throw new Exception("await block must return a Task");
        }
        return awaitValueWithParent(resolvedValue, parent);
      }
      function awaitValueSync(value) {
        const task2 = Task.from(value);
        if (task2.status() === "fulfilled") {
          return task2._value;
        }
        if (task2.status() === "rejected" || task2.status() === "cancelled") {
          throw task2._reason || new Exception("Task failed");
        }
        throw new Exception("cannot synchronously await pending task");
      }
      function awaitBlockSync(value) {
        const resolvedValue = value && typeof value === "object" && Object.prototype.hasOwnProperty.call(value, "__zuzu_await_block_value") ? value.__zuzu_await_block_value : value;
        if (!(resolvedValue instanceof Task)) {
          throw new Exception("await block must return a Task");
        }
        return awaitValueSync(resolvedValue);
      }
      function task(fn2, _metadata = {}) {
        const callsite = currentCallsite();
        return new Task(async () => fn2(), {
          name: _metadata.name || "<async>",
          file: (callsite ? callsite.file : null) || _metadata.file || null,
          line: (callsite ? callsite.line : null) || _metadata.line || null
        });
      }
      function taskSync(fn2, _metadata = {}) {
        const callsite = currentCallsite();
        const task2 = new Task(null, {
          name: _metadata.name || "<async>",
          file: (callsite ? callsite.file : null) || _metadata.file || null,
          line: (callsite ? callsite.line : null) || _metadata.line || null
        });
        task2._status = "running";
        traceTask("start", task2);
        try {
          const value = runWithTask(task2, () => fn2());
          if (value instanceof Task) {
            if (value.status() === "fulfilled") {
              task2._resolve(value._value);
            } else if (value.status() === "rejected" || value.status() === "cancelled") {
              task2._reject(value._reason || new Exception("Task failed"));
            } else {
              task2._reject(new Exception("cannot synchronously await pending task"));
            }
          } else if (value && typeof value.then === "function") {
            Task.from(value).then(
              (result) => task2._resolve(result),
              (err) => task2._reject(err)
            );
          } else {
            task2._resolve(value);
          }
        } catch (err) {
          task2._reject(err);
        }
        return task2;
      }
      function spawn(fn2, _metadata = {}) {
        return new Task(async () => fn2(), {
          status: "running",
          name: _metadata.name || "<spawn>",
          file: _metadata.file || (currentCallsite() ? currentCallsite().file : null) || null,
          line: _metadata.line || (currentCallsite() ? currentCallsite().line : null) || null
        });
      }
      function resolved(value = null) {
        return Task.resolved(value);
      }
      function failed(value) {
        return Task.failed(value == null ? "Task failed" : value);
      }
      function sleep(seconds = 0) {
        let timer = null;
        const readyAt = Date.now() + Math.max(0, Number(seconds) || 0) * 1e3;
        const task2 = new Task(null, {
          status: "sleeping",
          name: "sleep",
          poll() {
            if (Date.now() >= readyAt) {
              if (timer != null) {
                safeClearTimeout(timer);
                timer = null;
              }
              task2._resolve(null);
            }
          },
          cancel() {
            if (timer != null) {
              safeClearTimeout(timer);
              timer = null;
            }
          }
        });
        timer = safeSetTimeout(() => {
          timer = null;
          task2._resolve(null);
        }, Math.max(0, Number(seconds) || 0) * 1e3);
        return task2;
      }
      function yieldTask() {
        let timer = null;
        const task2 = new Task(null, {
          status: "waiting",
          name: "yield",
          cancel() {
            if (timer != null) {
              safeClearTimeout(timer);
              timer = null;
            }
          }
        });
        timer = safeSetTimeout(() => {
          timer = null;
          task2._resolve(null);
        }, 0);
        return task2;
      }
      function all(values = []) {
        const tasks = taskItems(values, "all");
        return new Task(
          () => new Promise((resolve, reject) => {
            if (tasks.length === 0) {
              resolve([]);
              return;
            }
            const results = new Array(tasks.length);
            let remaining = tasks.length;
            let settled = false;
            tasks.forEach((task2, index) => {
              task2.then(
                (value) => {
                  if (settled) {
                    return;
                  }
                  results[index] = value;
                  remaining--;
                  if (remaining === 0) {
                    settled = true;
                    resolve(results);
                  }
                },
                (err) => {
                  if (settled) {
                    return;
                  }
                  settled = true;
                  for (const child of tasks) {
                    if (child !== task2) {
                      child.cancel();
                    }
                  }
                  reject(err);
                }
              );
            });
          }),
          {
            status: "waiting",
            name: "all",
            cancel(reason) {
              for (const task2 of tasks) {
                task2.cancel(reason);
              }
            }
          }
        );
      }
      function race(values = []) {
        const tasks = taskItems(values, "race");
        if (tasks.length === 0) {
          return Task.failed(new Exception("race expects at least one task"));
        }
        return new Task(
          () => new Promise((resolve, reject) => {
            let settled = false;
            for (const task2 of tasks) {
              task2.then(
                (value) => {
                  if (settled) {
                    return;
                  }
                  settled = true;
                  for (const loser of tasks) {
                    if (loser !== task2) {
                      loser.cancel(new CancelledException("race loser cancelled"));
                    }
                  }
                  resolve(value);
                },
                (err) => {
                  if (settled) {
                    return;
                  }
                  settled = true;
                  for (const loser of tasks) {
                    if (loser !== task2) {
                      loser.cancel(new CancelledException("race loser cancelled"));
                    }
                  }
                  reject(err);
                }
              );
            }
          }),
          {
            status: "waiting",
            name: "race",
            cancel(reason) {
              for (const task2 of tasks) {
                task2.cancel(reason);
              }
            }
          }
        );
      }
      function timeout(seconds, value) {
        if (!(value instanceof Task)) {
          throw new Exception("timeout expects a Task");
        }
        const waited = value;
        const timeoutError = () => new TimeoutException(`timeout after ${Number(seconds) || 0}s`);
        let settled = false;
        let timer = null;
        return new Task(
          () => new Promise((resolve, reject) => {
            timer = safeSetTimeout(() => {
              if (settled) {
                return;
              }
              settled = true;
              const err = timeoutError();
              waited.cancel(err);
              reject(err);
            }, Math.max(0, Number(seconds) || 0) * 1e3);
            waited.then(
              (result) => {
                if (settled) {
                  return;
                }
                settled = true;
                if (timer != null) {
                  safeClearTimeout(timer);
                  timer = null;
                }
                resolve(result);
              },
              (err) => {
                if (settled) {
                  return;
                }
                settled = true;
                if (timer != null) {
                  safeClearTimeout(timer);
                  timer = null;
                }
                reject(err);
              }
            );
          }),
          {
            status: "waiting",
            name: "timeout",
            cancel(reason) {
              settled = true;
              if (timer != null) {
                safeClearTimeout(timer);
                timer = null;
              }
              waited.cancel(reason);
            }
          }
        );
      }
      var Channel = class {
        constructor() {
          this._closed = false;
          this._queue = [];
          this._receivers = [];
        }
        send(value = null) {
          if (this._closed) {
            return Task.failed(new ChannelClosedException());
          }
          const receiver = this._receivers.shift();
          if (receiver) {
            receiver._resolve(value);
          } else {
            this._queue.push(value);
          }
          return Task.resolved(value);
        }
        recv() {
          if (this._queue.length > 0) {
            return Task.resolved(this._queue.shift());
          }
          if (this._closed) {
            return Task.resolved(null);
          }
          const task2 = new Task(null, {
            status: "waiting",
            name: "channel.recv",
            cancel: () => {
              this._receivers = this._receivers.filter((item) => item !== task2);
            }
          });
          this._receivers.push(task2);
          return task2;
        }
        close() {
          this._closed = true;
          while (this._receivers.length > 0) {
            this._receivers.shift()._resolve(null);
          }
          return null;
        }
      };
      var CancellationToken = class {
        constructor() {
          this._cancelled = false;
          this._reason = null;
          this._tasks = /* @__PURE__ */ new Set();
        }
        cancelled() {
          return this._cancelled ? 1 : 0;
        }
        reason() {
          return this._reason;
        }
        throw_if_cancelled() {
          if (this._cancelled) {
            throw this._reason || new CancelledException();
          }
          return null;
        }
        watch(task2) {
          if (!(task2 instanceof Task)) {
            throw new Exception("CancellationToken.watch expects a Task");
          }
          if (this._cancelled) {
            task2.cancel(this._reason);
          } else {
            this._tasks.add(task2);
          }
          return task2;
        }
      };
      var CancellationSource = class {
        constructor() {
          this._token = new CancellationToken();
        }
        token() {
          return this._token;
        }
        cancel(reason = null) {
          if (this._token._cancelled) {
            return this;
          }
          this._token._cancelled = true;
          this._token._reason = normalizeException(
            reason == null ? "Task cancelled" : reason,
            CancelledException
          );
          for (const task2 of this._token._tasks) {
            task2.cancel(this._token._reason);
          }
          this._token._tasks.clear();
          return this;
        }
        cancelled() {
          return this._token.cancelled();
        }
        reason() {
          return this._token.reason();
        }
      };
      function setDebugLevel(level = 0) {
        debugLevel = Number(level) || 0;
      }
      function clearTrace() {
        traceEvents.length = 0;
        return null;
      }
      function taskTrace() {
        return traceEvents.map((record) => ({ ...record }));
      }
      function activeCount() {
        for (const task2 of [...activeTasks.values()]) {
          cleanupTask(task2);
        }
        return activeTasks.size;
      }
      function traceBlockingOperation(operation, metadata = {}) {
        const task2 = currentTask();
        if (!task2 || debugLevel <= 0) {
          return null;
        }
        return traceTask("blocked_operation", task2, {
          operation: String(operation ?? ""),
          ...metadata
        });
      }
      function shutdown(reason = null) {
        for (const task2 of [...activeTasks.values()]) {
          if (!task2.done()) {
            task2.cancel(reason == null ? "Task cancelled" : reason);
          }
        }
        traceTask("shutdown", null);
        return null;
      }
      function resetForRun(level = 0) {
        const previousDebugLevel = debugLevel;
        debugLevel = 0;
        shutdown("Task cancelled");
        debugLevel = Number(level) || 0;
        traceEvents.length = 0;
        nextTaskId = 1;
        fallbackCurrentTask = null;
        callsiteStack.length = 0;
        return previousDebugLevel;
      }
      function withoutAsyncLocalStorageForTesting(fn2) {
        const previous = taskStorage;
        taskStorage = null;
        try {
          const result = fn2();
          if (result && typeof result.then === "function") {
            return Promise.resolve(result).finally(() => {
              taskStorage = previous;
              fallbackCurrentTask = null;
            });
          }
          taskStorage = previous;
          fallbackCurrentTask = null;
          return result;
        } catch (err) {
          taskStorage = previous;
          fallbackCurrentTask = null;
          throw err;
        }
      }
      function taskItems(values, label) {
        if (!Array.isArray(values)) {
          throw new Exception("TypeException: task combinator expects Array");
        }
        const out = [];
        for (const value of values) {
          if (!(value instanceof Task)) {
            throw new Exception(`${label} expects only Task values`);
          }
          out.push(value);
        }
        return out;
      }
      module2.exports = {
        Task,
        Exception,
        CancelledException,
        TimeoutException,
        ChannelClosedException,
        Channel,
        CancellationToken,
        CancellationSource,
        awaitValue,
        awaitBlock,
        awaitValueSync,
        awaitBlockSync,
        withCallsite,
        runWithTask,
        currentTask,
        setDebugLevel,
        clearTrace,
        taskTrace,
        activeCount,
        traceBlockingOperation,
        shutdown,
        resetForRun,
        withoutAsyncLocalStorageForTesting,
        task,
        taskSync,
        spawn,
        resolved,
        failed,
        sleep,
        yield: yieldTask,
        all,
        race,
        timeout
      };
    }
  });

  // package.json
  var require_package = __commonJS({
    "package.json"(exports2, module2) {
      module2.exports = {
        name: "zuzu-js",
        version: "0.6.0",
        description: "JavaScript runtime, compiler, and browser bundle for ZuzuScript.",
        main: "lib/zuzu.js",
        bin: {
          zuzu: "bin/zuzu",
          "zuzu-js": "bin/zuzu-js",
          "zuzu-js-compile": "bin/zuzu-js-compile",
          "zuzu-js-electron": "bin/zuzu-js-electron"
        },
        files: [
          "bin/",
          "dist/zuzu-browser.js",
          "dist/zuzu-browser-worker.js",
          "lib/",
          "modules/",
          "stdlib/modules/"
        ],
        directories: {
          example: "examples",
          lib: "lib",
          test: "test"
        },
        scripts: {
          "electron:demo": "electron bin/zuzu-js-electron docs/examples/09_gui_dialogue_demo.zzs",
          test: "node test/cli.js && node test/argument-spread.js && node test/default-operator.js && node test/declaration-unpacking.js && node test/collection-copy.js && node test/std-marshal-cbor.js && node test/std-marshal-data-graph.js && node test/std-marshal-user-object.js && node test/std-marshal-code-table.js && node test/async-parity.js && node test/browser-stdlib-generator.js && node test/browser-gui.js && node test/electron-gui.js && node test/electron-renderer.js && node test/electron-packaging.js",
          "test:electron": "node test/electron-gui.js && node test/electron-renderer.js && node test/electron-packaging.js"
        },
        keywords: [
          "zuzu",
          "zuzuscript",
          "language",
          "runtime",
          "compiler"
        ],
        author: "",
        license: "Artistic-1.0 OR GPL-2.0-or-later",
        repository: {
          type: "git",
          url: "git+ssh://git@github.com/zuzuscript/zuzu-js.git"
        },
        bugs: {
          url: "https://github.com/zuzuscript/zuzu-js/issues"
        },
        homepage: "https://zuzulang.org/",
        engines: {
          node: ">=16"
        },
        dependencies: {
          "@std-uritemplate/std-uritemplate": "^2.0.10",
          "@xmldom/xmldom": "^0.9.10",
          "adm-zip": "^0.5.17",
          "better-sqlite3": "^11.10.0",
          "cbor-x": "^1.6.4",
          cborg: "^5.1.1",
          compressjs: "^1.0.3",
          "js-yaml": "^4.1.1",
          koffi: "^2.16.1",
          mysql2: "^3.22.3",
          "node-forge": "^1.4.0",
          pg: "^8.20.0",
          xpath: "^0.0.34"
        },
        devDependencies: {
          electron: "^41.3.0"
        }
      };
    }
  });

  // modules/std/io.js
  var require_io = __commonJS({
    "modules/std/io.js"(exports2, module2) {
      "use strict";
      var fs = __require("node:fs");
      var os = __require("node:os");
      var path = __require("node:path");
      var { BinaryString: BinaryString2 } = require_runtime_helpers();
      var { Task, traceBlockingOperation } = require_task();
      var runtimePolicy2 = {};
      function makeTempFilePath() {
        for (let attempt = 0; attempt < 1e3; attempt++) {
          const nonce = `${process.pid}-${Date.now()}-${attempt}-${Math.random().toString(36).slice(2)}`;
          const file = path.join(os.tmpdir(), `zuzu-js-${nonce}.tmp`);
          let fd = null;
          try {
            fd = fs.openSync(file, "wx");
            return file;
          } catch (err) {
            if (err && err.code === "EEXIST") {
              continue;
            }
            throw err;
          } finally {
            if (fd !== null) {
              fs.closeSync(fd);
            }
          }
        }
        throw new Error("IOError: could not create temporary file");
      }
      function typeName2(value) {
        if (value == null) {
          return "Null";
        }
        if (typeof value === "string") {
          return "String";
        }
        if (value.bytes instanceof Uint8Array) {
          return "BinaryString";
        }
        return value.constructor && value.constructor.name ? value.constructor.name : typeof value;
      }
      function bool(value) {
        return value ? 1 : 0;
      }
      function formatSizeHuman(size) {
        const units = ["B", "KB", "MB", "GB", "TB"];
        let value = Number(size);
        let unit = 0;
        while (value >= 1024 && unit < units.length - 1) {
          value /= 1024;
          unit++;
        }
        if (unit === 0) {
          return `${value} ${units[unit]}`;
        }
        return `${value.toFixed(1)} ${units[unit]}`;
      }
      function binaryLinesFromBuffer(buffer) {
        const out = [];
        let start = 0;
        for (let i = 0; i < buffer.length; i++) {
          if (buffer[i] === 10) {
            out.push(new BinaryString2(Uint8Array.from(buffer.slice(start, i + 1))));
            start = i + 1;
          }
        }
        if (start < buffer.length) {
          out.push(new BinaryString2(Uint8Array.from(buffer.slice(start))));
        }
        return out;
      }
      function textLinesFromString(text) {
        const out = [];
        let start = 0;
        for (let i = 0; i < text.length; i++) {
          if (text[i] === "\n") {
            out.push(text.slice(start, i + 1));
            start = i + 1;
          }
        }
        if (start < text.length) {
          out.push(text.slice(start));
        }
        return out;
      }
      function renderValue(value) {
        if (value && value.bytes instanceof Uint8Array) {
          return value.to_String();
        }
        if (typeof runtimePolicy2.to_String === "function") {
          return runtimePolicy2.to_String(value);
        }
        return String(value ?? "");
      }
      function writeStdout(text) {
        if (typeof runtimePolicy2.stdout_write === "function") {
          runtimePolicy2.stdout_write(text);
          return;
        }
        process.stdout.write(text);
      }
      function writeStderr(text) {
        if (typeof runtimePolicy2.stderr_write === "function") {
          runtimePolicy2.stderr_write(text);
          return;
        }
        process.stderr.write(text);
      }
      function streamPayload(values, newline) {
        const text = values.map(renderValue).join("");
        return newline ? `${text}
` : text;
      }
      var StandardOutputStream = class {
        print(...values) {
          writeStdout(streamPayload(values, false));
          return null;
        }
        say(...values) {
          writeStdout(streamPayload(values, true));
          return null;
        }
      };
      var StandardErrorStream = class {
        print(...values) {
          writeStderr(streamPayload(values, false));
          return null;
        }
        say(...values) {
          writeStderr(streamPayload(values, true));
          return null;
        }
      };
      var StandardInputStream = class {
        constructor() {
          this._buffer = null;
          this._linePos = 0;
          this._lineMode = "text";
        }
        _bufferBytes() {
          if (this._buffer == null) {
            this._buffer = fs.readFileSync(0);
          }
          return this._buffer;
        }
        _lines(raw) {
          const buffer = this._bufferBytes();
          return raw ? binaryLinesFromBuffer(buffer) : textLinesFromString(buffer.toString("utf8"));
        }
        next_line(raw = false) {
          const mode = raw ? "raw" : "text";
          if (this._lineMode !== mode) {
            this._lineMode = mode;
            this._linePos = 0;
          }
          const lines = this._lines(raw);
          if (this._linePos >= lines.length) {
            return null;
          }
          return lines[this._linePos++];
        }
        each_line(fn2, raw = false) {
          for (const line of this._lines(raw).slice(this._linePos)) {
            fn2(line);
            this._linePos++;
          }
          return this;
        }
      };
      function statToDict(stats) {
        if (!stats) {
          return null;
        }
        const out = {
          dev: stats.dev,
          ino: stats.ino,
          mode: stats.mode,
          nlink: stats.nlink,
          uid: stats.uid,
          gid: stats.gid,
          rdev: stats.rdev,
          size: stats.size,
          atime: Math.floor(stats.atimeMs / 1e3),
          mtime: Math.floor(stats.mtimeMs / 1e3),
          ctime: Math.floor(stats.ctimeMs / 1e3),
          blksize: stats.blksize ?? 0,
          blocks: stats.blocks ?? 0
        };
        Object.defineProperty(out, "has", {
          value(key) {
            return Object.prototype.hasOwnProperty.call(out, String(key)) ? 1 : 0;
          },
          enumerable: false
        });
        Object.defineProperty(out, "get", {
          value(key, fallback = null) {
            return Object.prototype.hasOwnProperty.call(out, String(key)) ? out[String(key)] : fallback;
          },
          enumerable: false
        });
        return out;
      }
      var Path = class _Path {
        constructor(rawPath, options = {}) {
          const pathValue = rawPath && typeof rawPath === "object" && !Array.isArray(rawPath) && (Object.prototype.hasOwnProperty.call(rawPath, "path") || typeof rawPath.get === "function" && typeof rawPath.has === "function" && rawPath.has("path")) ? typeof rawPath.get === "function" ? rawPath.get("path") : rawPath.path : rawPath;
          this.value = String(pathValue ?? "");
          this._linePos = 0;
          this._lineMode = "text";
          this._tempCleanup = options.tempCleanup || null;
        }
        __demolish__() {
          const cleanup = this._tempCleanup;
          this._tempCleanup = null;
          if (cleanup === "dir") {
            try {
              fs.rmSync(this.value, { recursive: true, force: true });
            } catch (_err) {
            }
          } else if (cleanup === "file") {
            try {
              fs.rmSync(this.value, { force: true });
            } catch (_err) {
            }
          }
          return null;
        }
        to_String() {
          return this.value;
        }
        parent() {
          const dir = path.dirname(this.value);
          return new _Path(dir === "" ? "." : dir);
        }
        sibling(name2) {
          return this.parent().child(name2);
        }
        absolute() {
          return new _Path(path.resolve(this.value));
        }
        realpath() {
          try {
            return new _Path(fs.realpathSync(this.value));
          } catch (_err) {
            return null;
          }
        }
        is_absolute() {
          return path.isAbsolute(this.value) ? 1 : 0;
        }
        basename() {
          return path.basename(this.value);
        }
        exists() {
          return bool(fs.existsSync(this.value));
        }
        is_file() {
          try {
            return bool(fs.statSync(this.value).isFile());
          } catch (_err) {
            return 0;
          }
        }
        is_dir() {
          try {
            return bool(fs.statSync(this.value).isDirectory());
          } catch (_err) {
            return 0;
          }
        }
        size() {
          return fs.statSync(this.value).size;
        }
        size_human() {
          return formatSizeHuman(this.size());
        }
        stat() {
          return statToDict(fs.statSync(this.value));
        }
        lstat() {
          return statToDict(fs.lstatSync(this.value));
        }
        child(name2) {
          return new _Path(path.join(this.value, String(name2)));
        }
        children() {
          return fs.readdirSync(this.value).map((name2) => new _Path(path.join(this.value, name2)));
        }
        iterator() {
          const kids = this.children();
          let i = 0;
          return {
            next() {
              if (i >= kids.length) {
                return null;
              }
              return kids[i++];
            }
          };
        }
        chmod(mode) {
          fs.chmodSync(this.value, Number(mode));
          return Number(mode);
        }
        copy(target) {
          const dest = target instanceof _Path ? target : new _Path(target);
          fs.copyFileSync(this.value, dest.value);
          return dest;
        }
        move(target) {
          const dest = target instanceof _Path ? target : new _Path(target);
          fs.renameSync(this.value, dest.value);
          return dest;
        }
        remove() {
          try {
            fs.rmSync(this.value, { force: true });
            return 1;
          } catch (_err) {
            return 0;
          }
        }
        remove_tree() {
          try {
            fs.rmSync(this.value, { recursive: true, force: true });
            return 1;
          } catch (_err) {
            return 0;
          }
        }
        touchpath() {
          fs.mkdirSync(path.dirname(this.value), { recursive: true });
          if (!fs.existsSync(this.value)) {
            fs.writeFileSync(this.value, "");
          }
          return this;
        }
        mkdir() {
          fs.mkdirSync(this.value, { recursive: true });
          return 1;
        }
        mkdir_exclusive() {
          try {
            fs.mkdirSync(this.value);
            return 1;
          } catch (err) {
            if (err && err.code === "EEXIST") {
              return 0;
            }
            throw err;
          }
        }
        spew(value) {
          traceBlockingOperation("std/io Path.spew");
          if (!(value && value.bytes instanceof Uint8Array)) {
            throw new Error(`TypeException: Path.spew expects BinaryString, got ${typeName2(value)}`);
          }
          fs.writeFileSync(this.value, Buffer.from(value.bytes));
          return this;
        }
        spew_async(value) {
          return new Task(async () => {
            this.spew(value);
            return this;
          });
        }
        slurp() {
          traceBlockingOperation("std/io Path.slurp");
          return new BinaryString2(Uint8Array.from(fs.readFileSync(this.value)));
        }
        slurp_async() {
          return new Task(async () => new BinaryString2(Uint8Array.from(await fs.promises.readFile(this.value))));
        }
        spew_utf8(text) {
          traceBlockingOperation("std/io Path.spew_utf8");
          if (typeof text !== "string") {
            throw new Error(`TypeException: Path.spew_utf8 expects String, got ${typeName2(text)}`);
          }
          fs.writeFileSync(this.value, text, "utf8");
          return this;
        }
        spew_utf8_async(text) {
          return new Task(async () => {
            if (typeof text !== "string") {
              throw new Error(`TypeException: Path.spew_utf8 expects String, got ${typeName2(text)}`);
            }
            await fs.promises.writeFile(this.value, text, "utf8");
            return this;
          });
        }
        slurp_utf8() {
          traceBlockingOperation("std/io Path.slurp_utf8");
          return fs.readFileSync(this.value, "utf8");
        }
        slurp_utf8_async() {
          return new Task(async () => fs.promises.readFile(this.value, "utf8"));
        }
        append(value) {
          traceBlockingOperation("std/io Path.append");
          if (!(value && value.bytes instanceof Uint8Array)) {
            throw new Error(`TypeException: Path.append expects BinaryString, got ${typeName2(value)}`);
          }
          fs.appendFileSync(this.value, Buffer.from(value.bytes));
          return this;
        }
        append_async(value) {
          return new Task(async () => {
            if (!(value && value.bytes instanceof Uint8Array)) {
              throw new Error(`TypeException: Path.append expects BinaryString, got ${typeName2(value)}`);
            }
            await fs.promises.appendFile(this.value, Buffer.from(value.bytes));
            return this;
          });
        }
        append_utf8(text) {
          traceBlockingOperation("std/io Path.append_utf8");
          if (typeof text !== "string") {
            throw new Error(`TypeException: Path.append_utf8 expects String, got ${typeName2(text)}`);
          }
          fs.appendFileSync(this.value, text, "utf8");
          return this;
        }
        append_utf8_async(text) {
          return new Task(async () => {
            if (typeof text !== "string") {
              throw new Error(`TypeException: Path.append_utf8 expects String, got ${typeName2(text)}`);
            }
            await fs.promises.appendFile(this.value, text, "utf8");
            return this;
          });
        }
        lines_async() {
          return new Task(async () => binaryLinesFromBuffer(await fs.promises.readFile(this.value)));
        }
        lines_utf8_async() {
          return new Task(async () => textLinesFromString(await fs.promises.readFile(this.value, "utf8")));
        }
        each_line(fn2, raw = false) {
          traceBlockingOperation("std/io Path.each_line");
          const lines = raw ? binaryLinesFromBuffer(fs.readFileSync(this.value)) : textLinesFromString(this.slurp_utf8());
          for (const line of lines) {
            fn2(line);
          }
          return this;
        }
        next_line(raw = false) {
          traceBlockingOperation("std/io Path.next_line");
          const mode = raw ? "raw" : "text";
          if (this._lineMode !== mode) {
            this._lineMode = mode;
            this._linePos = 0;
          }
          const lines = raw ? binaryLinesFromBuffer(fs.readFileSync(this.value)) : textLinesFromString(this.slurp_utf8());
          if (this._linePos >= lines.length) {
            return null;
          }
          return lines[this._linePos++];
        }
        static cwd() {
          return new _Path(process.cwd());
        }
        static tempfile() {
          return new _Path(makeTempFilePath(), { tempCleanup: "file" });
        }
        static tempdir() {
          return new _Path(
            fs.mkdtempSync(path.join(os.tmpdir(), "zuzu-js-dir-")),
            { tempCleanup: "dir" }
          );
        }
        static join(parts) {
          return new _Path(path.join(...parts.map((p) => String(p))));
        }
        static split(source) {
          return path.normalize(String(source)).split(path.sep).filter(Boolean);
        }
        static normalize(source) {
          return new _Path(path.normalize(String(source)));
        }
        static glob(pattern) {
          const text = String(pattern ?? "");
          const star = text.indexOf("*");
          if (star < 0) {
            return fs.existsSync(text) ? [new _Path(text)] : [];
          }
          const dir = path.dirname(text);
          const ext = text.slice(star + 1);
          return fs.readdirSync(dir).filter((name2) => ext === "" || name2.endsWith(ext.replace(/^\./u, "."))).map((name2) => new _Path(path.join(dir, name2)));
        }
      };
      module2.exports = {
        Path,
        STDIN: new StandardInputStream(),
        STDOUT: new StandardOutputStream(),
        STDERR: new StandardErrorStream()
      };
      Object.defineProperty(module2.exports, "__zuzu_set_runtime_policy", {
        value(policy = {}) {
          runtimePolicy2 = policy || {};
        },
        enumerable: false
      });
    }
  });

  // lib/runtime.js
  var require_runtime = __commonJS({
    "lib/runtime.js"(exports2, module2) {
      "use strict";
      var { capabilitiesForModule } = require_capabilities();
      var { setCompiledSource } = require_execution_metadata();
      var {
        DEFAULT_TRANSPILER,
        normalizeTranspilerName,
        transpile,
        stripPod
      } = require_transpiler();
      var {
        collectTopLevelDeclarations,
        runSwitch,
        runMatch,
        contains,
        collectionUnion,
        collectionIntersection,
        collectionDifference,
        collectionSubsetOf,
        collectionSupersetOf,
        collectionEquivalentOf,
        makeArray,
        makeSet,
        makeBag,
        makePairList,
        makeTemporaryPairList,
        lengthOf,
        operatorString,
        operatorRegexp,
        ZuzuBinary,
        BinaryString: BinaryString2,
        Pair,
        PairList,
        withArrayMethods,
        ZuzuBag,
        isPairListLike,
        isWeakableValue,
        makeWeakValue,
        resolveWeakValue,
        retainValue,
        releaseValue,
        strongReferenceCount,
        retainCollectionValue,
        releaseCollectionValue,
        releaseCollectionValues,
        addSetValue,
        assignStrongValue,
        assignWeakValue,
        codePointStringCompare,
        stringSortComparator
      } = require_runtime_helpers();
      var taskRuntime2 = require_task();
      var textEncoder = new TextEncoder();
      var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
      var ZUZU_SKIP_BUILD = /* @__PURE__ */ Symbol.for("zuzu.skip_build");
      var runtimeVersion = (() => {
        if (typeof globalThis === "object" && globalThis !== null) {
          const globalVersion = globalThis.__ZUZU_RUNTIME_VERSION;
          if (typeof globalVersion === "string" && globalVersion.trim()) {
            return String(globalVersion);
          }
        }
        if (typeof process === "object" && process && process.versions) {
          try {
            const packageMetadata = require_package();
            const packageVersion = packageMetadata && packageMetadata.version;
            if (packageVersion) {
              return String(packageVersion);
            }
          } catch (err) {
            return "dev";
          }
        }
        return "dev";
      })();
      function defaultModuleSearchRoots(host, repoRoot, includePaths) {
        if (host.name === "browser") {
          return [
            host.join(repoRoot, "modules"),
            ...includePaths
          ];
        }
        const pathsModule = "./paths";
        return __require(pathsModule).defaultModuleSearchRoots({
          includePaths,
          packageRoot: repoRoot,
          initialCwd: host.cwd()
        });
      }
      function installHostCollectionMethods() {
        withArrayMethods();
        const define = (proto, name2, fn2) => {
          if (!Object.prototype.hasOwnProperty.call(proto, name2)) {
            const desc = /* @__PURE__ */ Object.create(null);
            desc.value = fn2;
            desc.enumerable = false;
            desc.configurable = true;
            desc.writable = true;
            Object.defineProperty(proto, name2, desc);
          }
        };
        define(Array.prototype, "push_weak", function _pushWeak(...values) {
          this.push(...values.map(makeWeakValue));
          return this;
        });
        define(Array.prototype, "unshift_weak", function _unshiftWeak(...values) {
          this.unshift(...values.map(makeWeakValue));
          return this;
        });
        define(Array.prototype, "set_weak", function _setWeak(index, value) {
          releaseCollectionValue(this, this[index]);
          this[index] = makeWeakValue(value);
          return this;
        });
        define(Set.prototype, "add_weak", function _addWeak(value) {
          this.add(makeWeakValue(value));
          return this;
        });
        define(Set.prototype, "push_weak", function _pushWeak(...values) {
          for (const value of values) {
            this.add(makeWeakValue(value));
          }
          return this;
        });
        define(Set.prototype, "copy", function _copy() {
          return makeSet(this);
        });
        define(ZuzuBag.prototype, "add_weak", function _addWeak(...values) {
          this.items.push(...values.map(makeWeakValue));
          return this;
        });
        define(ZuzuBag.prototype, "push_weak", function _pushWeak(...values) {
          return this.add_weak(...values);
        });
        define(PairList.prototype, "add_weak", function _addWeak(key, value) {
          this.list.push([String(key), makeWeakValue(value)]);
          return this;
        });
        define(PairList.prototype, "set_weak", function _setWeak(key, value) {
          return this.add_weak(key, value);
        });
        Object.defineProperty(ZuzuBag.prototype, "contains", {
          value: function _containsWeakAware(value) {
            const resolved = resolveWeakValue(value);
            return this.items.some((item) => resolveWeakValue(item) === resolved) ? 1 : 0;
          },
          enumerable: false,
          configurable: true,
          writable: true
        });
        Object.defineProperty(Set.prototype, "contains", {
          value: function _containsWeakAware(value) {
            const resolved = resolveWeakValue(value);
            for (const item of this) {
              if (resolveWeakValue(item) === resolved) {
                return 1;
              }
            }
            return 0;
          },
          enumerable: false,
          configurable: true,
          writable: true
        });
      }
      function createObjectFacade() {
        function ZuzuContextObject(value) {
          if (new.target) {
            return void 0;
          }
          return Object(value);
        }
        Object.setPrototypeOf(ZuzuContextObject, Object);
        Object.defineProperty(ZuzuContextObject, "prototype", {
          value: Object.prototype,
          enumerable: false,
          configurable: false,
          writable: false
        });
        return ZuzuContextObject;
      }
      function zuzuStringify(value) {
        value = resolveWeakValue(value);
        if (value == null) {
          return "";
        }
        if (typeof value === "boolean") {
          return value ? "1" : "0";
        }
        if (value instanceof RegExp) {
          return value.source;
        }
        if (value instanceof ZuzuBinary) {
          return value.to_String();
        }
        if (value && typeof value.to_String === "function") {
          return String(value.to_String());
        }
        if (value instanceof Error) {
          return value.message || value.name || String(value);
        }
        return String(value);
      }
      function zuzuOperatorString(value) {
        return operatorString(value);
      }
      function binaryFromLiteral(value) {
        const text = String(value ?? "");
        const bytes = [];
        for (let i = 0; i < text.length; i++) {
          bytes.push(text.charCodeAt(i) & 255);
        }
        return new BinaryString2(bytes);
      }
      function toBinaryValue(value) {
        value = resolveWeakValue(value);
        if (value instanceof ZuzuBinary) {
          return new BinaryString2(value);
        }
        if (typeof value === "string") {
          return new BinaryString2(textEncoder.encode(value));
        }
        throw new Error(`TypeException: expected String for to_binary, got ${zuzuTypeof(value)}`);
      }
      function toStringValue(value) {
        value = resolveWeakValue(value);
        if (typeof value === "string") {
          return value;
        }
        if (value instanceof ZuzuBinary) {
          try {
            return utf8Decoder.decode(value.bytes);
          } catch (err) {
            return Array.from(value.bytes, (byte) => String.fromCharCode(byte)).join("");
          }
        }
        throw new Error(`TypeException: expected BinaryString for to_string, got ${zuzuTypeof(value)}`);
      }
      function stringCompare(left, right, options = {}) {
        const l = options.insensitive ? zuzuOperatorString(left).toLowerCase() : zuzuOperatorString(left);
        const r = options.insensitive ? zuzuOperatorString(right).toLowerCase() : zuzuOperatorString(right);
        return codePointStringCompare(l, r);
      }
      function parseNumericString(value) {
        const text = String(value).trim();
        const radix = text.match(/^([+-]?)0([xX][0-9a-fA-F]+|[bB][01]+|[oO][0-7]+)$/);
        if (radix) {
          const base = "xX".includes(radix[2][0]) ? 16 : "bB".includes(radix[2][0]) ? 2 : 8;
          const magnitude = parseInt(radix[2].slice(1), base);
          return radix[1] === "-" ? -magnitude : magnitude;
        }
        const match = text.match(/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/);
        if (!match) {
          throw new Error(`TypeException: cannot coerce String to Number: ${JSON.stringify(String(value))}`);
        }
        const parsed = Number(text);
        if (Number.isNaN(parsed)) {
          throw new Error(`TypeException: cannot coerce String to Number: ${JSON.stringify(String(value))}`);
        }
        return parsed;
      }
      function zuzuToNumber(value) {
        value = resolveWeakValue(value);
        if (value == null) {
          return 0;
        }
        if (typeof value === "number" || Object.prototype.toString.call(value) === "[object Number]") {
          return Number(value);
        }
        if (typeof value === "boolean" || Object.prototype.toString.call(value) === "[object Boolean]") {
          return value.valueOf() ? 1 : 0;
        }
        if (typeof value === "string" || Object.prototype.toString.call(value) === "[object String]") {
          return parseNumericString(value);
        }
        if (typeof value === "function") {
          throw new Error(`TypeException: cannot coerce ${zuzuTypeof(value)} to Number`);
        }
        if (value && typeof value.to_Number === "function") {
          return zuzuToNumber(value.to_Number());
        }
        throw new Error(`TypeException: cannot coerce ${zuzuTypeof(value)} to Number`);
      }
      function zuzuTruthy(value) {
        value = resolveWeakValue(value);
        if (value == null) {
          return false;
        }
        if (value && typeof value.to_Boolean === "function") {
          return zuzuTruthy(value.to_Boolean());
        }
        if (value instanceof ZuzuBinary) {
          return value.byteLength() > 0;
        }
        if (typeof value === "boolean" || Object.prototype.toString.call(value) === "[object Boolean]") {
          return value.valueOf() === true;
        }
        if (typeof value === "number" || Object.prototype.toString.call(value) === "[object Number]") {
          return Number(value) !== 0;
        }
        if (typeof value === "string" || Object.prototype.toString.call(value) === "[object String]") {
          return String(value) !== "";
        }
        if (Array.isArray(value)) {
          return value.length > 0;
        }
        if (isPairListLike(value)) {
          return value.length() > 0;
        }
        if (value instanceof ZuzuBag) {
          return value.length() > 0;
        }
        if (isSetLike(value)) {
          return value.size > 0;
        }
        const ctorName = value && value.constructor && value.constructor.name;
        if (value && typeof value === "object" && (ctorName === "Object" || ctorName == null)) {
          return Object.keys(value).length > 0;
        }
        return Boolean(value);
      }
      function defaultOperator(leftInput, rightInput) {
        const left = resolveWeakValue(leftInput);
        const right = resolveWeakValue(rightInput);
        const leftType = zuzuTypeof(left);
        if (left != null && leftType !== "Dict" && !isPairListLike(left)) {
          throw new Error(
            `TypeException: default operator left operand expects Dict, PairList, or Null, got ${leftType}`
          );
        }
        if (zuzuTypeof(right) !== "Dict" && !isPairListLike(right)) {
          throw new Error(
            `TypeException: default operator right operand expects Dict or PairList, got ${zuzuTypeof(right)}`
          );
        }
        if (leftType === "Dict") {
          const result = {};
          for (const key of Object.keys(left)) {
            result[key] = left[key];
          }
          if (isPairListLike(right)) {
            for (const [key, value] of right.list) {
              if (!Object.prototype.hasOwnProperty.call(result, key)) {
                result[key] = value;
              }
            }
          } else {
            for (const key of Object.keys(right).sort()) {
              if (!Object.prototype.hasOwnProperty.call(result, key)) {
                result[key] = right[key];
              }
            }
          }
          return result;
        }
        const values = isPairListLike(left) ? left.list.map(([key, value]) => [key, value]) : [];
        const originalKeys = new Set(values.map(([key]) => key));
        if (isPairListLike(right)) {
          for (const [key, value] of right.list) {
            if (!originalKeys.has(key)) {
              values.push([key, value]);
            }
          }
        } else {
          for (const key of Object.keys(right).sort()) {
            if (!originalKeys.has(key)) {
              values.push([key, right[key]]);
            }
          }
        }
        return makePairList(values);
      }
      function isNumericComparable(value) {
        value = resolveWeakValue(value);
        if (value == null) {
          return true;
        }
        if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
          return true;
        }
        const tag = Object.prototype.toString.call(value);
        if (tag === "[object Number]" || tag === "[object String]" || tag === "[object Boolean]") {
          return true;
        }
        return Boolean(value && typeof value.to_Number === "function");
      }
      function numericEqual(left, right) {
        const leftNum = zuzuToNumber(left);
        const rightNum = zuzuToNumber(right);
        if (Object.is(leftNum, rightNum)) {
          return true;
        }
        if (Number.isInteger(leftNum) && Number.isInteger(rightNum)) {
          return false;
        }
        const scale = Math.max(1, Math.abs(leftNum), Math.abs(rightNum));
        return Math.abs(leftNum - rightNum) <= Number.EPSILON * 16 * scale;
      }
      function isExhaustedIteratorError(err) {
        if (!err) {
          return false;
        }
        const name2 = String(err.name || err.constructor && err.constructor.name || "");
        if (name2 === "ExhaustedException") {
          return true;
        }
        const message = String(err.message || "");
        if (/\bExhaustedException\b/.test(message)) {
          return true;
        }
        const stack = String(err.stack || "");
        return /\bExhaustedException\b/.test(stack);
      }
      function formatRuntimeError(err) {
        if (err && err.name === "SyntaxError" && typeof err.stack === "string" && err.stack.trim()) {
          return `${err.stack}
`;
        }
        if (err && err.name && err.message) {
          return `${err.name}: ${err.message}
`;
        }
        return `${String(err)}
`;
      }
      async function runSwitchAsync(value, comparator, cases, defaultBody) {
        const cmp = (left, right) => {
          switch (comparator) {
            case "eq":
              return stringCompare(left, right) === 0;
            case "eqi":
              return stringCompare(left, right, { insensitive: true }) === 0;
            case "ne":
              return stringCompare(left, right) !== 0;
            case "nei":
              return stringCompare(left, right, { insensitive: true }) !== 0;
            case "=":
              return numericEqual(zuzuToNumber(left), zuzuToNumber(right));
            case "==":
            default:
              return !!zuzuEqual(left, right);
          }
        };
        let runNext = false;
        for (const section of cases) {
          let matched = false;
          if (Array.isArray(section.tests)) {
            for (const test of section.tests) {
              if (zuzuTruthy(await taskRuntime2.awaitValue(test(value)))) {
                matched = true;
                break;
              }
            }
          } else {
            matched = section.values.some((item) => cmp(value, item));
          }
          if (matched || runNext) {
            const result = await taskRuntime2.awaitValue(section.body());
            runNext = result === true;
            if (!runNext && result && typeof result === "object" && result.__zuzu_return) {
              return result;
            }
            if (!runNext) {
              return null;
            }
          }
        }
        if (defaultBody) {
          const result = await taskRuntime2.awaitValue(defaultBody());
          if (result && typeof result === "object" && result.__zuzu_return) {
            return result;
          }
        }
        return null;
      }
      function concatValue(left, right) {
        left = resolveWeakValue(left);
        right = resolveWeakValue(right);
        if (left instanceof ZuzuBinary && right instanceof ZuzuBinary) {
          const merged = new Uint8Array(left.length + right.length);
          merged.set(left.bytes, 0);
          merged.set(right.bytes, left.length);
          return new BinaryString2(merged);
        }
        if (typeof left === "string" && typeof right === "string") {
          return left + right;
        }
        if (left instanceof ZuzuBinary && typeof right === "string") {
          if (!left.isAscii()) {
            throw new Error("TypeException: Cannot implicitly concatenate non-ASCII BinaryString with String");
          }
          return left.to_String() + right;
        }
        if (typeof left === "string" && right instanceof ZuzuBinary) {
          if (!right.isAscii()) {
            throw new Error("TypeException: Cannot implicitly concatenate non-ASCII BinaryString with String");
          }
          return left + right.to_String();
        }
        return zuzuOperatorString(left) + zuzuOperatorString(right);
      }
      function operatorLength(value) {
        value = resolveWeakValue(value);
        if (value instanceof ZuzuBinary) {
          return value.byteLength();
        }
        if (Array.isArray(value) || isPairListLike(value) || value instanceof ZuzuBag || isSetLike(value) || value && typeof value === "object" && value.constructor && value.constructor.name === "Object") {
          return lengthOf(value);
        }
        return [...zuzuOperatorString(value)].length;
      }
      function regexReplaceValue(current, pattern, replacement) {
        const source = zuzuOperatorString(current);
        const regex = operatorRegexp(pattern);
        return source.replace(regex, replacement);
      }
      function bitwiseBinaryPair(left, right, opName) {
        if (left.length !== right.length) {
          throw new Error("Exception: BinaryString bitwise operands must be equal length");
        }
        const out = new Uint8Array(left.length);
        for (let i = 0; i < left.length; i++) {
          const a = left.bytes[i];
          const b = right.bytes[i];
          if (opName === "and") {
            out[i] = a & b;
          } else if (opName === "or") {
            out[i] = a | b;
          } else {
            out[i] = a ^ b;
          }
        }
        return new BinaryString2(out);
      }
      function bitwiseAnd(left, right) {
        if (left instanceof ZuzuBinary && right instanceof ZuzuBinary) {
          return bitwiseBinaryPair(left, right, "and");
        }
        return (zuzuToNumber(left) >>> 0 & zuzuToNumber(right) >>> 0) >>> 0;
      }
      function bitwiseOr(left, right) {
        if (left instanceof ZuzuBinary && right instanceof ZuzuBinary) {
          return bitwiseBinaryPair(left, right, "or");
        }
        return (zuzuToNumber(left) >>> 0 | zuzuToNumber(right) >>> 0) >>> 0;
      }
      function bitwiseXor(left, right) {
        if (left instanceof ZuzuBinary && right instanceof ZuzuBinary) {
          return bitwiseBinaryPair(left, right, "xor");
        }
        return (zuzuToNumber(left) >>> 0 ^ zuzuToNumber(right) >>> 0) >>> 0;
      }
      function bitwiseNot(value) {
        value = resolveWeakValue(value);
        if (value instanceof ZuzuBinary) {
          const out = new Uint8Array(value.length);
          for (let i = 0; i < value.length; i++) {
            out[i] = ~value.bytes[i] & 255;
          }
          return new BinaryString2(out);
        }
        return ~(zuzuToNumber(value) >>> 0) >>> 0;
      }
      function shiftBitstream(bytes, count, left) {
        const len = bytes.length;
        const out = new Uint8Array(len);
        if (len === 0 || count >= len * 8) {
          return out;
        }
        const byteShift = Math.floor(count / 8);
        const bitShift = count % 8;
        for (let i = 0; i < len; i++) {
          let value;
          if (left) {
            const src = i + byteShift;
            const hi = src < len ? bytes[src] : 0;
            const lo = src + 1 < len ? bytes[src + 1] : 0;
            value = (hi << 8 | lo) << bitShift >> 8;
          } else {
            if (i < byteShift) {
              continue;
            }
            const lo = bytes[i - byteShift];
            const hi = i > byteShift ? bytes[i - byteShift - 1] : 0;
            value = (hi << 8 | lo) >> bitShift;
          }
          out[i] = value & 255;
        }
        return out;
      }
      function shiftValue(left, right, leftward) {
        left = resolveWeakValue(left);
        const count = Math.trunc(zuzuToNumber(right));
        if (!(count >= 0) || !Number.isFinite(count)) {
          throw new Error("Exception: shift count must be a non-negative integer");
        }
        if (left instanceof ZuzuBinary) {
          return new BinaryString2(shiftBitstream(left.bytes, count, leftward));
        }
        const value = Math.trunc(zuzuToNumber(left));
        const factor = Math.pow(2, count);
        return leftward ? value * factor : Math.floor(value / factor);
      }
      function zuzuComparableValue(value) {
        value = resolveWeakValue(value);
        if (typeof value === "function" && value.length === 0) {
          try {
            return value();
          } catch (_err) {
            return value;
          }
        }
        return value;
      }
      function zuzuEqual(left, right) {
        const a = zuzuComparableValue(left);
        const b = zuzuComparableValue(right);
        if (a === b) {
          return 1;
        }
        if (a == null || b == null) {
          return 0;
        }
        if (a instanceof ZuzuBinary && b instanceof ZuzuBinary) {
          if (a.bytes.length !== b.bytes.length) {
            return 0;
          }
          for (let i = 0; i < a.bytes.length; i++) {
            if (a.bytes[i] !== b.bytes[i]) {
              return 0;
            }
          }
          return 1;
        }
        if (Array.isArray(a) && Array.isArray(b)) {
          if (a.length !== b.length) {
            return 0;
          }
          for (let i = 0; i < a.length; i++) {
            if (!zuzuEqual(a[i], b[i])) {
              return 0;
            }
          }
          return 1;
        }
        if (isSetLike(a) && isSetLike(b)) {
          return collectionEquivalentOf(a, b) ? 1 : 0;
        }
        if (isBagLike(a) && isBagLike(b)) {
          return zuzuEqual(a.to_Array(), b.to_Array());
        }
        if (isPairListLike(a) && isPairListLike(b)) {
          if (a.list.length !== b.list.length) {
            return 0;
          }
          for (let i = 0; i < a.list.length; i++) {
            if (a.list[i][0] !== b.list[i][0]) {
              return 0;
            }
            if (!zuzuEqual(a.list[i][1], b.list[i][1])) {
              return 0;
            }
          }
          return 1;
        }
        if (isPlainObjectLike(a) && isPlainObjectLike(b)) {
          const keysA = Object.keys(a).sort();
          const keysB = Object.keys(b).sort();
          if (!zuzuEqual(keysA, keysB)) {
            return 0;
          }
          for (const key of keysA) {
            if (!zuzuEqual(a[key], b[key])) {
              return 0;
            }
          }
          return 1;
        }
        return 0;
      }
      function isSetLike(value) {
        return Object.prototype.toString.call(value) === "[object Set]";
      }
      function isBagLike(value) {
        return value instanceof ZuzuBag || value && value.constructor && value.constructor.name === "ZuzuBag";
      }
      function isPlainObjectLike(value) {
        return Object.prototype.toString.call(value) === "[object Object]" && !(value.constructor && value.constructor.__zuzu_class_name);
      }
      function isDictMethodReceiver(value) {
        return isPlainObjectLike(value) && !isPairListLike(value) && !isSetLike(value) && !isBagLike(value);
      }
      function normalizeDictKey(key) {
        key = resolveWeakValue(key);
        if (key == null) {
          return "";
        }
        if (typeof key === "string") {
          return key;
        }
        if (key instanceof ZuzuBinary) {
          return key.to_String();
        }
        if (key && typeof key.to_String === "function") {
          return String(key.to_String());
        }
        return String(key);
      }
      function arraySliceBounds(length, start, end = length) {
        let from = Number(start ?? 0);
        let to = Number(end ?? length);
        from = Number.isFinite(from) ? Math.trunc(from) : 0;
        to = Number.isFinite(to) ? Math.trunc(to) : length;
        if (from < 0) {
          from += length;
        }
        if (to < 0) {
          to += length;
        }
        from = Math.max(0, Math.min(length, from));
        to = Math.max(0, Math.min(length, to));
        return [Math.min(from, to), Math.max(from, to)];
      }
      function arrayMethodArity(name2, actual, min, max = min) {
        const count = actual - 1;
        if (count < min || count > max) {
          throw new Error(
            min === max ? `${name2} expects ${min} argument${min === 1 ? "" : "s"}` : `${name2} expects between ${min} and ${max} arguments`
          );
        }
      }
      function arrayIndex(length, idx) {
        let index = Number(idx);
        index = Number.isFinite(index) ? Math.trunc(index) : 0;
        if (index < 0) {
          index += length;
        }
        return index;
      }
      function shuffledArrayValues(self) {
        const out = self.slice();
        for (let idx = out.length - 1; idx > 0; idx--) {
          const swapIdx = Math.floor(Math.random() * (idx + 1));
          [out[idx], out[swapIdx]] = [out[swapIdx], out[idx]];
        }
        return out;
      }
      function arrayJoin(self, separator, fallback, hasFallback) {
        const sep = operatorString(separator);
        let fallbackString;
        const out = [];
        for (const value of self) {
          try {
            out.push(operatorString(value));
          } catch (err) {
            if (!hasFallback) {
              throw err;
            }
            if (typeof fallback === "function") {
              out.push(operatorString(fallback(value)));
            } else {
              if (fallbackString === void 0) {
                fallbackString = operatorString(fallback);
              }
              out.push(fallbackString);
            }
          }
        }
        return out.join(sep);
      }
      var ARRAY_METHODS = Object.freeze({
        append(self, ...values) {
          self.push(...values.map((value) => retainCollectionValue(self, value)));
          return self;
        },
        push(self, ...values) {
          return ARRAY_METHODS.append(self, ...values);
        },
        add(self, ...values) {
          return ARRAY_METHODS.append(self, ...values);
        },
        push_weak(self, ...values) {
          self.push(...values.map(makeWeakValue));
          return self;
        },
        pop(self) {
          return self.length ? self.pop() : null;
        },
        prepend(self, ...values) {
          self.unshift(...values.map((value) => retainCollectionValue(self, value)));
          return self;
        },
        unshift(self, ...values) {
          return ARRAY_METHODS.prepend(self, ...values);
        },
        unshift_weak(self, ...values) {
          self.unshift(...values.map(makeWeakValue));
          return self;
        },
        shift(self) {
          return self.length ? self.shift() : null;
        },
        length(self) {
          return self.length;
        },
        count(self) {
          return self.length;
        },
        empty(self) {
          return self.length === 0 ? 1 : 0;
        },
        is_empty(self) {
          return ARRAY_METHODS.empty(self);
        },
        copy(self) {
          return makeArray(self);
        },
        to_Array(self) {
          return makeArray(self);
        },
        get(self, idx, fallback = null) {
          arrayMethodArity("Array.get", arguments.length, 1, 2);
          const index = arrayIndex(self.length, idx);
          return index >= 0 && index < self.length ? self[index] : fallback;
        },
        set(self, idx, value) {
          arrayMethodArity("Array.set", arguments.length, 2);
          const index = arrayIndex(self.length, idx);
          if (index < 0) {
            throw new Error("Array index is out of range");
          }
          releaseCollectionValue(self, self[index]);
          self[index] = retainCollectionValue(self, value);
          return self;
        },
        set_weak(self, idx, value) {
          arrayMethodArity("Array.set_weak", arguments.length, 2);
          const index = arrayIndex(self.length, idx);
          if (index < 0) {
            throw new Error("Array index is out of range");
          }
          releaseCollectionValue(self, self[index]);
          self[index] = makeWeakValue(value);
          return self;
        },
        clear(self) {
          releaseCollectionValues(self);
          self.splice(0, self.length);
          return self;
        },
        join(self, separator, fallback) {
          return arrayJoin(self, separator, fallback, arguments.length > 2);
        },
        slice(self, start, end) {
          const [from, to] = arraySliceBounds(self.length, start, end);
          return makeArray(self.slice(from, to));
        },
        head(self, n = 1) {
          arrayMethodArity("Array.head", arguments.length, 0, 1);
          return makeArray(self.slice(0, Math.max(0, Number(n) || 0)));
        },
        tail(self, n = 1) {
          arrayMethodArity("Array.tail", arguments.length, 0, 1);
          const count = Math.max(0, Number(n) || 0);
          return makeArray(count === 0 ? [] : self.slice(-count));
        },
        to_Set(self) {
          return makeSet(self);
        },
        to_Bag(self) {
          return makeBag(self);
        },
        to_Iterator(self) {
          return self[Symbol.iterator]();
        },
        sort(self, fn2) {
          const out = self.slice();
          out.sort((left, right) => Number(fn2(left, right)) || 0);
          return makeArray(out);
        },
        sortstr(self) {
          return makeArray(self.slice().sort(stringSortComparator));
        },
        sortnum(self) {
          return makeArray(
            self.map((item) => Number(item)).sort((a, b) => a - b)
          );
        },
        reverse(self) {
          return makeArray(self.slice().reverse());
        },
        sum(self) {
          return self.reduce((a, b) => Number(a) + Number(b), 0);
        },
        product(self) {
          return self.reduce((a, b) => Number(a) * Number(b), 1);
        },
        shuffle(self) {
          arrayMethodArity("Array.shuffle", arguments.length, 0);
          return makeArray(shuffledArrayValues(self));
        },
        sample(self, n = 1) {
          arrayMethodArity("Array.sample", arguments.length, 0, 1);
          return makeArray(
            shuffledArrayValues(self).slice(0, Math.max(0, Number(n) || 0))
          );
        },
        contains(self, value) {
          return self.includes(value) ? 1 : 0;
        },
        map(self, fn2) {
          arrayMethodArity("Array.map", arguments.length, 1);
          return makeArray(self.map((value) => fn2(value)));
        },
        grep(self, fn2) {
          arrayMethodArity("Array.grep", arguments.length, 1);
          return makeArray(self.filter((value) => fn2(value)));
        },
        any(self, fn2) {
          arrayMethodArity("Array.any", arguments.length, 1);
          return self.some((value) => fn2(value)) ? 1 : 0;
        },
        all(self, fn2) {
          arrayMethodArity("Array.all", arguments.length, 1);
          return self.every((value) => fn2(value)) ? 1 : 0;
        },
        first(self, fn2) {
          arrayMethodArity("Array.first", arguments.length, 1);
          for (const value of self) {
            if (fn2(value)) {
              return value;
            }
          }
          return null;
        },
        remove(self, fn2) {
          for (let idx = self.length - 1; idx >= 0; idx--) {
            if (fn2(self[idx])) {
              releaseCollectionValue(self, self[idx]);
              self.splice(idx, 1);
            }
          }
          return self;
        },
        first_index(self, fn2) {
          for (let idx = 0; idx < self.length; idx++) {
            if (fn2(self[idx])) {
              return idx;
            }
          }
          return -1;
        },
        for_each_value(self, fn2) {
          for (const value of self) {
            fn2(value);
          }
          return self;
        },
        reduce(self, fn2) {
          if (self.length === 0) {
            return null;
          }
          let acc = self[0];
          for (let idx = 1; idx < self.length; idx++) {
            acc = fn2(acc, self[idx]);
          }
          return acc;
        },
        reductions(self, fn2) {
          if (self.length === 0) {
            return makeArray([]);
          }
          const out = [self[0]];
          for (let idx = 1; idx < self.length; idx++) {
            out.push(fn2(out[out.length - 1], self[idx]));
          }
          return makeArray(out);
        }
      });
      var ARRAY_ZERO_ARG_METHODS = /* @__PURE__ */ new Set([
        "copy",
        "count",
        "empty",
        "is_empty",
        "length",
        "pop",
        "reverse",
        "shift",
        "shuffle",
        "sortnum",
        "sortstr",
        "to_Array",
        "to_Bag",
        "to_Iterator",
        "to_Set"
      ]);
      function getArrayMethod(object, property) {
        if (typeof property === "symbol") {
          return null;
        }
        const name2 = String(property);
        if (!Array.isArray(object) || !Object.prototype.hasOwnProperty.call(ARRAY_METHODS, name2)) {
          return null;
        }
        return function zuzuArrayMethod(...args) {
          return ARRAY_METHODS[name2](object, ...args);
        };
      }
      var SET_METHODS = Object.freeze({
        add_weak(self, ...values) {
          for (const value of values) {
            self.add(makeWeakValue(value));
          }
          return self;
        },
        push_weak(self, ...values) {
          return SET_METHODS.add_weak(self, ...values);
        },
        clear(self) {
          releaseCollectionValues(self);
          Set.prototype.clear.call(self);
          return self;
        }
      });
      var SET_ZERO_ARG_METHODS = /* @__PURE__ */ new Set(["clear"]);
      function getSetMethod(object, property) {
        if (typeof property === "symbol") {
          return null;
        }
        const name2 = String(property);
        if (!isSetLike(object) || !Object.prototype.hasOwnProperty.call(SET_METHODS, name2)) {
          return null;
        }
        return function zuzuSetMethod(...args) {
          return SET_METHODS[name2](object, ...args);
        };
      }
      function dictSortedKeys(self) {
        return isDictMethodReceiver(self) ? Object.keys(self).sort() : [];
      }
      var DICT_METHODS = Object.freeze({
        length(self) {
          return isDictMethodReceiver(self) ? Object.keys(self).length : 0;
        },
        keys(self) {
          return makeSet(dictSortedKeys(self));
        },
        values(self) {
          if (!isDictMethodReceiver(self)) {
            return makeBag([]);
          }
          return makeBag(dictSortedKeys(self).map((key) => resolveWeakValue(self[key])));
        },
        copy(self) {
          if (!isDictMethodReceiver(self)) {
            return {};
          }
          const out = {};
          for (const key of Object.keys(self)) {
            out[key] = retainCollectionValue(out, self[key]);
          }
          return out;
        },
        enumerate(self) {
          if (!isDictMethodReceiver(self)) {
            return makeBag([]);
          }
          return makeBag(dictSortedKeys(self).map(
            (key) => new Pair({ pair: [key, resolveWeakValue(self[key])] })
          ));
        },
        has(self, key) {
          return isDictMethodReceiver(self) && Object.prototype.hasOwnProperty.call(self, normalizeDictKey(key)) ? 1 : 0;
        },
        contains(self, key) {
          return DICT_METHODS.has(self, key);
        },
        exists(self, key) {
          return DICT_METHODS.has(self, key);
        },
        defined(self, key) {
          const normalized = normalizeDictKey(key);
          return isDictMethodReceiver(self) && resolveWeakValue(self[normalized]) != null ? 1 : 0;
        },
        get(self, key, fallback = null) {
          const normalized = normalizeDictKey(key);
          return DICT_METHODS.has(self, normalized) ? resolveWeakValue(self[normalized]) : fallback;
        },
        add(self, key, value) {
          if (!isDictMethodReceiver(self) || key instanceof Pair) {
            return self;
          }
          const normalized = normalizeDictKey(key);
          releaseCollectionValue(self, self[normalized]);
          self[normalized] = retainCollectionValue(self, value);
          return self;
        },
        set(self, key, value) {
          return DICT_METHODS.add(self, key, value);
        },
        add_weak(self, key, value) {
          if (!isDictMethodReceiver(self) || key instanceof Pair) {
            return self;
          }
          const normalized = normalizeDictKey(key);
          releaseCollectionValue(self, self[normalized]);
          self[normalized] = makeWeakValue(value);
          return self;
        },
        set_weak(self, key, value) {
          return DICT_METHODS.add_weak(self, key, value);
        },
        kv(self) {
          if (!isDictMethodReceiver(self)) {
            return [];
          }
          const out = [];
          for (const key of dictSortedKeys(self)) {
            out.push(key, resolveWeakValue(self[key]));
          }
          return out;
        },
        sorted_keys(self) {
          return dictSortedKeys(self);
        },
        remove(self, key) {
          if (!isDictMethodReceiver(self)) {
            return self;
          }
          if (typeof key === "function") {
            for (const [k, v] of Object.entries(self)) {
              if (key(new Pair({ pair: [k, v] }))) {
                releaseCollectionValue(self, self[k]);
                delete self[k];
              }
            }
            return self;
          }
          if (key instanceof Pair) {
            return self;
          }
          const normalized = normalizeDictKey(key);
          releaseCollectionValue(self, self[normalized]);
          delete self[normalized];
          return self;
        },
        count(self) {
          return DICT_METHODS.length(self);
        },
        empty(self) {
          return DICT_METHODS.length(self) === 0 ? 1 : 0;
        },
        is_empty(self) {
          return DICT_METHODS.empty(self);
        },
        to_Array(self) {
          if (!isDictMethodReceiver(self)) {
            return [];
          }
          return makeArray(dictSortedKeys(self).map(
            (key) => new Pair({ pair: [key, resolveWeakValue(self[key])] })
          ));
        },
        to_Iterator(self) {
          return dictSortedKeys(self)[Symbol.iterator]();
        },
        for_each_key(self, fn2) {
          for (const key of dictSortedKeys(self)) {
            fn2(key);
          }
          return self;
        },
        for_each_value(self, fn2) {
          for (const key of dictSortedKeys(self)) {
            fn2(resolveWeakValue(self[key]));
          }
          return self;
        },
        for_each_pair(self, fn2) {
          for (const key of dictSortedKeys(self)) {
            fn2(new Pair({ pair: [key, resolveWeakValue(self[key])] }));
          }
          return self;
        },
        clear(self) {
          if (isDictMethodReceiver(self)) {
            for (const key of Object.keys(self)) {
              releaseCollectionValue(self, self[key]);
              delete self[key];
            }
          }
          return self;
        }
      });
      var DICT_ZERO_ARG_METHODS = /* @__PURE__ */ new Set([
        "clear",
        "copy",
        "count",
        "empty",
        "enumerate",
        "is_empty",
        "keys",
        "kv",
        "length",
        "sorted_keys",
        "to_Array",
        "to_Iterator",
        "values"
      ]);
      function getDictMethod(object, property) {
        if (typeof property === "symbol") {
          return null;
        }
        const name2 = String(property);
        for (let proto = Object.getPrototypeOf(object); proto; proto = Object.getPrototypeOf(proto)) {
          const descriptor = Object.getOwnPropertyDescriptor(proto, name2);
          if (descriptor && typeof descriptor.value === "function") {
            return null;
          }
        }
        if (!isDictMethodReceiver(object) || Object.prototype.hasOwnProperty.call(object, name2) || !Object.prototype.hasOwnProperty.call(DICT_METHODS, name2)) {
          return null;
        }
        return function zuzuDictMethod(...args) {
          return DICT_METHODS[name2](object, ...args);
        };
      }
      var ZuzuMethod = class {
        constructor(name2, fn2) {
          this.name = String(name2 || "");
          this.fn = fn2;
        }
        invoke(self, args = []) {
          return this.fn.apply(self, args);
        }
        to_String() {
          return this.name;
        }
      };
      function zuzuBoundMethod(receiver, name2, fn2) {
        const methodName = String(name2 || "");
        const bound = function __zuzu_bound_method(...args) {
          return fn2.apply(receiver, args);
        };
        Object.defineProperty(bound, "__zuzu_method", {
          value: true,
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(bound, "__zuzu_bound_receiver", {
          value: receiver,
          enumerable: false,
          configurable: true
        });
        Object.defineProperty(bound, "__zuzu_bound_method_name", {
          value: methodName,
          enumerable: false,
          configurable: true
        });
        bound.invoke = function invoke(self, args = []) {
          return fn2.apply(self, args);
        };
        bound.to_String = function to_String() {
          return methodName;
        };
        return bound;
      }
      function zuzuTypeof(value) {
        value = resolveWeakValue(value);
        if (value == null) {
          return "Null";
        }
        if (value && value.__zuzu_method) {
          return "Method";
        }
        if (value instanceof ZuzuMethod) {
          return "Method";
        }
        if (isPairListLike(value)) {
          return "PairList";
        }
        if (value && (typeof value === "object" || typeof value === "function") && typeof value.__zuzu_type_name === "string") {
          return value.__zuzu_type_name;
        }
        if (isBagLike(value)) {
          return "Bag";
        }
        if (isSetLike(value)) {
          return "Set";
        }
        if (Array.isArray(value)) {
          return "Array";
        }
        if (value instanceof Pair) {
          return "Pair";
        }
        if (value instanceof RegExp) {
          return "Regexp";
        }
        if (Object.prototype.toString.call(value) === "[object RegExp]") {
          return "Regexp";
        }
        if (typeof value === "boolean") {
          return "Boolean";
        }
        if (typeof value === "number") {
          return "Number";
        }
        if (typeof value === "string") {
          return "String";
        }
        if (value instanceof ZuzuBinary) {
          return "BinaryString";
        }
        if (typeof value === "function") {
          const source = Function.prototype.toString.call(value);
          if (/^\s*class\b/.test(source)) {
            return "Class";
          }
          return "Function";
        }
        if (value && value.constructor) {
          const ctorName = value.constructor.name || "Object";
          if (ctorName === "Object") {
            return "Dict";
          }
          if (ctorName === "Error") {
            return "Exception";
          }
          return ctorName;
        }
        return "Object";
      }
      function zuzuInstanceof(value, klass) {
        value = resolveWeakValue(value);
        klass = resolveWeakValue(klass);
        if (klass == null) {
          return value == null ? 1 : 0;
        }
        const klassName = typeof klass === "function" && klass.name ? klass.name : "";
        if (klassName === "Any") {
          return 1;
        }
        if (klassName === "Null") {
          return value == null ? 1 : 0;
        }
        if (klassName === "Boolean" || klass === Boolean) {
          return typeof value === "boolean" || Object.prototype.toString.call(value) === "[object Boolean]" ? 1 : 0;
        }
        if (klassName === "Number" || klass === Number) {
          return typeof value === "number" || Object.prototype.toString.call(value) === "[object Number]" ? 1 : 0;
        }
        if (klassName === "String" || klass === String) {
          return typeof value === "string" || Object.prototype.toString.call(value) === "[object String]" ? 1 : 0;
        }
        if (klassName === "Array" || klass === Array) {
          return Array.isArray(value) ? 1 : 0;
        }
        if (klassName === "BinaryString") {
          return value instanceof ZuzuBinary ? 1 : 0;
        }
        if (klassName === "Function" || klass === Function) {
          return typeof value === "function" ? 1 : 0;
        }
        if (klassName === "Exception") {
          if (value == null) {
            return 0;
          }
          if (value instanceof Error) {
            return 1;
          }
          const valueName = String(
            value.name || value.constructor && value.constructor.name || ""
          );
          return [
            "Exception",
            "TypeException",
            "ExhaustedException",
            "CancelledException",
            "TimeoutException",
            "ChannelClosedException"
          ].includes(valueName) ? 1 : 0;
        }
        if (klassName === "TypeException") {
          if (value == null) {
            return 0;
          }
          const valueName = String(
            value.name || value.constructor && value.constructor.name || ""
          );
          return valueName === "TypeException" ? 1 : 0;
        }
        if (klassName === "ExhaustedException") {
          if (value == null) {
            return 0;
          }
          const valueName = String(
            value.name || value.constructor && value.constructor.name || ""
          );
          return valueName === "ExhaustedException" ? 1 : 0;
        }
        if ([
          "CancelledException",
          "TimeoutException",
          "ChannelClosedException"
        ].includes(klassName)) {
          if (value == null) {
            return 0;
          }
          const valueName = String(
            value.name || value.constructor && value.constructor.name || ""
          );
          return valueName === klassName ? 1 : 0;
        }
        if (klassName === "Collection") {
          return Array.isArray(value) || isSetLike(value) || isBagLike(value) || zuzuTypeof(value) === "Dict" ? 1 : 0;
        }
        if (klassName === "Dict") {
          return zuzuTypeof(value) === "Dict" ? 1 : 0;
        }
        if (klassName === "Set") {
          return isSetLike(value) ? 1 : 0;
        }
        if (klassName === "Bag") {
          return isBagLike(value) ? 1 : 0;
        }
        if (klassName === "Class") {
          return typeof value === "function" ? 1 : 0;
        }
        if (klassName === "Object" || klass === Object) {
          return value !== null && typeof value === "object" ? 1 : 0;
        }
        try {
          return value instanceof klass ? 1 : 0;
        } catch (_err) {
          return 0;
        }
      }
      function isNativeErrorConstructorName(name2) {
        return [
          "Error",
          "EvalError",
          "RangeError",
          "ReferenceError",
          "SyntaxError",
          "TypeError",
          "URIError"
        ].includes(String(name2 || ""));
      }
      function zuzuTrait(name2, methods, source = null, captures = {}) {
        const trait = {
          __zuzu_trait_name: String(name2 || ""),
          __zuzu_trait_methods: methods || {}
        };
        if (source != null) {
          Object.defineProperty(trait, "__zuzu_marshal_meta", {
            value: {
              kind: "trait",
              name: String(name2 || ""),
              source: String(source),
              captures: captures || {}
            },
            enumerable: false,
            configurable: true,
            writable: true
          });
        }
        return trait;
      }
      var perObjectTraitClassCache = /* @__PURE__ */ new WeakMap();
      function isZuzuIdentifierName(name2) {
        return /^[A-Za-z_][A-Za-z0-9_]*$/u.test(String(name2 || ""));
      }
      function zuzuClassWithTraits(base, traits) {
        if (typeof base !== "function") {
          throw new Error(`TypeException: new with traits expects Class, got ${zuzuTypeof(base)}`);
        }
        const traitList = Array.isArray(traits) ? traits : [];
        let node = perObjectTraitClassCache.get(base);
        if (!node) {
          node = /* @__PURE__ */ new WeakMap();
          perObjectTraitClassCache.set(base, node);
        }
        for (const trait of traitList) {
          if (!trait || !trait.__zuzu_trait_methods) {
            throw new Error(`TypeException: new with traits expects Trait, got ${zuzuTypeof(trait)}`);
          }
          let next = node.get(trait);
          if (!next) {
            next = /* @__PURE__ */ new WeakMap();
            node.set(trait, next);
          }
          node = next;
        }
        if (node.__zuzu_class) {
          return node.__zuzu_class;
        }
        const rawName = base.__zuzu_class_name || base.name || "Object";
        const name2 = isZuzuIdentifierName(rawName) ? rawName : "__zuzu_per_object_class";
        const captures = { __zuzu_per_object_base: base };
        const traitNames = traitList.map((trait, index) => {
          const captureName = `__zuzu_per_object_trait_${index}`;
          captures[captureName] = trait;
          return captureName;
        });
        const source = `class ${name2} extends __zuzu_per_object_base with ${traitNames.join(", ")};`;
        const klass = defineZuzuClass(rawName, base, {
          marshalSource: source,
          marshalCaptures: captures,
          traits: traitList,
          fields: [],
          methods: {},
          statics: {},
          nested: {}
        });
        Object.defineProperty(node, "__zuzu_class", {
          value: klass,
          enumerable: false,
          configurable: true,
          writable: true
        });
        return klass;
      }
      function zuzuApplyTraits(klass, traits) {
        if (!klass || !klass.prototype || !Array.isArray(traits)) {
          return klass;
        }
        if (!Object.prototype.hasOwnProperty.call(klass, "__zuzu_traits")) {
          const desc = /* @__PURE__ */ Object.create(null);
          desc.value = /* @__PURE__ */ new Set();
          desc.enumerable = false;
          desc.configurable = true;
          desc.writable = true;
          Object.defineProperty(klass, "__zuzu_traits", desc);
        }
        for (const trait of traits) {
          if (!trait || !trait.__zuzu_trait_methods) {
            continue;
          }
          klass.__zuzu_traits.add(trait.__zuzu_trait_name || "");
          for (const [name2, fn2] of Object.entries(trait.__zuzu_trait_methods)) {
            if (typeof fn2 !== "function") {
              continue;
            }
            if (Object.prototype.hasOwnProperty.call(klass.prototype, name2) && typeof klass.prototype[name2] === "function") {
              klass.prototype[`__zuzu_trait_super__${name2}`] = fn2;
            } else {
              klass.prototype[name2] = fn2;
            }
          }
        }
        return klass;
      }
      function zuzuDoes(value, trait) {
        value = resolveWeakValue(value);
        if (value == null || !trait) {
          return 0;
        }
        const name2 = trait.__zuzu_trait_name || trait.name || String(trait);
        let ctor = value.constructor;
        while (ctor) {
          if (ctor.__zuzu_traits instanceof Set && ctor.__zuzu_traits.has(name2)) {
            return 1;
          }
          ctor = Object.getPrototypeOf(ctor);
        }
        return 0;
      }
      function zuzuStoreField(object, field, value) {
        const stored = field.isWeakStorage ? makeWeakValue(value) : retainValue(value);
        releaseValue(object[field.name]);
        object[field.name] = stored;
        return stored;
      }
      function defineZuzuClass(name2, base, spec = {}) {
        const parent = typeof base === "function" ? base : Object;
        const fields = Array.isArray(spec.fields) ? spec.fields : [];
        const traits = Array.isArray(spec.traits) ? spec.traits : [];
        const methods = spec.methods && typeof spec.methods === "object" ? spec.methods : {};
        const statics = spec.statics && typeof spec.statics === "object" ? spec.statics : {};
        const nested = spec.nested && typeof spec.nested === "object" ? spec.nested : {};
        const ctor = {
          [name2]: class extends parent {
            constructor(...args) {
              const skipBuild = args[0] === ZUZU_SKIP_BUILD;
              const ctorArgs = skipBuild ? args.slice(1) : args;
              const superArgs = parent.__zuzu_class_name ? skipBuild ? args : [ZUZU_SKIP_BUILD, ...ctorArgs] : ctorArgs;
              super(...superArgs);
              if (this instanceof Error) {
                this.name = name2;
              }
              for (const field of fields) {
                let value = null;
                if (field.defaultValue && typeof field.defaultValue === "function") {
                  value = field.defaultValue.call(this);
                }
                zuzuStoreField(this, field, value);
              }
              let named = null;
              const lastArg = ctorArgs[ctorArgs.length - 1];
              if (ctorArgs.length === 1 && isPairListLike(ctorArgs[0])) {
                named = ctorArgs[0];
              } else if (ctorArgs.length === 1 && ctorArgs[0] && typeof ctorArgs[0] === "object" && !Array.isArray(ctorArgs[0])) {
                named = ctorArgs[0];
              } else if (ctorArgs.length > 1 && isPairListLike(lastArg)) {
                named = lastArg;
              } else if (ctorArgs.length > 1 && lastArg && typeof lastArg === "object" && !Array.isArray(lastArg)) {
                named = lastArg;
              }
              const releaseTemporaryNamed = !skipBuild && isPairListLike(named) && named.__zuzu_temporary_call_args === true;
              try {
                if (named) {
                  for (const field of fields) {
                    const incoming = isPairListLike(named) ? named.get(field.name, resolveWeakValue(this[field.name])) : Object.prototype.hasOwnProperty.call(named, field.name) ? named[field.name] : resolveWeakValue(this[field.name]);
                    if (field.typeName && incoming != null && !zuzuTypeMatches(incoming, field.typeName)) {
                      throw new Error(`TypeException: field '${field.name}' must be ${field.typeName}, got ${zuzuTypeof(incoming)}`);
                    }
                    zuzuStoreField(this, field, incoming);
                  }
                }
                for (const [nestedName, nestedClass] of Object.entries(nested)) {
                  this[nestedName] = nestedClass;
                }
                if (!skipBuild && typeof this.__build__ === "function") {
                  this.__build__();
                }
              } finally {
                if (releaseTemporaryNamed) {
                  releaseCollectionValues(named);
                }
              }
            }
          }
        }[name2];
        for (const field of fields) {
          if (Array.isArray(field.accessors)) {
            if (field.accessors.includes("get") && typeof ctor.prototype[`get_${field.name}`] !== "function") {
              ctor.prototype[`get_${field.name}`] = function _get_field() {
                return resolveWeakValue(this[field.name]);
              };
            }
            if (field.accessors.includes("set") && typeof ctor.prototype[`set_${field.name}`] !== "function") {
              ctor.prototype[`set_${field.name}`] = function _set_field(value) {
                if (field.typeName && value != null && !zuzuTypeMatches(value, field.typeName)) {
                  throw new Error(`TypeException: field '${field.name}' must be ${field.typeName}, got ${zuzuTypeof(value)}`);
                }
                zuzuStoreField(this, field, value);
                return this;
              };
            }
            if (field.accessors.includes("clear") && typeof ctor.prototype[`clear_${field.name}`] !== "function") {
              ctor.prototype[`clear_${field.name}`] = function _clear_field() {
                zuzuStoreField(this, field, null);
                return this;
              };
            }
            if (field.accessors.includes("has") && typeof ctor.prototype[`has_${field.name}`] !== "function") {
              ctor.prototype[`has_${field.name}`] = function _has_field() {
                return resolveWeakValue(this[field.name]) != null ? 1 : 0;
              };
            }
          }
        }
        for (const [methodName, fn2] of Object.entries(methods)) {
          ctor.prototype[methodName] = fn2;
        }
        for (const [methodName, fn2] of Object.entries(statics)) {
          ctor[methodName] = fn2;
        }
        for (const [nestedName, nestedClass] of Object.entries(nested)) {
          ctor[nestedName] = nestedClass;
        }
        zuzuApplyTraits(ctor, traits);
        Object.defineProperty(ctor, "__zuzu_class_name", {
          value: name2,
          enumerable: false,
          configurable: true,
          writable: true
        });
        Object.defineProperty(ctor, "__zuzu_class_spec", {
          value: {
            fields: fields.map((field) => ({ ...field })),
            traits: traits.slice(),
            methods: { ...methods },
            statics: { ...statics },
            nested: { ...nested }
          },
          enumerable: false,
          configurable: true,
          writable: true
        });
        if (typeof spec.marshalSource === "string") {
          Object.defineProperty(ctor, "__zuzu_marshal_meta", {
            value: {
              kind: "class",
              name: name2,
              source: spec.marshalSource,
              captures: spec.marshalCaptures || {}
            },
            enumerable: false,
            configurable: true,
            writable: true
          });
        }
        return ctor;
      }
      function zuzuGetMember(object, property) {
        object = resolveWeakValue(object);
        if (object == null) {
          return null;
        }
        if (property !== "length") {
          const arrayMethod = getArrayMethod(object, property);
          if (arrayMethod && ARRAY_ZERO_ARG_METHODS.has(String(property))) {
            return arrayMethod();
          }
          if (arrayMethod) {
            return arrayMethod;
          }
        }
        const setMethod = getSetMethod(object, property);
        if (setMethod && SET_ZERO_ARG_METHODS.has(String(property))) {
          return setMethod();
        }
        if (setMethod) {
          return setMethod;
        }
        const value = resolveWeakValue(object[property]);
        if (typeof value === "function" && value.length === 0 && !value.__zuzu_marshal_meta) {
          return value.call(object);
        }
        const dictMethod = getDictMethod(object, property);
        if (dictMethod && DICT_ZERO_ARG_METHODS.has(String(property))) {
          return dictMethod();
        }
        if (dictMethod) {
          return dictMethod;
        }
        return resolveWeakValue(value);
      }
      function zuzuResolveBraceKey(_object, literalProperty, _getDynamicProperty) {
        const literal = String(literalProperty || "");
        return literal;
      }
      function zuzuGetBraceMember(object, literalProperty, getDynamicProperty) {
        object = resolveWeakValue(object);
        if (object == null) {
          return null;
        }
        return zuzuGetIndex(object, zuzuResolveBraceKey(object, literalProperty, getDynamicProperty));
      }
      function zuzuCallMember(object, property, ...args) {
        object = resolveWeakValue(object);
        if (object == null) {
          throw new TypeError(`Cannot call member ${String(property)} of null`);
        }
        if (property instanceof ZuzuMethod || property && property.__zuzu_method) {
          return property.invoke(object, args);
        }
        const arrayMethod = getArrayMethod(object, property);
        if (arrayMethod) {
          return arrayMethod(...args);
        }
        const setMethod = getSetMethod(object, property);
        if (setMethod) {
          return setMethod(...args);
        }
        const dictMethod = getDictMethod(object, property);
        if (dictMethod) {
          return dictMethod(...args);
        }
        const value = resolveWeakValue(object[property]);
        if (typeof value === "function") {
          return value.apply(object, args);
        }
        let proto = Object.getPrototypeOf(object);
        while (proto) {
          const descriptor = Object.getOwnPropertyDescriptor(proto, property);
          if (descriptor && typeof descriptor.value === "function") {
            return descriptor.value.apply(object, args);
          }
          proto = Object.getPrototypeOf(proto);
        }
        throw new TypeError(`${String(property)} is not a function`);
      }
      function zuzuMaybeDemolish(value, preserved = null) {
        const original = value;
        value = resolveWeakValue(value);
        const shouldDemolish = value && value !== resolveWeakValue(preserved) && typeof value.__demolish__ === "function";
        releaseValue(original, {
          preserveCollectionValues: value === resolveWeakValue(preserved),
          suppressDemolish: true
        });
        if (shouldDemolish && strongReferenceCount(value) === 0) {
          return value.__demolish__();
        }
        return null;
      }
      function zuzuCan(value, methodName) {
        value = resolveWeakValue(value);
        if (value == null) {
          return 0;
        }
        const key = String(methodName || "");
        if (getArrayMethod(value, key)) {
          return 1;
        }
        if (getSetMethod(value, key)) {
          return 1;
        }
        if (getDictMethod(value, key)) {
          return 1;
        }
        if (typeof value[key] === "function") {
          return 1;
        }
        let proto = Object.getPrototypeOf(value);
        while (proto) {
          const descriptor = Object.getOwnPropertyDescriptor(proto, key);
          if (descriptor && typeof descriptor.value === "function") {
            return 1;
          }
          proto = Object.getPrototypeOf(proto);
        }
        return 0;
      }
      function zuzuSuperCall(self, klass, methodName, args = []) {
        const method = String(methodName || "");
        const argv = Array.isArray(args) ? args : [];
        if (klass && self && typeof self[`__zuzu_trait_super__${method}`] === "function") {
          return self[`__zuzu_trait_super__${method}`].apply(self, argv);
        }
        if (!klass && self && self.constructor) {
          klass = self.constructor;
        }
        if (klass && klass.prototype) {
          const parentProto = Object.getPrototypeOf(klass.prototype);
          if (parentProto && typeof parentProto[method] === "function") {
            return parentProto[method].apply(self, argv);
          }
        }
        return null;
      }
      function zuzuSuperStaticCall(klass, methodName, args = []) {
        const method = String(methodName || "");
        const argv = Array.isArray(args) ? args : [];
        if (!klass) {
          return null;
        }
        const parentClass = Object.getPrototypeOf(klass);
        if (parentClass && typeof parentClass[method] === "function") {
          return parentClass[method].apply(klass, argv);
        }
        return null;
      }
      function zuzuSuperDispatch(isStatic, self, klass, methodName, args = []) {
        return isStatic ? zuzuSuperStaticCall(klass, methodName, args) : zuzuSuperCall(self, klass, methodName, args);
      }
      function refIndex(target, index) {
        target = resolveWeakValue(target);
        return function refValue(maybeValue) {
          if (arguments.length === 0) {
            if (target instanceof ZuzuBinary) {
              return target.at(index);
            }
            return resolveWeakValue(target[index]);
          }
          if (target instanceof ZuzuBinary) {
            throw new Error("Exception: BinaryString index assignment is not supported");
          }
          target[index] = maybeValue;
          return maybeValue;
        };
      }
      function zuzuGetIndex(target, index) {
        target = resolveWeakValue(target);
        if (target == null) {
          return null;
        }
        const key = String(index);
        if (typeof target === "function" && target.prototype) {
          if (typeof target.prototype[key] === "function") {
            return new ZuzuMethod(key, target.prototype[key]);
          }
        }
        if (target instanceof ZuzuBinary) {
          return target.at(index);
        }
        if (isPairListLike(target)) {
          return resolveWeakValue(target.get(index, null));
        }
        if (typeof target === "string" || Array.isArray(target)) {
          let resolved = Number(index);
          if (Number.isFinite(resolved)) {
            const indexed = typeof target === "string" ? [...target] : target;
            if (resolved < 0) {
              resolved = indexed.length + resolved;
            }
            return resolveWeakValue(indexed[resolved] ?? null);
          }
        }
        if (target && typeof target === "object" && target.constructor && typeof target.constructor.__zuzu_class_name === "string" && !Object.prototype.hasOwnProperty.call(target, key) && typeof target[key] === "function") {
          return zuzuBoundMethod(target, key, target[key]);
        }
        return resolveWeakValue(target[index]);
      }
      function zuzuSliceBounds(size, from, length) {
        let start = Number(from ?? 0);
        if (!Number.isFinite(start)) {
          start = 0;
        }
        if (start < 0) {
          start = size + start;
        }
        start = Math.max(0, Math.min(size, start));
        if (length == null) {
          return [start, size];
        }
        const span = Number(length);
        if (!Number.isFinite(span)) {
          return [start, start];
        }
        const end = span < 0 ? Math.max(0, Math.min(size, size + span)) : Math.max(0, Math.min(size, start + span));
        return [Math.min(start, end), Math.max(start, end)];
      }
      function zuzuGetSlice(target, from, length) {
        target = resolveWeakValue(target);
        if (target == null) {
          return null;
        }
        if (typeof target === "string") {
          const chars = [...target];
          const [start, end] = zuzuSliceBounds(chars.length, from, length);
          return chars.slice(start, end).join("");
        }
        if (target instanceof ZuzuBinary) {
          const [start, end] = zuzuSliceBounds(target.length, from, length);
          return target.slice(start, end);
        }
        if (Array.isArray(target)) {
          const [start, end] = zuzuSliceBounds(target.length, from, length);
          return target.slice(start, end);
        }
        return target.slice(from, length == null ? void 0 : Number(from) + Number(length));
      }
      function zuzuAssignSlice(target, from, length, value) {
        const hasLength = length != null;
        const replacement = value == null ? "" : value;
        if (typeof target === "string") {
          const chars = [...target];
          const [start2, end] = zuzuSliceBounds(chars.length, from, length);
          chars.splice(start2, end - start2, ...[...String(replacement)]);
          return chars.join("");
        }
        const start = Number(from);
        if (Array.isArray(target)) {
          const items = Array.isArray(replacement) ? replacement : [replacement];
          const span = hasLength ? Number(length) : null;
          if (hasLength) {
            target.splice(start, span, ...items);
          } else {
            target.splice(start, target.length - start, ...items);
          }
          return target;
        }
        if (target instanceof ZuzuBinary) {
          if (!(value instanceof ZuzuBinary)) {
            throw new Error(`TypeException: BinaryString slice assignment expects BinaryString, got ${zuzuTypeof(value)}`);
          }
          const [byteStart, byteEnd] = zuzuSliceBounds(target.length, from, length);
          const next = new Uint8Array(target.length - (byteEnd - byteStart) + value.bytes.length);
          next.set(target.bytes.slice(0, byteStart), 0);
          next.set(value.bytes, byteStart);
          next.set(target.bytes.slice(byteEnd), byteStart + value.bytes.length);
          target.bytes = next;
          return target;
        }
        throw new Error(`TypeException: slice assignment expects String or Array, got ${zuzuTypeof(target)}`);
      }
      function refKey(target, key) {
        target = resolveWeakValue(target);
        return function refValue(maybeValue) {
          if (arguments.length === 0) {
            return resolveWeakValue(target[key]);
          }
          target[key] = maybeValue;
          return maybeValue;
        };
      }
      function assignIndexedValue(target, index, value, isWeakWrite = false, assignTarget = null) {
        target = resolveWeakValue(target);
        if (target == null) {
          throw new Error("TypeException: cannot assign to null");
        }
        if (target instanceof ZuzuBinary) {
          if (!(value instanceof ZuzuBinary)) {
            throw new Error(`TypeException: BinaryString index assignment expects BinaryString, got ${zuzuTypeof(value)}`);
          }
          zuzuAssignSlice(target, index, 1, value);
          if (typeof assignTarget === "function") {
            assignTarget(target);
          }
          return target;
        }
        if (typeof target === "string") {
          let resolved = Number(index);
          if (!Number.isFinite(resolved)) {
            throw new Error("TypeException: String index assignment expects numeric index");
          }
          const chars = [...target];
          if (resolved < 0) {
            resolved = chars.length + resolved;
          }
          resolved = Math.max(0, Math.min(chars.length, resolved));
          chars.splice(resolved, resolved < chars.length ? 1 : 0, ...[...String(value ?? "")]);
          const updated = chars.join("");
          return typeof assignTarget === "function" ? assignTarget(updated) : updated;
        }
        if (isPairListLike(target)) {
          const stored2 = isWeakWrite ? makeWeakValue(value) : retainCollectionValue(target, value);
          target.list.push([String(index), stored2]);
          return stored2;
        }
        const stored = isWeakWrite ? makeWeakValue(value) : retainCollectionValue(target, value);
        releaseCollectionValue(target, target[index]);
        target[index] = stored;
        return stored;
      }
      function refSlice(target, from, length) {
        target = resolveWeakValue(target);
        return function refSliceValue(maybeValue) {
          const start = Number(from);
          const hasLength = length != null;
          const span = hasLength ? Number(length) : null;
          if (arguments.length === 0) {
            return zuzuGetSlice(target, start, hasLength ? span : null);
          }
          if (target instanceof ZuzuBinary || typeof target === "string") {
            return zuzuAssignSlice(target, start, hasLength ? span : null, maybeValue);
          }
          if (!hasLength) {
            target.splice(start, target.length - start, ...maybeValue);
            return maybeValue;
          }
          target.splice(start, span, ...maybeValue);
          return maybeValue;
        };
      }
      function makePathOperator(runtime, filename) {
        return function zuzuPathOp(haystack, pathSpec, mode = "first") {
          const pathObj = resolvePathObject(runtime, filename, pathSpec);
          if (mode === "all") {
            return pathObj.query(haystack);
          }
          if (mode === "exists") {
            return pathObj.exists(haystack);
          }
          return pathObj.first(haystack, null);
        };
      }
      function resolveActivePathClass(runtime, filename) {
        const internals = runtime.loadModule("std/internals", filename);
        if (!internals || typeof internals.getupperprop !== "function") {
          return null;
        }
        return internals.getupperprop(0, "paths");
      }
      function resolvePathObject(runtime, filename, pathSpec) {
        let PathClass = resolveActivePathClass(runtime, filename);
        const pathText = String(pathSpec ?? "");
        if (!PathClass) {
          const zzpath = runtime.loadModule("std/path/zz", filename);
          PathClass = zzpath && zzpath.ZZPath ? zzpath.ZZPath : null;
        }
        if (!PathClass) {
          throw new Error("Exception: no path implementation available");
        }
        return pathSpec && typeof pathSpec === "object" && typeof pathSpec.query === "function" ? pathSpec : new PathClass({ path: pathText });
      }
      function makePathAssignmentOperator(runtime, filename) {
        return function zuzuPathAssign(haystack, pathSpec, value, mode = "first", op = ":=", isWeakWrite = false) {
          const pathObj = resolvePathObject(runtime, filename, pathSpec);
          const storedValue = isWeakWrite ? makeWeakValue(value) : value;
          if (mode === "all") {
            return pathObj.assign_all(haystack, storedValue, op);
          }
          if (mode === "maybe") {
            return pathObj.assign_maybe(haystack, storedValue, op);
          }
          return pathObj.assign_first(haystack, storedValue, op);
        };
      }
      function makePathReferenceOperator(runtime, filename) {
        return function zuzuPathRef(haystack, pathSpec, mode = "first") {
          const pathObj = resolvePathObject(runtime, filename, pathSpec);
          if (mode === "all") {
            return pathObj.ref_all(haystack);
          }
          if (mode === "maybe") {
            return pathObj.ref_maybe(haystack);
          }
          return pathObj.ref_first(haystack);
        };
      }
      function callPathRef(refFn) {
        if (typeof refFn !== "function") {
          throw new Error("Exception: path reference target is not assignable");
        }
        return refFn();
      }
      function setPathRef(refFn, value) {
        if (typeof refFn !== "function") {
          throw new Error("Exception: path reference target is not assignable");
        }
        return refFn(value);
      }
      function makePathUpdateOperator(runtime, filename) {
        return function zuzuPathUpdate(haystack, pathSpec, mode, operator, prefix) {
          const pathObj = resolvePathObject(runtime, filename, pathSpec);
          if (mode === "all") {
            const refs = pathObj.ref_all(haystack);
            const oldValues = [];
            const newValues = [];
            for (const refFn2 of refs) {
              const oldValue2 = zuzuToNumber(callPathRef(refFn2));
              const newValue2 = operator === "++" ? oldValue2 + 1 : oldValue2 - 1;
              setPathRef(refFn2, newValue2);
              oldValues.push(oldValue2);
              newValues.push(newValue2);
            }
            return prefix ? newValues : oldValues;
          }
          if (mode === "maybe") {
            const refFn2 = pathObj.ref_maybe(haystack);
            if (refFn2 == null) {
              return false;
            }
            const oldValue2 = zuzuToNumber(callPathRef(refFn2));
            const newValue2 = operator === "++" ? oldValue2 + 1 : oldValue2 - 1;
            setPathRef(refFn2, newValue2);
            return true;
          }
          const refFn = pathObj.ref_first(haystack);
          const oldValue = zuzuToNumber(callPathRef(refFn));
          const newValue = operator === "++" ? oldValue + 1 : oldValue - 1;
          setPathRef(refFn, newValue);
          return prefix ? newValue : oldValue;
        };
      }
      function zuzuTypeMatches(value, typeName2) {
        value = resolveWeakValue(value);
        if (typeName2 === "Any") {
          return 1;
        }
        if (value == null) {
          return 0;
        }
        if (typeName2 === "Number" || typeName2 === "String" || typeName2 === "Array" || typeName2 === "Dict" || typeName2 === "Set" || typeName2 === "Bag" || typeName2 === "PairList" || typeName2 === "Collection" || typeName2 === "Class" || typeName2 === "Function" || typeName2 === "Object" || typeName2 === "Exception" || typeName2 === "Regexp") {
          if (typeName2 === "Collection") {
            return Array.isArray(value) || isSetLike(value) || isBagLike(value) || isPairListLike(value) || zuzuTypeof(value) === "Dict" ? 1 : 0;
          }
          if (typeName2 === "Object") {
            return value !== null && typeof value === "object" ? 1 : 0;
          }
          if (typeName2 === "PairList") {
            return isPairListLike(value) ? 1 : 0;
          }
          if (typeName2 === "Exception") {
            const globalType2 = globalThis.Exception;
            if (globalType2 != null && zuzuInstanceof(value, globalType2)) {
              return 1;
            }
            return value instanceof Error ? 1 : 0;
          }
          return zuzuTypeof(value) === typeName2 ? 1 : 0;
        }
        if (typeName2 === "BinaryString") {
          return value instanceof ZuzuBinary ? 1 : 0;
        }
        if (typeName2 === "Boolean") {
          if (typeof value === "boolean" || Object.prototype.toString.call(value) === "[object Boolean]") {
            return 1;
          }
          if (typeof value === "number") {
            return value === 0 || value === 1 ? 1 : 0;
          }
        }
        if (typeName2 === "Regexp") {
          return Object.prototype.toString.call(value) === "[object RegExp]" ? 1 : 0;
        }
        if (zuzuTypeof(value) === typeName2) {
          return 1;
        }
        if (Array.isArray(value.__zuzu_type_names) && value.__zuzu_type_names.includes(typeName2)) {
          return 1;
        }
        let proto = Object.getPrototypeOf(value);
        while (proto) {
          const ctor = proto.constructor;
          if (ctor && ctor.name === typeName2) {
            return 1;
          }
          proto = Object.getPrototypeOf(proto);
        }
        const globalType = globalThis[typeName2];
        if (globalType == null) {
          return 0;
        }
        return zuzuInstanceof(value, globalType) ? 1 : 0;
      }
      var ZuzuScript = class {
        constructor(options = {}) {
          if (options.host) {
            this.host = options.host;
          } else {
            const { createNodeHost } = __require("./host/node-host");
            this.host = createNodeHost(options);
          }
          this.repoRoot = this.host.repoRoot;
          this.includePaths = this.host.includePaths;
          this.moduleSearchRoots = defaultModuleSearchRoots(
            this.host,
            this.repoRoot,
            this.includePaths
          );
          const allowCapabilities = new Set(Array.isArray(options.allowCapabilities) ? options.allowCapabilities.map((item) => String(item)) : []);
          this.denyCapabilities = new Set(Array.isArray(options.denyCapabilities) ? options.denyCapabilities.map((item) => String(item)) : []);
          for (const capability of ["gui"]) {
            if (!allowCapabilities.has(capability) && !this.host.capabilities.has(capability)) {
              this.denyCapabilities.add(capability);
            }
          }
          this.denyModules = new Set(Array.isArray(options.denyModules) ? options.denyModules.map((item) => String(item)) : []);
          this.debugLevel = Number.isFinite(Number(options.debugLevel)) ? Number(options.debugLevel) : 0;
          this.moduleCache = /* @__PURE__ */ new Map();
          this.moduleLoading = /* @__PURE__ */ new Set();
          this.evalCapabilityOverrides = null;
          this.outputLines = null;
          this.stdoutHandler = null;
          this.stderrHandler = null;
          this.executionTimeoutMs = Number.isFinite(Number(options.executionTimeoutMs)) ? Number(options.executionTimeoutMs) : null;
          this.transpiler = normalizeTranspilerName(
            options.transpiler || DEFAULT_TRANSPILER
          );
          this.asyncImports = options.asyncImports === true;
          if (typeof this.host.loadJsModule !== "function") {
            this.host.loadJsModule = (filename) => __require(filename);
          }
        }
        usesAsyncImports() {
          return this.asyncImports || typeof this.host.hasAsyncModules === "function" && this.host.hasAsyncModules();
        }
        transpile(source, options = {}) {
          return transpile(source, {
            ...options,
            transpiler: options.transpiler || this.transpiler,
            asyncImports: options.asyncImports ?? this.usesAsyncImports()
          });
        }
        getModuleSearchRoots() {
          return this.moduleSearchRoots.slice();
        }
        isDeniedByCapability(moduleName) {
          const required = capabilitiesForModule(moduleName);
          for (const capability of required) {
            if (this.isCapabilityDenied(capability)) {
              return capability;
            }
            if (!this.host.capabilities.has(capability)) {
              return capability;
            }
          }
          return null;
        }
        isCapabilityDenied(capability) {
          if (this.denyCapabilities.has(capability)) {
            return true;
          }
          if (this.evalCapabilityOverrides) {
            const flagName = `deny_${capability}`;
            if (this.evalCapabilityOverrides[flagName]) {
              return true;
            }
          }
          return false;
        }
        enforceModulePolicy(moduleName) {
          if (this.denyModules.has(moduleName)) {
            throw new Error(`Denied module: ${moduleName}`);
          }
          const capability = this.isDeniedByCapability(moduleName);
          if (capability) {
            if (this.denyCapabilities.has(capability)) {
              throw new Error(`Denied capability '${capability}' blocks module '${moduleName}'`);
            }
            throw new Error(`Module '${moduleName}' requires unsupported capability '${capability}' on host '${this.host.name}'`);
          }
        }
        fileValueForFilename(filename) {
          if (this.isCapabilityDenied("fs") || !this.host.capabilities.has("fs") || !filename || String(filename).startsWith("<") || String(filename).startsWith("(")) {
            return null;
          }
          const { Path } = require_io();
          return new Path(filename);
        }
        resolveModulePath(moduleName, fromFile) {
          const fromDir = fromFile ? this.host.dirname(fromFile) : this.repoRoot;
          if (!moduleName.startsWith(".") && !moduleName.startsWith("/")) {
            const runtimeSupported = this.host.resolve(
              this.repoRoot,
              "modules",
              `${moduleName}.js`
            );
            if (this.host.fileExists(runtimeSupported)) {
              return runtimeSupported;
            }
          }
          const candidates = [];
          if (moduleName.startsWith(".") || moduleName.startsWith("/")) {
            candidates.push(this.host.resolve(fromDir, moduleName));
          } else {
            for (const base of this.getModuleSearchRoots()) {
              candidates.push(this.host.resolve(base, moduleName));
            }
          }
          const withExt = [];
          for (const candidate of candidates) {
            withExt.push(candidate, `${candidate}.zzs`, `${candidate}.zzm`, `${candidate}.js`);
          }
          for (const candidate of withExt) {
            if (this.host.fileExists(candidate)) {
              return candidate;
            }
          }
          throw new Error(`Unable to resolve module: ${moduleName}`);
        }
        buildContext(options = {}) {
          const filename = options.filename;
          const runtime = this;
          taskRuntime2.setDebugLevel(this.debugLevel);
          let context;
          const capabilityFlags = /* @__PURE__ */ Object.create(null);
          for (const name2 of this.host.capabilities) {
            if (!this.denyCapabilities.has(name2)) {
              capabilityFlags[name2] = 1;
            }
          }
          if (this.evalCapabilityOverrides) {
            for (const [flagName, denied] of Object.entries(this.evalCapabilityOverrides)) {
              const capability = flagName.replace(/^deny_/, "");
              if (denied) {
                delete capabilityFlags[capability];
              } else if (this.host.capabilities.has(capability) && !this.denyCapabilities.has(capability)) {
                capabilityFlags[capability] = 1;
              }
            }
          }
          const moduleSearchRoots = this.getModuleSearchRoots();
          const emit = (value) => {
            let line = String(value);
            if (line === "Infinity") {
              line = "Inf";
            } else if (line === "-Infinity") {
              line = "-Inf";
            }
            if (this.outputLines) {
              this.outputLines.push(line);
            }
            if (typeof this.stdoutHandler === "function") {
              this.stdoutHandler(`${line}
`);
            } else if (!this.outputLines) {
              this.host.consoleLog(line);
            }
          };
          const emitStderr = (value) => {
            const line = String(value);
            if (typeof this.stderrHandler === "function") {
              this.stderrHandler(`${line}
`);
            } else if (typeof console !== "undefined" && typeof console.warn === "function") {
              console.warn(line);
            }
          };
          installHostCollectionMethods();
          const ZuzuException = class Exception extends Error {
            constructor(value = "") {
              if (isPairListLike(value)) {
                super(value.get("message", ""));
                this.name = "Exception";
                this.file = value.get("file", null);
                this.line = value.get("line", null);
                this.code = value.get("code", null);
                return;
              }
              if (value && typeof value === "object" && !Array.isArray(value) && Object.prototype.hasOwnProperty.call(value, "message")) {
                super(value.message);
                this.name = "Exception";
                this.file = Object.prototype.hasOwnProperty.call(value, "file") ? value.file : null;
                this.line = Object.prototype.hasOwnProperty.call(value, "line") ? value.line : null;
                this.code = Object.prototype.hasOwnProperty.call(value, "code") ? value.code : null;
                return;
              }
              super(value);
              this.name = "Exception";
              this.file = null;
              this.line = null;
              this.code = null;
            }
            to_String() {
              const name2 = this.name || this.constructor.name || "Exception";
              const message = String(this.message ?? "");
              if (message === name2 || message.startsWith(`${name2}:`)) {
                return message;
              }
              return message === "" ? name2 : `${name2}: ${message}`;
            }
            message() {
              return String(this.message ?? "");
            }
          };
          const ZuzuTypeException = class TypeException extends ZuzuException {
            constructor(value = "") {
              super(value);
              this.name = "TypeException";
            }
          };
          const snapshotSpreadArg = (input) => {
            const value = resolveWeakValue(input);
            if (Array.isArray(value)) {
              return {
                type: "spread_positional",
                values: value.slice()
              };
            }
            if (isPairListLike(value)) {
              return {
                type: "spread_named",
                entries: value.list.map((pair) => [pair[0], pair[1]])
              };
            }
            if (zuzuTypeof(value) === "Dict") {
              return {
                type: "spread_named",
                entries: Object.keys(value).sort().map((key) => [key, value[key]])
              };
            }
            throw new ZuzuTypeException(
              `argument spread expects Array, Dict, or PairList, got ${zuzuTypeof(value)}`
            );
          };
          const unpackDeclarationSource = (input) => {
            const value = resolveWeakValue(input);
            if (isPairListLike(value) || zuzuTypeof(value) === "Dict") {
              return value;
            }
            throw new ZuzuTypeException(
              `Declaration unpacking expects Dict or PairList, got ${zuzuTypeof(value)}`
            );
          };
          const unpackDeclarationValue = (source, key, defaultThunk, name2, typeName2, isWeakStorage) => {
            const valueSource = unpackDeclarationSource(source);
            const normalized = normalizeDictKey(key);
            let value;
            let found = false;
            if (isPairListLike(valueSource)) {
              const pair = valueSource.list.find(
                (entry) => entry[0] === normalized
              );
              if (pair) {
                value = pair[1];
                found = true;
              }
            } else if (Object.prototype.hasOwnProperty.call(valueSource, normalized)) {
              value = valueSource[normalized];
              found = true;
            }
            if (!found) {
              value = typeof defaultThunk === "function" ? defaultThunk() : null;
            }
            if (typeName2 && typeName2 !== "Any" && !zuzuTypeMatches(value, typeName2)) {
              throw new ZuzuTypeException(
                `'${name2}' must be ${typeName2}, got ${zuzuTypeof(value)}`
              );
            }
            return isWeakStorage ? makeWeakValue(value) : retainValue(value);
          };
          const spreadCallArgs = (parts) => {
            const positional = [];
            const named = [];
            for (const part of parts) {
              if (part.type === "positional") {
                positional.push(part.value);
                continue;
              }
              if (part.type === "named") {
                named.push(part.value);
                continue;
              }
              if (part.type === "spread_positional") {
                positional.push(...part.values);
                continue;
              }
              if (part.type === "spread_named") {
                for (const entry of part.entries) {
                  named.push(entry);
                }
                continue;
              }
              throw new ZuzuTypeException("invalid call argument descriptor");
            }
            if (named.length > 0) {
              positional.push(makeTemporaryPairList(named));
            }
            return positional;
          };
          const normalizeZuzuException = (err) => {
            if (err instanceof ZuzuException) {
              return err;
            }
            if (err && err.__zuzu_nonlocal_return) {
              return err;
            }
            if (err instanceof Error && [
              "CancelledException",
              "TimeoutException",
              "ChannelClosedException"
            ].includes(err.name)) {
              return err;
            }
            if (err && typeof err === "object") {
              const ctorName = err.constructor && err.constructor.name;
              if (!isNativeErrorConstructorName(ctorName)) {
                return err;
              }
            }
            const message = err && err.message != null ? String(err.message) : String(err);
            if (message.startsWith("TypeException:")) {
              return new ZuzuTypeException({
                message,
                file: err && err.file != null ? err.file : null,
                line: err && err.line != null ? err.line : null,
                code: err && err.code != null ? err.code : null
              });
            }
            return new ZuzuException({
              message: message.startsWith("Exception: ") ? message.slice("Exception: ".length) : message,
              file: err && err.file != null ? err.file : null,
              line: err && err.line != null ? err.line : null,
              code: err && err.code != null ? err.code : null
            });
          };
          const ZuzuExhaustedException = class ExhaustedException extends Error {
            constructor(message = "") {
              super(message);
              this.name = "ExhaustedException";
            }
            to_String() {
              const message = String(this.message ?? "");
              if (message === this.name || message.startsWith(`${this.name}:`)) {
                return message;
              }
              return message === "" ? this.name : `${this.name}: ${message}`;
            }
          };
          const defineRuntimeMethod = (proto, name2, fn2) => {
            const desc = /* @__PURE__ */ Object.create(null);
            desc.value = fn2;
            desc.enumerable = false;
            Object.defineProperty(proto, name2, desc);
          };
          if (!Number.prototype.contains) {
            defineRuntimeMethod(Number.prototype, "contains", function _containsNumber(value) {
              return Number(this.valueOf()) === Number(value) ? 1 : 0;
            });
          }
          if (!Set.prototype.push) {
            defineRuntimeMethod(Set.prototype, "length", function _lengthSet() {
              return this.size;
            });
            defineRuntimeMethod(Set.prototype, "count", function _countSet() {
              return this.size;
            });
            defineRuntimeMethod(Set.prototype, "empty", function _emptySet() {
              return this.size === 0 ? 1 : 0;
            });
            defineRuntimeMethod(Set.prototype, "is_empty", function _isEmptySet() {
              return this.empty();
            });
            defineRuntimeMethod(Set.prototype, "push", function _pushSet(...values) {
              for (const v of values) {
                addSetValue(this, v);
              }
              return this;
            });
            defineRuntimeMethod(Set.prototype, "push_weak", function _pushWeakSet(...values) {
              for (const v of values) {
                this.add(makeWeakValue(v));
              }
              return this;
            });
            defineRuntimeMethod(Set.prototype, "contains", function _containsSet(value) {
              return contains(this, value);
            });
            defineRuntimeMethod(Set.prototype, "remove", function _removeSet(value) {
              const resolved = resolveWeakValue(value);
              if (this.delete(resolved)) {
                releaseCollectionValue(this, resolved);
              }
              return this;
            });
            defineRuntimeMethod(Set.prototype, "to_Array", function _setToArray() {
              return makeArray(this);
            });
            defineRuntimeMethod(Set.prototype, "to_Bag", function _setToBag() {
              return makeBag([...this]);
            });
            defineRuntimeMethod(Set.prototype, "copy", function _setCopy() {
              return makeSet(this);
            });
            defineRuntimeMethod(Set.prototype, "union", function _setUnion(other) {
              return collectionUnion(this, other);
            });
            defineRuntimeMethod(Set.prototype, "intersection", function _setIntersection(other) {
              return collectionIntersection(this, other);
            });
            defineRuntimeMethod(Set.prototype, "difference", function _setDifference(other) {
              return collectionDifference(this, other);
            });
            defineRuntimeMethod(Set.prototype, "symmetric_difference", function _setSymmetricDifference(other) {
              return collectionDifference(this.union(other), this.intersection(other));
            });
            defineRuntimeMethod(Set.prototype, "is_subset", function _setIsSubset(other) {
              return collectionSubsetOf(this, other);
            });
            defineRuntimeMethod(Set.prototype, "is_superset", function _setIsSuperset(other) {
              return collectionSupersetOf(this, other);
            });
            defineRuntimeMethod(Set.prototype, "is_disjoint", function _setIsDisjoint(other) {
              return this.intersection(other).size === 0 ? 1 : 0;
            });
            defineRuntimeMethod(Set.prototype, "equals", function _setEquals(other) {
              return collectionEquivalentOf(this, other);
            });
            defineRuntimeMethod(Set.prototype, "sort", function _setSort(fn2) {
              return [...this].sort(fn2);
            });
            defineRuntimeMethod(Set.prototype, "sortstr", function _setSortstr() {
              return [...this].sort(stringSortComparator);
            });
            defineRuntimeMethod(Set.prototype, "sortnum", function _setSortnum() {
              return [...this].map((item) => Number(item)).sort((a, b) => a - b);
            });
            defineRuntimeMethod(Set.prototype, "map", function _setMap(fn2) {
              return new Set([...this].map(fn2));
            });
            defineRuntimeMethod(Set.prototype, "grep", function _setGrep(fn2) {
              return new Set([...this].filter(fn2));
            });
            defineRuntimeMethod(Set.prototype, "any", function _setAny(fn2) {
              return [...this].some(fn2) ? 1 : 0;
            });
            defineRuntimeMethod(Set.prototype, "all", function _setAll(fn2) {
              return [...this].every(fn2) ? 1 : 0;
            });
            defineRuntimeMethod(Set.prototype, "first", function _setFirst(fn2) {
              for (const v of this) {
                if (fn2(v)) {
                  return v;
                }
              }
              return null;
            });
            defineRuntimeMethod(Set.prototype, "remove_if", function _setRemoveIf(fn2) {
              for (const v of [...this]) {
                if (fn2(v)) {
                  releaseCollectionValue(this, v);
                  this.delete(v);
                }
              }
              return this;
            });
            defineRuntimeMethod(Set.prototype, "for_each_value", function _setForEachValue(fn2) {
              for (const v of this) {
                fn2(v);
              }
              return this;
            });
          }
          const fallbackDoneTesting = function done_testing(n = null) {
            if (typeof globalThis._LEVEL === "number" && globalThis._LEVEL > 0) {
              throw new Error("Unexpected done_testing() in subtest");
            }
            let seen = 0;
            if (Array.isArray(runtime.outputLines)) {
              for (const line of runtime.outputLines) {
                if (/^ok\b/.test(line) || /^not ok\b/.test(line)) {
                  seen++;
                }
              }
            }
            if (n != null && Number(n) !== Number(seen)) {
              throw new Error(`Expected ${n} tests, but ran ${seen}`);
            }
            emit(`1..${seen}`);
            if (typeof globalThis._FAILED === "number" && globalThis._FAILED > 0) {
              throw new Error(`Failed ${globalThis._FAILED} tests`);
            }
            return true;
          };
          const systemGlobalSeed = {
            language_version: 0,
            runtime: "zuzu-js",
            runtime_version: runtimeVersion,
            platform: this.host.name,
            inc: Object.freeze(moduleSearchRoots.slice()),
            deny_fs: capabilityFlags.fs ? false : true,
            deny_net: capabilityFlags.net ? false : true,
            deny_perl: true,
            deny_js: capabilityFlags.js ? false : true,
            deny_proc: capabilityFlags.proc ? false : true,
            deny_db: capabilityFlags.db ? false : true,
            deny_clib: capabilityFlags.clib ? false : true,
            deny_gui: capabilityFlags.gui ? false : true,
            deny_worker: capabilityFlags.worker ? false : true
          };
          if (this.host.name === "node" && typeof process !== "undefined" && process.versions) {
            systemGlobalSeed.nodejs_version = String(process.versions.node || "");
          }
          Object.freeze(systemGlobalSeed);
          const currentSystem = () => {
            const current = {
              ...systemGlobalSeed,
              deny_fs: this.isCapabilityDenied("fs") || !this.host.capabilities.has("fs"),
              deny_net: this.isCapabilityDenied("net") || !this.host.capabilities.has("net"),
              deny_perl: true,
              deny_js: this.isCapabilityDenied("js") || !this.host.capabilities.has("js"),
              deny_proc: this.isCapabilityDenied("proc") || !this.host.capabilities.has("proc"),
              deny_db: this.isCapabilityDenied("db") || !this.host.capabilities.has("db"),
              deny_clib: this.isCapabilityDenied("clib") || !this.host.capabilities.has("clib"),
              deny_gui: this.isCapabilityDenied("gui") || !this.host.capabilities.has("gui"),
              deny_worker: this.isCapabilityDenied("worker") || !this.host.capabilities.has("worker")
            };
            return Object.freeze(current);
          };
          context = {
            ...options.globals || {},
            __file__: this.fileValueForFilename(filename),
            __zuzu_system_seed: systemGlobalSeed,
            __zuzu_current_system: currentSystem,
            __zuzu_operator_string: zuzuOperatorString,
            DEBUG: this.debugLevel,
            __zuzu_host_capabilities: capabilityFlags,
            has_capability(name2) {
              const key = String(name2);
              return capabilityFlags[key] ? 1 : 0;
            },
            outputLines: this.outputLines,
            done_testing: options.globals && typeof options.globals.done_testing === "function" ? options.globals.done_testing : fallbackDoneTesting,
            exports: options.exports,
            module: options.module,
            console: {
              log: (value) => this.host.consoleLog(value),
              warn: (value) => emitStderr(value),
              error: (value) => emitStderr(value)
            },
            Bag: ZuzuBag,
            PairList,
            Exception: ZuzuException,
            TypeException: ZuzuTypeException,
            ExhaustedException: ZuzuExhaustedException,
            __zuzu_normalize_exception: normalizeZuzuException,
            Task: taskRuntime2.Task,
            CancelledException: taskRuntime2.CancelledException,
            TimeoutException: taskRuntime2.TimeoutException,
            ChannelClosedException: taskRuntime2.ChannelClosedException,
            Null: null,
            Any: function Any() {
            },
            Collection: function Collection() {
            },
            Class: function Class() {
            },
            BinaryString: BinaryString2,
            say(value, ...parts) {
              if (Array.isArray(value) && Object.prototype.hasOwnProperty.call(value, "raw")) {
                let out = "";
                for (let i = 0; i < value.length; i++) {
                  out += value[i];
                  if (i < parts.length) {
                    out += String(parts[i]);
                  }
                }
                emit(out);
                return;
              }
              emit(value);
            },
            __zuzu_switch: runSwitch,
            __zuzu_switch_async: runSwitchAsync,
            __zuzu_match: runMatch,
            __zuzu_to_regexp: operatorRegexp,
            __zuzu_regex_replace: regexReplaceValue,
            __zuzu_contains: contains,
            __zuzu_union: collectionUnion,
            __zuzu_intersection: collectionIntersection,
            __zuzu_difference: collectionDifference,
            __zuzu_default: defaultOperator,
            __zuzu_subsetof: collectionSubsetOf,
            __zuzu_supersetof: collectionSupersetOf,
            __zuzu_equivalentof: collectionEquivalentOf,
            __zuzu_array: makeArray,
            __zuzu_set: makeSet,
            __zuzu_bag: makeBag,
            __zuzu_pairlist_literal: makePairList,
            __zuzu_temp_pairlist: makeTemporaryPairList,
            __zuzu_snapshot_spread_arg: snapshotSpreadArg,
            __zuzu_spread_call_args: spreadCallArgs,
            __zuzu_unpack_source: unpackDeclarationSource,
            __zuzu_unpack_value: unpackDeclarationValue,
            __zuzu_release_collection_values: releaseCollectionValues,
            __zuzu_path_op: makePathOperator(runtime, filename),
            __zuzu_path_assign: makePathAssignmentOperator(runtime, filename),
            __zuzu_path_ref: makePathReferenceOperator(runtime, filename),
            __zuzu_path_update: makePathUpdateOperator(runtime, filename),
            __zuzu_call_member: zuzuCallMember,
            __zuzu_is_weakable_value: isWeakableValue,
            __zuzu_is_pairlist: isPairListLike,
            __zuzu_make_weak_value: makeWeakValue,
            __zuzu_resolve_weak_value: resolveWeakValue,
            __zuzu_retain_value: retainValue,
            __zuzu_release_value: releaseValue,
            __zuzu_retain_collection_value: retainCollectionValue,
            __zuzu_release_collection_value: releaseCollectionValue,
            __zuzu_add_set_value: addSetValue,
            __zuzu_assign_strong: assignStrongValue,
            __zuzu_assign_weak: assignWeakValue,
            __zuzu_assign_index: assignIndexedValue,
            __zuzu_bodyless_function(name2) {
              let target = null;
              const fn2 = function __zuzu_bodyless_function_wrapper(...args) {
                if (typeof target === "function") {
                  return target.apply(this, args);
                }
                throw new Error(`Exception: Function '${name2}' has no body`);
              };
              Object.defineProperty(fn2, "__zuzu_complete_body", {
                value(completed) {
                  target = completed;
                  return fn2;
                },
                enumerable: false,
                configurable: true
              });
              return fn2;
            },
            __zuzu_complete_function(current, completed, meta) {
              const value = completed;
              if (value && (typeof value === "function" || typeof value === "object")) {
                Object.defineProperty(value, "__zuzu_marshal_meta", {
                  value: meta || {},
                  enumerable: false,
                  configurable: true,
                  writable: true
                });
              }
              if (current && typeof current.__zuzu_complete_body === "function") {
                return current.__zuzu_complete_body(value);
              }
              throw new Error("Exception: function predeclaration target is not bodyless");
            },
            __zuzu_with_marshal_meta(value, meta) {
              if (value && (typeof value === "function" || typeof value === "object")) {
                Object.defineProperty(value, "__zuzu_marshal_meta", {
                  value: meta || {},
                  enumerable: false,
                  configurable: true,
                  writable: true
                });
              }
              return value;
            },
            __zuzu_await_value(value) {
              return taskRuntime2.awaitValue(value);
            },
            __zuzu_await_block(value) {
              return taskRuntime2.awaitBlock(value);
            },
            __zuzu_callsite(metadata, fn2) {
              return taskRuntime2.withCallsite(
                {
                  file: filename,
                  ...metadata || {}
                },
                fn2
              );
            },
            __zuzu_task(fn2, metadata) {
              return taskRuntime2.task(fn2, {
                file: filename,
                ...metadata || {}
              });
            },
            __zuzu_task_sync(fn2, metadata) {
              return taskRuntime2.taskSync(fn2, {
                file: filename,
                ...metadata || {}
              });
            },
            __zuzu_spawn(fn2, metadata) {
              return taskRuntime2.spawn(fn2, {
                file: filename,
                ...metadata || {}
              });
            },
            async __zuzu_collection_map_async(collection, fn2) {
              const out = [];
              for (const item of collection || []) {
                out.push(await taskRuntime2.awaitValue(fn2(item)));
              }
              return out;
            },
            async __zuzu_collection_grep_async(collection, fn2) {
              const out = [];
              for (const item of collection || []) {
                if (zuzuTruthy(await taskRuntime2.awaitValue(fn2(item)))) {
                  out.push(item);
                }
              }
              return out;
            },
            async __zuzu_collection_reduce_async(collection, fn2) {
              const items = Array.from(collection || []);
              if (items.length === 0) {
                return null;
              }
              let acc = items[0];
              for (let i = 1; i < items.length; i++) {
                acc = await taskRuntime2.awaitValue(fn2(acc, items[i]));
              }
              return acc;
            },
            __zuzu_prepare_eval(source, namedArgs = null) {
              if (typeof source !== "string") {
                throw new ZuzuTypeException(
                  `TypeException: eval expects String, got ${zuzuTypeof(source)}`
                );
              }
              if (namedArgs != null && !isPairListLike(namedArgs)) {
                throw new ZuzuTypeException(
                  `TypeException: eval named arguments must be PairList, got ${zuzuTypeof(namedArgs)}`
                );
              }
              let compiled;
              try {
                compiled = runtime.transpile(source, { syncEval: true });
              } catch (err) {
                const line = err && err.token && err.token.line != null ? err.token.line : 1;
                throw new ZuzuException({
                  message: err && err.message ? String(err.message) : String(err),
                  file: "<std/eval>",
                  line,
                  code: "E_COMPILE_SYNTAX"
                });
              }
              if (namedArgs == null) {
                return compiled;
              }
              const overrides = /* @__PURE__ */ Object.create(null);
              const accepted = /* @__PURE__ */ new Set([
                "deny_fs",
                "deny_net",
                "deny_perl",
                "deny_js",
                "deny_proc",
                "deny_db",
                "deny_clib",
                "deny_gui",
                "deny_worker"
              ]);
              for (const optName of namedArgs.keys()) {
                if (!accepted.has(optName)) {
                  throw new ZuzuException(
                    `Unknown named argument '${optName}' for eval`
                  );
                }
              }
              for (const [optName, flagName] of [
                ["deny_fs", "deny_fs"],
                ["deny_net", "deny_net"],
                ["deny_perl", "deny_perl"],
                ["deny_js", "deny_js"],
                ["deny_proc", "deny_proc"],
                ["deny_db", "deny_db"],
                ["deny_clib", "deny_clib"],
                ["deny_gui", "deny_gui"],
                ["deny_worker", "deny_worker"]
              ]) {
                if (namedArgs.has(optName) && zuzuTruthy(namedArgs.get(optName))) {
                  overrides[flagName] = true;
                }
              }
              if (Object.keys(overrides).length === 0) {
                return compiled;
              }
              return [
                "( () => {",
                `const __zuzu_eval_prev_caps = __zuzu_push_eval_capability_overrides( ${JSON.stringify(overrides)} );`,
                "try {",
                "return ( () => {",
                "const __system__ = __zuzu_current_system();",
                `return ${compiled};`,
                "} )();",
                "} finally {",
                "__zuzu_pop_eval_capability_overrides( __zuzu_eval_prev_caps );",
                "}",
                "} )()"
              ].join("\n");
            },
            __zuzu_prepare_eval_call_args(args) {
              let source = "";
              let namedArgs = null;
              if (args.length > 0) {
                if (isPairListLike(args[args.length - 1])) {
                  namedArgs = args[args.length - 1];
                  if (args.length > 1) {
                    source = args[0];
                  }
                } else {
                  source = args[0];
                }
              }
              return context.__zuzu_prepare_eval(source, namedArgs);
            },
            __zuzu_await_block_sync(value) {
              return taskRuntime2.awaitBlockSync(value);
            },
            __zuzu_iter(value) {
              const asIterable = (input) => {
                const hasMethodHere = (candidate, name2) => {
                  if (candidate == null) {
                    return false;
                  }
                  if (Object.prototype.hasOwnProperty.call(candidate, name2)) {
                    return true;
                  }
                  const proto = Object.getPrototypeOf(candidate);
                  if (!proto) {
                    return false;
                  }
                  return Object.prototype.hasOwnProperty.call(proto, name2);
                };
                if (input == null) {
                  return [];
                }
                if (input instanceof ZuzuBinary) {
                  return Array.from(input.bytes, (byte) => new BinaryString2([byte]));
                }
                if (typeof input === "string" || input instanceof String) {
                  return Array.from(String(input));
                }
                if (typeof input[Symbol.iterator] === "function") {
                  return input;
                }
                if (typeof input === "function") {
                  return {
                    *[Symbol.iterator]() {
                      while (true) {
                        try {
                          yield input();
                        } catch (err) {
                          if (isExhaustedIteratorError(err)) {
                            return;
                          }
                          throw err;
                        }
                      }
                    }
                  };
                }
                if (input && typeof input.to_Iterator === "function" && hasMethodHere(input, "to_Iterator")) {
                  const iterator = input.to_Iterator();
                  if (typeof iterator === "function" && input && typeof input === "object") {
                    return asIterable(iterator.bind(input));
                  }
                  return asIterable(iterator);
                }
                if (input && typeof input.to_Array === "function" && hasMethodHere(input, "to_Array")) {
                  return asIterable(input.to_Array());
                }
                if (isPlainObjectLike(input) && typeof input.to_Iterator === "function") {
                  return asIterable(input.to_Iterator());
                }
                if (isPlainObjectLike(input) && typeof input.to_Array === "function") {
                  return asIterable(input.to_Array());
                }
                if (input && typeof input === "object") {
                  return Object.keys(input).sort();
                }
                return [];
              };
              return asIterable(value);
            },
            __zuzu_length: operatorLength,
            __zuzu_num(value) {
              return zuzuToNumber(value);
            },
            __zuzu_truthy(value) {
              return zuzuTruthy(value);
            },
            __zuzu_not(value) {
              return !zuzuTruthy(value);
            },
            __zuzu_and(left, right) {
              return zuzuTruthy(left) && zuzuTruthy(right);
            },
            __zuzu_or(left, right) {
              return zuzuTruthy(left) || zuzuTruthy(right);
            },
            __zuzu_typeof(value) {
              return zuzuTypeof(value);
            },
            __zuzu_instanceof(value, klass) {
              return zuzuInstanceof(value, klass);
            },
            __zuzu_trait(name2, methods, source = null, captures = {}) {
              return zuzuTrait(name2, methods, source, captures);
            },
            __zuzu_apply_traits(klass, traits) {
              return zuzuApplyTraits(klass, traits);
            },
            __zuzu_class_with_traits(klass, traits) {
              return zuzuClassWithTraits(klass, traits);
            },
            __zuzu_does(value, trait) {
              return zuzuDoes(value, trait);
            },
            __zuzu_can(value, methodName) {
              return zuzuCan(value, methodName);
            },
            __zuzu_super_call(self, klass, methodName, args) {
              return zuzuSuperCall(self, klass, methodName, args);
            },
            __zuzu_super_static_call(klass, methodName, args) {
              return zuzuSuperStaticCall(klass, methodName, args);
            },
            __zuzu_super_dispatch(isStatic, self, klass, methodName, args) {
              return zuzuSuperDispatch(isStatic, self, klass, methodName, args);
            },
            __zuzu_type_matches(value, typeName2) {
              return zuzuTypeMatches(value, typeName2);
            },
            __zuzu_require_type(argName, typeName2, value) {
              if (!zuzuTypeMatches(value, typeName2)) {
                throw new Error(`TypeException: argument '${argName}' must be ${typeName2}, got ${zuzuTypeof(value)}`);
              }
              return value;
            },
            __zuzu_checked_declaration(name2, typeName2, value) {
              if (typeName2 !== "Any" && !zuzuTypeMatches(value, typeName2)) {
                throw new Error(`TypeException: '${name2}' must be ${typeName2}, got ${zuzuTypeof(value)}`);
              }
              return value;
            },
            __zuzu_checked_return(fnName, typeName2, value) {
              if (typeName2 !== "Any" && !zuzuTypeMatches(value, typeName2)) {
                throw new Error(`TypeException: 'return value of '${fnName}'' must be ${typeName2}, got ${zuzuTypeof(value)}`);
              }
              return value;
            },
            __zuzu_die(value) {
              if (typeof value === "string") {
                throw new ZuzuException(value);
              }
              throw value;
            },
            __zuzu_throw(value, line) {
              const err = value instanceof Error || value && typeof value === "object" ? value : new ZuzuException(value);
              if (err.file == null) {
                err.file = filename;
              }
              if (err.line == null) {
                err.line = Number(line || 0);
              }
              throw err;
            },
            __zuzu_add(left, right) {
              return zuzuToNumber(left) + zuzuToNumber(right);
            },
            __zuzu_concat(left, right) {
              return concatValue(left, right);
            },
            __zuzu_binary_literal(value) {
              return binaryFromLiteral(value);
            },
            to_binary(value) {
              return toBinaryValue(value);
            },
            to_string(value) {
              return toStringValue(value);
            },
            is_ascii(value) {
              if (!(value instanceof ZuzuBinary)) {
                throw new Error(`TypeException: expected BinaryString for is_ascii, got ${zuzuTypeof(value)}`);
              }
              return value.isAscii();
            },
            __zuzu_bit_and(left, right) {
              return bitwiseAnd(left, right);
            },
            __zuzu_shift_left(left, right) {
              return shiftValue(left, right, true);
            },
            // The left operand is the divisor: a ∣ b tests b mod a.
            __zuzu_divides(left, right) {
              return zuzuToNumber(right) % zuzuToNumber(left) === 0;
            },
            __zuzu_ndivides(left, right) {
              return zuzuToNumber(right) % zuzuToNumber(left);
            },
            __zuzu_shift_right(left, right) {
              return shiftValue(left, right, false);
            },
            __zuzu_bit_or(left, right) {
              return bitwiseOr(left, right);
            },
            __zuzu_bit_xor(left, right) {
              return bitwiseXor(left, right);
            },
            __zuzu_bit_not(value) {
              return bitwiseNot(value);
            },
            __zuzu_sub(left, right) {
              return zuzuToNumber(left) - zuzuToNumber(right);
            },
            __zuzu_mul(left, right) {
              return zuzuToNumber(left) * zuzuToNumber(right);
            },
            __zuzu_div(left, right) {
              return zuzuToNumber(left) / zuzuToNumber(right);
            },
            __zuzu_mod(left, right) {
              return zuzuToNumber(left) % zuzuToNumber(right);
            },
            __zuzu_pow(left, right) {
              return zuzuToNumber(left) ** zuzuToNumber(right);
            },
            __zuzu_cmp(left, right) {
              const l = zuzuToNumber(left);
              const r = zuzuToNumber(right);
              return l < r ? -1 : l > r ? 1 : 0;
            },
            __zuzu_eq(left, right) {
              if (arguments.length < 2) {
                return 0;
              }
              return zuzuEqual(left, right);
            },
            __zuzu_ne(left, right) {
              if (arguments.length < 2) {
                return 0;
              }
              return zuzuEqual(left, right) ? 0 : 1;
            },
            __zuzu_str_eq(left, right) {
              return stringCompare(left, right) === 0 ? 1 : 0;
            },
            __zuzu_str_ne(left, right) {
              return stringCompare(left, right) !== 0 ? 1 : 0;
            },
            __zuzu_str_gt(left, right) {
              return stringCompare(left, right) > 0 ? 1 : 0;
            },
            __zuzu_str_ge(left, right) {
              return stringCompare(left, right) >= 0 ? 1 : 0;
            },
            __zuzu_str_lt(left, right) {
              return stringCompare(left, right) < 0 ? 1 : 0;
            },
            __zuzu_str_le(left, right) {
              return stringCompare(left, right) <= 0 ? 1 : 0;
            },
            __zuzu_str_cmp(left, right) {
              return stringCompare(left, right);
            },
            __zuzu_str_eqi(left, right) {
              return stringCompare(left, right, { insensitive: true }) === 0 ? 1 : 0;
            },
            __zuzu_str_nei(left, right) {
              return stringCompare(left, right, { insensitive: true }) !== 0 ? 1 : 0;
            },
            __zuzu_str_gti(left, right) {
              return stringCompare(left, right, { insensitive: true }) > 0 ? 1 : 0;
            },
            __zuzu_str_gei(left, right) {
              return stringCompare(left, right, { insensitive: true }) >= 0 ? 1 : 0;
            },
            __zuzu_str_lti(left, right) {
              return stringCompare(left, right, { insensitive: true }) < 0 ? 1 : 0;
            },
            __zuzu_str_lei(left, right) {
              return stringCompare(left, right, { insensitive: true }) <= 0 ? 1 : 0;
            },
            __zuzu_str_cmpi(left, right) {
              return stringCompare(left, right, { insensitive: true });
            },
            __zuzu_warn(...parts) {
              emitStderr(parts.map((part) => zuzuStringify(part)).join(""));
            },
            __zuzu_debug(levelThunk, messageThunk) {
              const level = typeof levelThunk === "function" ? levelThunk() : levelThunk;
              if (Number(level || 0) > runtime.debugLevel) {
                return null;
              }
              const message = typeof messageThunk === "function" ? messageThunk() : messageThunk;
              emitStderr(zuzuStringify(message ?? ""));
              return null;
            },
            __zuzu_assert(conditionThunk) {
              if (runtime.debugLevel <= 0) {
                return null;
              }
              const condition = typeof conditionThunk === "function" ? conditionThunk() : conditionThunk;
              if (!condition) {
                throw new Error("Assertion failed");
              }
              return condition;
            },
            __zuzu_make_class(name2, base) {
              const parent = typeof base === "function" ? base : Object;
              return {
                [name2]: class extends parent {
                  constructor(...args) {
                    if (args.length === 1 && args[0] && typeof args[0] === "object" && !Array.isArray(args[0]) && Object.prototype.hasOwnProperty.call(args[0], "message")) {
                      super(args[0].message);
                      if (this instanceof Error) {
                        this.name = name2;
                      }
                      return;
                    }
                    super(...args);
                    if (this instanceof Error) {
                      this.name = name2;
                    }
                  }
                }
              }[name2];
            },
            __zuzu_define_class(name2, base, spec) {
              return defineZuzuClass(name2, base, spec);
            },
            __zuzu_get_member(object, property) {
              return zuzuGetMember(object, property);
            },
            __zuzu_get_index(object, index) {
              return zuzuGetIndex(object, index);
            },
            __zuzu_get_brace_member(object, literalProperty, getDynamicProperty) {
              return zuzuGetBraceMember(object, literalProperty, getDynamicProperty);
            },
            __zuzu_resolve_brace_key(object, literalProperty, getDynamicProperty) {
              return zuzuResolveBraceKey(object, literalProperty, getDynamicProperty);
            },
            __zuzu_maybe_demolish(value, preserved = null) {
              return zuzuMaybeDemolish(value, preserved);
            },
            __zuzu_xor(left, right) {
              return zuzuTruthy(left) !== zuzuTruthy(right);
            },
            __zuzu_nand(left, right) {
              return !(zuzuTruthy(left) && zuzuTruthy(right));
            },
            __zuzu_num_eq(left, right) {
              if (!isNumericComparable(left) || !isNumericComparable(right)) {
                return zuzuEqual(left, right);
              }
              return numericEqual(left, right) ? 1 : 0;
            },
            __zuzu_num_ne(left, right) {
              if (!isNumericComparable(left) || !isNumericComparable(right)) {
                return zuzuEqual(left, right) ? 0 : 1;
              }
              return numericEqual(left, right) ? 0 : 1;
            },
            __zuzu_num_lt(left, right) {
              return zuzuToNumber(left) < zuzuToNumber(right) ? 1 : 0;
            },
            __zuzu_num_lte(left, right) {
              return zuzuToNumber(left) <= zuzuToNumber(right) ? 1 : 0;
            },
            __zuzu_num_gt(left, right) {
              return zuzuToNumber(left) > zuzuToNumber(right) ? 1 : 0;
            },
            __zuzu_num_gte(left, right) {
              return zuzuToNumber(left) >= zuzuToNumber(right) ? 1 : 0;
            },
            __zuzu_abs(value) {
              return Math.abs(zuzuToNumber(value));
            },
            __zuzu_sqrt(value) {
              return Math.sqrt(zuzuToNumber(value));
            },
            __zuzu_floor(value) {
              return Math.floor(zuzuToNumber(value));
            },
            __zuzu_ceil(value) {
              return Math.ceil(zuzuToNumber(value));
            },
            __zuzu_round(value) {
              const n = zuzuToNumber(value);
              return n >= 0 ? Math.floor(n + 0.5) : Math.ceil(n - 0.5);
            },
            __zuzu_int(value) {
              const n = zuzuToNumber(value);
              return n < 0 ? Math.ceil(n) : Math.floor(n);
            },
            __zuzu_uc(value) {
              if (value instanceof ZuzuBinary) {
                throw new Error("TypeException: uc expects String, got BinaryString");
              }
              return zuzuOperatorString(value).toUpperCase();
            },
            __zuzu_lc(value) {
              if (value instanceof ZuzuBinary) {
                throw new Error("TypeException: lc expects String, got BinaryString");
              }
              return zuzuOperatorString(value).toLowerCase();
            },
            __zuzu_range(start, end) {
              const from = zuzuToNumber(start);
              const to = zuzuToNumber(end);
              const out = [];
              const step = from <= to ? 1 : -1;
              for (let n = from; step > 0 ? n <= to : n >= to; n += step) {
                out.push(n);
              }
              return out;
            },
            __zuzu_ref_index(target, index) {
              return refIndex(target, index);
            },
            __zuzu_ref_key(target, key) {
              return refKey(target, key);
            },
            __zuzu_get_slice(target, from, length) {
              return zuzuGetSlice(target, from, length);
            },
            __zuzu_ref_slice(target, from, length) {
              return refSlice(target, from, length);
            },
            __zuzu_assign_slice(target, from, length, value) {
              return zuzuAssignSlice(target, from, length, value);
            },
            Pair
          };
          if (this.host.name === "browser") {
            context.Object = createObjectFacade();
          }
          context.__zuzu_push_eval_capability_overrides = (overrides = {}) => {
            const previous = this.evalCapabilityOverrides;
            const next = { ...previous || {} };
            for (const [key, value] of Object.entries(overrides || {})) {
              if (value) {
                next[key] = true;
              }
            }
            this.evalCapabilityOverrides = Object.keys(next).length > 0 ? next : null;
            return previous;
          };
          context.__zuzu_pop_eval_capability_overrides = (previous) => {
            this.evalCapabilityOverrides = previous || null;
          };
          context.__zuzu_import = (name2) => {
            if (name2 === "std/eval") {
              return { eval: context.__zuzu_native_eval };
            }
            if (this.usesAsyncImports()) {
              return this.loadModuleAsync(name2, filename, context);
            }
            return this.loadModule(name2, filename, context);
          };
          return context;
        }
        installCollectionMethods(context) {
          const bootstrap = `
			(function () {
				globalThis.__zuzu_native_eval = eval;
				globalThis.__zuzu_builtin_Array = Array;
				globalThis.__zuzu_builtin_Function = Function;
				globalThis.__zuzu_builtin_Object = Object;
				globalThis.__zuzu_builtin_RegExp = RegExp;
				globalThis.__zuzu_builtin_Set = Set;
				globalThis.Dict = function Dict( value ) {
					if ( value && typeof value === 'object' && !Array.isArray( value ) ) {
						return Object.assign( {}, value );
					}
					return {};
				};
				if ( !globalThis.__zuzu_define_property_patched ) {
					const __zuzu_native_define_property = Object.defineProperty;
					const __zuzu_native_define_properties = Object.defineProperties;
					const __zuzu_safe_descriptor = function ( descriptor ) {
						if ( !descriptor || typeof descriptor !== 'object' ) {
							return descriptor;
						}
						const safe = Object.create( null );
						for ( const key of [ 'value', 'get', 'set', 'writable', 'enumerable', 'configurable' ] ) {
							if ( Object.prototype.hasOwnProperty.call( descriptor, key ) ) {
								safe[key] = descriptor[key];
							}
						}
						return safe;
					};
					Object.defineProperty = function __zuzu_define_property( obj, prop, descriptor ) {
						return __zuzu_native_define_property(
							obj,
							prop,
							__zuzu_safe_descriptor( descriptor )
						);
					};
					Object.defineProperties = function __zuzu_define_properties( obj, descriptors ) {
						const safeDescriptors = Object.create( null );
						for ( const key of Object.keys( descriptors || {} ) ) {
							safeDescriptors[key] = __zuzu_safe_descriptor( descriptors[key] );
						}
						return __zuzu_native_define_properties( obj, safeDescriptors );
					};
					globalThis.__zuzu_define_property_patched = true;
				}
				const __zuzu_seed = globalThis.__zuzu_system_seed || Object.create( null );
				const __zuzu_system_desc = Object.create( null );
				__zuzu_system_desc.get = function __zuzu_get_system() {
					if ( typeof globalThis.__zuzu_current_system === 'function' ) {
						return globalThis.__zuzu_current_system();
					}
					return Object.freeze( Object.assign( {}, __zuzu_seed ) );
				};
				__zuzu_system_desc.enumerable = true;
				__zuzu_system_desc.configurable = true;
				Object.defineProperty(
					globalThis,
					'__system__',
					__zuzu_system_desc
				);
				delete globalThis.__zuzu_system_seed;
				const define = ( proto, name, fn ) => {
					if ( !Object.prototype.hasOwnProperty.call( proto, name ) ) {
						const desc = Object.create( null );
						desc.value = fn;
						desc.enumerable = false;
						desc.configurable = true;
						desc.writable = true;
						Object.defineProperty( proto, name, desc );
					}
				};
				if ( Array.prototype.join.__zuzu_array_join !== true ) {
					const __zuzu_native_array_join = Array.prototype.join;
					const joinDesc = Object.create( null );
					joinDesc.value = function _join( separator, fallback ) {
						const hasFallback = arguments.length > 1;
						let fallbackString;
						const sep = __zuzu_operator_string( separator );
						const out = [];
						for ( const value of this ) {
							try {
								out.push( __zuzu_operator_string( value ) );
							}
							catch ( err ) {
								if ( !hasFallback ) {
									throw err;
								}
								if ( typeof fallback === 'function' ) {
									out.push( __zuzu_operator_string( fallback( value ) ) );
								}
								else {
									if ( fallbackString === undefined ) {
										fallbackString = __zuzu_operator_string( fallback );
									}
									out.push( fallbackString );
								}
							}
						}
						return __zuzu_native_array_join.call( out, sep );
					};
					joinDesc.value.__zuzu_array_join = true;
					joinDesc.enumerable = false;
					joinDesc.configurable = true;
					joinDesc.writable = true;
					Object.defineProperty( Array.prototype, 'join', joinDesc );
				}
				define( Array.prototype, 'length', function _length() { return this.length; } );
				define( Array.prototype, 'count', function _count() { return this.length; } );
				define( Array.prototype, 'empty', function _empty() { return this.length === 0 ? 1 : 0; } );
				define( Array.prototype, 'is_empty', function _is_empty() { return this.empty(); } );
				define( Array.prototype, 'append', function _append( ...values ) { this.push( ...values.map( ( value ) => __zuzu_retain_collection_value( this, value ) ) ); return this; } );
				define( Array.prototype, 'add', function _add( ...values ) { this.push( ...values.map( ( value ) => __zuzu_retain_collection_value( this, value ) ) ); return this; } );
				define( Array.prototype, 'prepend', function _prepend( ...values ) { this.unshift( ...values.map( ( value ) => __zuzu_retain_collection_value( this, value ) ) ); return this; } );
				define( Array.prototype, 'push_weak', function _push_weak( ...values ) { this.push( ...values.map( __zuzu_make_weak_value ) ); return this; } );
				define( Array.prototype, 'unshift_weak', function _unshift_weak( ...values ) { this.unshift( ...values.map( __zuzu_make_weak_value ) ); return this; } );
				define( Array.prototype, 'get', function _get( idx, fallback = null ) { return idx >= 0 && idx < this.length ? this[idx] : fallback; } );
				define( Array.prototype, 'set', function _set( idx, value ) { __zuzu_release_collection_value( this, this[idx] ); this[idx] = __zuzu_retain_collection_value( this, value ); return this; } );
				define( Array.prototype, 'set_weak', function _set_weak( idx, value ) { __zuzu_release_collection_value( this, this[idx] ); this[idx] = __zuzu_make_weak_value( value ); return this; } );
				define( Array.prototype, 'grep', function _grep( fn ) { return this.filter( fn ); } );
				define( Array.prototype, 'any', function _any( fn ) { return this.some( fn ) ? 1 : 0; } );
				define( Array.prototype, 'all', function _all( fn ) { return this.every( fn ) ? 1 : 0; } );
				define( Array.prototype, 'first', function _first( fn ) { return this.find( fn ) ?? null; } );
				define( Array.prototype, 'remove', function _remove( fn ) { for ( let i = this.length - 1; i >= 0; i-- ) { if ( fn( this[i] ) ) { __zuzu_release_collection_value( this, this[i] ); this.splice( i, 1 ); } } return this; } );
				define( Array.prototype, 'contains', function _contains( value ) { return this.includes( value ) ? 1 : 0; } );
				define( Array.prototype, 'first_index', function _first_index( fn ) { return this.findIndex( fn ); } );
				define( Array.prototype, 'reductions', function _reductions( fn ) { const out = []; for ( const item of this ) { out.push( out.length === 0 ? item : fn( out[out.length - 1], item ) ); } return out; } );
				define( Array.prototype, 'head', function _head( n ) { return this.slice( 0, n ); } );
				define( Array.prototype, 'tail', function _tail( n ) { return this.slice( n - 1 ); } );
				define( Array.prototype, 'sum', function _sum() { return this.reduce( (a, b) => Number( a ) + Number( b ), 0 ); } );
				define( Array.prototype, 'product', function _product() { return this.reduce( (a, b) => Number( a ) * Number( b ), 1 ); } );
				define( Array.prototype, 'shuffle', function _shuffle() { return this.slice(); } );
				define( Array.prototype, 'sample', function _sample( n ) { return this.slice( 0, n ); } );
				define( Array.prototype, 'for_each_value', function _for_each_value( fn ) { this.forEach( fn ); return this; } );
				define( Array.prototype, 'sortstr', function _sortstr() { return this.slice().sort( stringSortComparator ); } );
				define( Array.prototype, 'sortnum', function _sortnum() { return this.map( (item) => Number( item ) ).sort( (a, b) => a - b ); } );
				define( Array.prototype, 'to_Array', function _to_array() { return __zuzu_array( this ); } );
				define( Array.prototype, 'to_Set', function _to_set() { return __zuzu_set( this ); } );
				define( Array.prototype, 'to_Bag', function _to_bag() { return new Bag( this ); } );
				define( Array.prototype, 'to_Iterator', function _to_iterator() { return this[Symbol.iterator](); } );
				define( Array.prototype, 'copy', function _copy() { return __zuzu_array( this ); } );
				define( Array.prototype, 'clear', function _clear() { __zuzu_release_collection_values( this ); this.splice( 0, this.length ); return this; } );

				define( Set.prototype, 'length', function _length() { return this.size; } );
				define( Set.prototype, 'count', function _count() { return this.size; } );
				define( Set.prototype, 'empty', function _empty() { return this.size === 0 ? 1 : 0; } );
				define( Set.prototype, 'is_empty', function _is_empty() { return this.empty(); } );
				define( Set.prototype, 'push', function _push( ...values ) { for ( const v of values ) { __zuzu_add_set_value( this, v ); } return this; } );
				define( Set.prototype, 'add_weak', function _add_weak( value ) { this.add( __zuzu_make_weak_value( value ) ); return this; } );
				define( Set.prototype, 'push_weak', function _push_weak( ...values ) { for ( const v of values ) { this.add( __zuzu_make_weak_value( v ) ); } return this; } );
				define( Set.prototype, 'contains', function _contains( value ) { return __zuzu_contains( this, value ); } );
				define( Set.prototype, 'remove', function _remove( value ) { const resolved = __zuzu_resolve_weak_value( value ); if ( this.delete( resolved ) ) { __zuzu_release_collection_value( this, resolved ); } return this; } );
				define( Set.prototype, 'to_Array', function _to_array() { return __zuzu_array( this ); } );
				define( Set.prototype, 'to_Bag', function _to_bag() { return __zuzu_bag( [ ...this ] ); } );
				define( Set.prototype, 'to_Iterator', function _to_iterator() { return this.values(); } );
				define( Set.prototype, 'copy', function _copy() { return __zuzu_set( this ); } );
				define( Set.prototype, 'union', function _union( other ) { return __zuzu_union( this, other ); } );
				define( Set.prototype, 'intersection', function _intersection( other ) { return __zuzu_intersection( this, other ); } );
				define( Set.prototype, 'difference', function _difference( other ) { return __zuzu_difference( this, other ); } );
				define( Set.prototype, 'symmetric_difference', function _symmetric_difference( other ) { return __zuzu_difference( this.union( other ), this.intersection( other ) ); } );
				define( Set.prototype, 'is_subset', function _is_subset( other ) { return __zuzu_subsetof( this, other ); } );
				define( Set.prototype, 'is_superset', function _is_superset( other ) { return __zuzu_supersetof( this, other ); } );
				define( Set.prototype, 'is_disjoint', function _is_disjoint( other ) { return this.intersection( other ).size === 0 ? 1 : 0; } );
				define( Set.prototype, 'equals', function _equals( other ) { return __zuzu_equivalentof( this, other ); } );
				define( Set.prototype, 'sort', function _sort( fn ) { return [ ...this ].sort( fn ); } );
				define( Set.prototype, 'sortstr', function _sortstr() { return [ ...this ].sort( stringSortComparator ); } );
				define( Set.prototype, 'sortnum', function _sortnum() { return [ ...this ].map( (item) => Number( item ) ).sort( (a, b) => a - b ); } );
				define( Set.prototype, 'map', function _map( fn ) { return new Set( [ ...this ].map( fn ) ); } );
				define( Set.prototype, 'grep', function _grep( fn ) { return new Set( [ ...this ].filter( fn ) ); } );
				define( Set.prototype, 'any', function _any( fn ) { return [ ...this ].some( fn ) ? 1 : 0; } );
				define( Set.prototype, 'all', function _all( fn ) { return [ ...this ].every( fn ) ? 1 : 0; } );
				define( Set.prototype, 'first', function _first( fn ) { for ( const v of this ) { if ( fn( v ) ) { return v; } } return null; } );
				define( Set.prototype, 'remove_if', function _remove_if( fn ) { for ( const v of [ ...this ] ) { if ( fn( v ) ) { __zuzu_release_collection_value( this, v ); this.delete( v ); } } return this; } );
				define( Set.prototype, 'for_each_value', function _for_each_value( fn ) { for ( const v of this ) { fn( v ); } return this; } );
				const clearSet = Set.prototype.clear;
				define( Set.prototype, 'clear', function _clear() { __zuzu_release_collection_values( this ); clearSet.call( this ); return this; } );
				define( RegExp.prototype, 'to_String', function _to_string() { return this.source; } );
				if ( !Object.prototype.hasOwnProperty.call( RegExp.prototype, Symbol.toPrimitive ) ) {
					const regDesc = Object.create( null );
					regDesc.value = function _regexp_to_primitive( hint ) {
						if ( hint === 'string' || hint === 'default' ) {
							return this.to_String();
						}
						return NaN;
					};
					regDesc.enumerable = false;
					regDesc.configurable = true;
					regDesc.writable = true;
					Object.defineProperty( RegExp.prototype, Symbol.toPrimitive, regDesc );
				}
				if ( !Object.prototype.hasOwnProperty.call( Object.prototype, Symbol.toPrimitive ) ) {
					const objectDesc = Object.create( null );
					objectDesc.value = function _object_to_primitive( hint ) {
						if ( ( hint === 'string' || hint === 'default' ) && typeof this.to_String === 'function' ) {
							return this.to_String();
						}
						const methods = hint === 'number'
							? [ 'valueOf', 'toString' ]
							: [ 'toString', 'valueOf' ];
						for ( const methodName of methods ) {
							const method = this[methodName];
							if ( typeof method !== 'function' ) {
								continue;
							}
							if ( methodName === 'toString' && method === Object.prototype.toString ) {
								continue;
							}
							if ( methodName === 'valueOf' && method === Object.prototype.valueOf ) {
								continue;
							}
							const value = method.call( this );
							if ( value == null || typeof value !== 'object' ) {
								return value;
							}
						}
						return Object.prototype.toString.call( this );
					};
					objectDesc.enumerable = false;
					objectDesc.configurable = true;
					objectDesc.writable = true;
					Object.defineProperty( Object.prototype, Symbol.toPrimitive, objectDesc );
				}

			})();
		`;
          const bootstrapRunOptions = {};
          if (this.executionTimeoutMs != null) {
            bootstrapRunOptions.timeout = this.executionTimeoutMs;
          }
          this.host.runInContext(bootstrap, context, bootstrapRunOptions);
        }
        loadModule(moduleName, fromFile, contextForPolicy = null) {
          if (/(^|\/)\.\.(\/|$)/.test(moduleName)) {
            throw new Error("Import module path cannot contain '..' segments");
          }
          this.enforceModulePolicy(moduleName);
          const resolved = this.resolveModulePath(moduleName, fromFile);
          const cacheable = moduleName !== "test/more" && this.evalCapabilityOverrides == null;
          if (cacheable && this.moduleCache.has(resolved)) {
            return this.moduleCache.get(resolved);
          }
          if (this.moduleLoading.has(resolved)) {
            throw new Error("Circular module loading detected");
          }
          if (resolved.endsWith(".js")) {
            const hiddenObjectPrototypeMethods = [];
            for (const name2 of ["get", "set"]) {
              const desc = Object.prototype.hasOwnProperty.call(Object.prototype, name2) ? Object.getOwnPropertyDescriptor(Object.prototype, name2) : null;
              if (desc && desc.configurable) {
                hiddenObjectPrototypeMethods.push([name2, desc]);
                delete Object.prototype[name2];
              }
            }
            let loaded;
            try {
              loaded = this.host.loadJsModule(resolved, moduleName, fromFile);
            } finally {
              for (const [name2, desc] of hiddenObjectPrototypeMethods) {
                Object.defineProperty(Object.prototype, name2, desc);
              }
            }
            if (loaded && typeof loaded.__zuzu_set_runtime_policy === "function") {
              const policy = {
                gui: this.host.gui || null,
                host_name: this.host.name,
                repo_root: this.repoRoot,
                include_paths: this.includePaths.slice(),
                deny_modules: [...this.denyModules],
                debug_level: this.debugLevel,
                transpiler: this.transpiler,
                load_module: (name2, requestFromFile = fromFile) => this.loadModule(
                  name2,
                  requestFromFile || fromFile,
                  contextForPolicy
                ),
                builtin_class: (name2) => {
                  if (!contextForPolicy) {
                    return null;
                  }
                  const builtins = {
                    Array: contextForPolicy.__zuzu_builtin_Array,
                    Bag: contextForPolicy.Bag,
                    Class: contextForPolicy.Class,
                    Dict: contextForPolicy.Dict || contextForPolicy.__zuzu_builtin_Object,
                    Function: contextForPolicy.__zuzu_builtin_Function,
                    Object: contextForPolicy.__zuzu_builtin_Object,
                    Pair: contextForPolicy.Pair,
                    PairList: contextForPolicy.PairList,
                    Regexp: contextForPolicy.__zuzu_builtin_RegExp,
                    Set: contextForPolicy.__zuzu_builtin_Set
                  };
                  return builtins[name2] || null;
                },
                to_String: (value) => zuzuOperatorString(value),
                to_Number: (value) => zuzuToNumber(value),
                to_Boolean: (value) => zuzuTruthy(value),
                to_Regexp: (value) => operatorRegexp(value),
                to_Regexp_with_flags: (value, flags) => {
                  const pattern = value instanceof RegExp ? value.source : zuzuOperatorString(value);
                  return new RegExp(pattern, zuzuOperatorString(flags));
                },
                stdout_write: (text) => {
                  if (typeof this.stdoutHandler === "function") {
                    this.stdoutHandler(String(text));
                  } else if (typeof process !== "undefined" && process.stdout) {
                    process.stdout.write(String(text));
                  } else {
                    this.host.consoleLog(String(text));
                  }
                },
                stderr_write: (text) => {
                  if (typeof this.stderrHandler === "function") {
                    this.stderrHandler(String(text));
                  } else if (typeof process !== "undefined" && process.stderr) {
                    process.stderr.write(String(text));
                  } else if (typeof console !== "undefined" && typeof console.warn === "function") {
                    console.warn(String(text));
                  }
                },
                browser_worker_source: this.host.workerSource || null,
                browser_worker_url: this.host.workerUrl || null,
                browser_worker_factory: this.host.workerFactory || null
              };
              for (const capability of [
                "fs",
                "net",
                "perl",
                "js",
                "proc",
                "db",
                "clib",
                "gui",
                "worker"
              ]) {
                policy[`deny_${capability}`] = this.isCapabilityDenied(capability) || !this.host.capabilities.has(capability);
              }
              loaded.__zuzu_set_runtime_policy(policy);
            }
            if (cacheable) {
              this.moduleCache.set(resolved, loaded);
            }
            return loaded;
          }
          const source = this.host.readFileText(resolved);
          let js = this.transpile(source);
          setCompiledSource(resolved, js);
          const exportNames = resolved.endsWith(".zzm") ? collectTopLevelDeclarations(source, stripPod) : [];
          if (exportNames.length > 0) {
            const exportBridge = exportNames.map((name2) => {
              if (name2.startsWith("_")) {
                return `if ( typeof ${name2} !== "undefined" ) { const __zuzu_desc = Object.create( null ); __zuzu_desc.get = function() { return ${name2}; }; __zuzu_desc.set = function( value ) { ${name2} = value; }; __zuzu_desc.enumerable = false; __zuzu_desc.configurable = true; Object.defineProperty( module.exports, ${JSON.stringify(name2)}, __zuzu_desc ); }`;
              }
              return `if ( typeof ${name2} !== "undefined" ) { const __zuzu_desc = Object.create( null ); __zuzu_desc.get = function() { return ${name2}; }; __zuzu_desc.set = function( value ) { ${name2} = value; }; __zuzu_desc.enumerable = true; __zuzu_desc.configurable = true; Object.defineProperty( module.exports, ${JSON.stringify(name2)}, __zuzu_desc ); }`;
            }).join("\n");
            js += `
${exportBridge}
`;
          }
          const moduleObj = { exports: {} };
          const context = this.buildContext({
            exports: moduleObj.exports,
            module: moduleObj,
            filename: resolved
          });
          context.__global__ = /* @__PURE__ */ Object.create(null);
          this.installCollectionMethods(context);
          const moduleRunOptions = { filename: resolved };
          if (this.executionTimeoutMs != null) {
            moduleRunOptions.timeout = this.executionTimeoutMs;
          }
          this.moduleLoading.add(resolved);
          try {
            this.host.runInContext(js, context, moduleRunOptions);
            if (cacheable) {
              this.moduleCache.set(resolved, moduleObj.exports);
            }
          } finally {
            this.moduleLoading.delete(resolved);
          }
          return moduleObj.exports;
        }
        async loadModuleAsync(moduleName, fromFile, contextForPolicy = null) {
          if (/(^|\/)\.\.(\/|$)/.test(moduleName)) {
            throw new Error("Import module path cannot contain '..' segments");
          }
          this.enforceModulePolicy(moduleName);
          const resolved = this.resolveModulePath(moduleName, fromFile);
          const cacheable = moduleName !== "test/more" && this.evalCapabilityOverrides == null;
          if (cacheable && this.moduleCache.has(resolved)) {
            return this.moduleCache.get(resolved);
          }
          if (resolved.endsWith(".js")) {
            return this.loadModule(moduleName, fromFile, contextForPolicy);
          }
          if (this.moduleLoading.has(resolved)) {
            throw new Error("Circular module loading detected");
          }
          this.moduleLoading.add(resolved);
          try {
            const source = typeof this.host.readFileTextAsync === "function" ? await this.host.readFileTextAsync(resolved) : this.host.readFileText(resolved);
            let js = this.transpile(source, {
              asyncImports: true,
              deferAsyncWrapper: true
            });
            const exportNames = resolved.endsWith(".zzm") ? collectTopLevelDeclarations(source, stripPod) : [];
            let exportBridge = "";
            if (exportNames.length > 0) {
              exportBridge = exportNames.map((name2) => {
                if (name2.startsWith("_")) {
                  return `if ( typeof ${name2} !== "undefined" ) { const __zuzu_desc = Object.create( null ); __zuzu_desc.get = function() { return ${name2}; }; __zuzu_desc.set = function( value ) { ${name2} = value; }; __zuzu_desc.enumerable = false; __zuzu_desc.configurable = true; Object.defineProperty( module.exports, ${JSON.stringify(name2)}, __zuzu_desc ); }`;
                }
                return `if ( typeof ${name2} !== "undefined" ) { const __zuzu_desc = Object.create( null ); __zuzu_desc.get = function() { return ${name2}; }; __zuzu_desc.set = function( value ) { ${name2} = value; }; __zuzu_desc.enumerable = true; __zuzu_desc.configurable = true; Object.defineProperty( module.exports, ${JSON.stringify(name2)}, __zuzu_desc ); }`;
              }).join("\n");
            }
            js = `( async () => {
${js}
${exportBridge}
} )()`;
            setCompiledSource(resolved, js);
            const moduleObj = { exports: {} };
            const context = this.buildContext({
              exports: moduleObj.exports,
              module: moduleObj,
              filename: resolved
            });
            context.__global__ = /* @__PURE__ */ Object.create(null);
            this.installCollectionMethods(context);
            const moduleRunOptions = { filename: resolved };
            if (this.executionTimeoutMs != null) {
              moduleRunOptions.timeout = this.executionTimeoutMs;
            }
            const result = this.host.runInContext(js, context, moduleRunOptions);
            if (result && typeof result.then === "function") {
              await result;
            }
            if (cacheable) {
              this.moduleCache.set(resolved, moduleObj.exports);
            }
            return moduleObj.exports;
          } finally {
            this.moduleLoading.delete(resolved);
          }
        }
        runSource(source, options = {}) {
          const filename = options.filename || this.host.join(this.repoRoot, "<inline>.zzs");
          let js;
          try {
            js = this.transpile(source);
          } catch (err) {
            const stderr = formatRuntimeError(err);
            if (typeof options.onStderr === "function") {
              options.onStderr(stderr);
            }
            return {
              status: 3,
              stdout: "",
              stderr
            };
          }
          return this.runCompiled(js, options);
        }
        runCompiled(js, options = {}) {
          const filename = options.filename || this.host.join(this.repoRoot, "<inline>.zzs");
          taskRuntime2.resetForRun(this.debugLevel);
          setCompiledSource(filename, js);
          const preloadGlobals = /* @__PURE__ */ Object.create(null);
          if (Array.isArray(options.preloadModules)) {
            for (const moduleName of options.preloadModules) {
              Object.assign(preloadGlobals, this.loadModule(moduleName, filename));
            }
          }
          this.outputLines = [];
          const previousStdoutHandler = this.stdoutHandler;
          const previousStderrHandler = this.stderrHandler;
          this.stdoutHandler = typeof options.onStdout === "function" ? options.onStdout : null;
          this.stderrHandler = typeof options.onStderr === "function" ? options.onStderr : null;
          const context = this.buildContext({
            filename,
            globals: preloadGlobals
          });
          context.__global__ = /* @__PURE__ */ Object.create(null);
          this.installCollectionMethods(context);
          const finishRun = () => {
            let topLevelTests = 0;
            let hasTopLevelPlan = false;
            for (const line of this.outputLines) {
              if (/^\d+\.\.\d+\s*$/.test(line)) {
                hasTopLevelPlan = true;
              }
              if (/^ok\b/.test(line) || /^not ok\b/.test(line)) {
                topLevelTests++;
              }
            }
            if (topLevelTests > 0 && !hasTopLevelPlan) {
              const stdout2 = this.outputLines.length > 0 ? `${this.outputLines.join("\n")}
` : "";
              const stderr = "Error: TAP plan missing (expected 1..N)\n";
              if (typeof this.stderrHandler === "function") {
                this.stderrHandler(stderr);
              }
              return {
                status: 1,
                stdout: stdout2,
                stderr
              };
            }
            const stdout = this.outputLines.length > 0 ? `${this.outputLines.join("\n")}
` : "";
            return {
              status: 0,
              stdout,
              stderr: ""
            };
          };
          const failRun = (err) => {
            const stdout = this.outputLines.length > 0 ? `${this.outputLines.join("\n")}
` : "";
            const isParse = err && err.name === "SyntaxError";
            const stderr = formatRuntimeError(err);
            if (typeof this.stderrHandler === "function") {
              this.stderrHandler(stderr);
            }
            return {
              status: isParse ? 3 : 1,
              stdout,
              stderr
            };
          };
          const cleanupRun = (result) => {
            taskRuntime2.shutdown("Task cancelled");
            this.outputLines = null;
            this.stdoutHandler = previousStdoutHandler;
            this.stderrHandler = previousStderrHandler;
            return result;
          };
          const invokeMain = () => {
            if (typeof context.__main__ !== "function") {
              return null;
            }
            const argv = Array.isArray(options.scriptArgs) ? options.scriptArgs.map((value) => String(value)) : [];
            const mainResult = context.__main__(argv);
            if (mainResult instanceof taskRuntime2.Task || mainResult && typeof mainResult.then === "function") {
              return taskRuntime2.awaitValue(mainResult);
            }
            return null;
          };
          try {
            const scriptRunOptions = { filename };
            if (this.executionTimeoutMs != null) {
              scriptRunOptions.timeout = this.executionTimeoutMs;
            }
            const topLevelResult = this.host.runInContext(js, context, scriptRunOptions);
            if (topLevelResult && typeof topLevelResult.then === "function") {
              return Promise.resolve(topLevelResult).then(invokeMain).then(finishRun, failRun).then(cleanupRun);
            }
            const mainResult = invokeMain();
            if (mainResult && typeof mainResult.then === "function") {
              return Promise.resolve(mainResult).then(finishRun, failRun).then(cleanupRun);
            }
            return cleanupRun(finishRun());
          } catch (err) {
            return cleanupRun(failRun(err));
          }
        }
        runFile(scriptPath) {
          const source = this.host.readFileText(scriptPath);
          return this.runSource(source, {
            filename: scriptPath,
            scriptArgs: []
          });
        }
      };
      module2.exports = {
        ZuzuScript,
        isWeakableValue,
        makeWeakValue,
        resolveWeakValue
      };
    }
  });

  // lib/browser-runtime.js
  var require_browser_runtime = __commonJS({
    "lib/browser-runtime.js"(exports2, module2) {
      "use strict";
      var { createBrowserHost } = require_browser_host();
      var { transpile } = require_transpiler();
      var { ZuzuScript } = require_runtime();
      function _extractLineColumn(errorText) {
        const match = String(errorText || "").match(/:(\d+):(\d+)\)?(?:\n|$)/u);
        if (!match) {
          return null;
        }
        return {
          line: Number(match[1]),
          column: Number(match[2])
        };
      }
      function _makeSnippet(source, line, column) {
        const lines = String(source || "").split(/\r?\n/u);
        if (!Number.isInteger(line) || line < 1 || line > lines.length) {
          return null;
        }
        const content = lines[line - 1];
        const caretColumn = Number.isInteger(column) && column > 0 ? column : 1;
        return `${content}
${" ".repeat(Math.max(0, caretColumn - 1))}^`;
      }
      function _toJsError(source, filename, result) {
        const stderr = String(result && result.stderr || "").trim();
        const message = stderr || `Zuzu evaluation failed (${filename})`;
        const err = new Error(message);
        err.name = result && result.status === 3 ? "ZuzuParseError" : "ZuzuRuntimeError";
        err.filename = filename;
        err.source = String(source || "");
        err.zuzu = {
          status: result ? result.status : 1,
          stdout: result ? result.stdout : "",
          stderr: result ? result.stderr : ""
        };
        const where = _extractLineColumn(stderr);
        if (where) {
          err.line = where.line;
          err.column = where.column;
          err.snippet = _makeSnippet(source, where.line, where.column);
        }
        return err;
      }
      function _coerceScalarOutput(stdout) {
        const lines = String(stdout || "").trimEnd().split(/\r?\n/u);
        if (lines.length !== 1) {
          return void 0;
        }
        const raw = lines[0];
        if (/^-?\d+(?:\.\d+)?$/u.test(raw)) {
          return Number(raw);
        }
        if (raw === "true" || raw === "1") {
          return true;
        }
        if (raw === "false" || raw === "0") {
          return false;
        }
        if (raw === "null") {
          return null;
        }
        return raw;
      }
      function createBrowserRuntime(options = {}) {
        const host = options.host || createBrowserHost(options);
        const runtime = options.runtime || new ZuzuScript({
          host,
          repoRoot: options.repoRoot || host.repoRoot || "/",
          includePaths: options.includePaths,
          denyCapabilities: options.denyCapabilities,
          allowCapabilities: options.allowCapabilities,
          denyModules: options.denyModules,
          debugLevel: options.debugLevel,
          executionTimeoutMs: options.executionTimeoutMs,
          transpiler: options.transpiler
        });
        function _runSource(source, evalOptions = {}) {
          const filename = evalOptions.filename || "/<browser>.zzs";
          return runtime.runSource(String(source ?? ""), {
            filename,
            preloadModules: evalOptions.preloadModules || []
          });
        }
        function zuzu_run(source, evalOptions = {}) {
          const result = _runSource(source, evalOptions);
          if (result && typeof result.then === "function") {
            return result.then((resolved) => {
              if (evalOptions.throwOnError !== false && resolved.status !== 0) {
                throw _toJsError(source, evalOptions.filename || "/<browser>.zzs", resolved);
              }
              return resolved;
            });
          }
          if (evalOptions.throwOnError !== false && result.status !== 0) {
            throw _toJsError(source, evalOptions.filename || "/<browser>.zzs", result);
          }
          return result;
        }
        function zuzu_eval(source, evalOptions = {}) {
          const sourceText = String(source ?? "");
          const filename = evalOptions.filename || "/<browser>.zzs";
          const run = () => {
            if (evalOptions.result === true) {
              return zuzu_run(sourceText, evalOptions);
            }
            const expressionResult = _runSource(`say( ${sourceText} );`, {
              ...evalOptions,
              filename
            });
            if (expressionResult && typeof expressionResult.then === "function") {
              return expressionResult.then((resolvedExpression) => {
                if (resolvedExpression.status === 0) {
                  return _coerceScalarOutput(resolvedExpression.stdout);
                }
                return Promise.resolve(zuzu_run(sourceText, evalOptions)).then((result2) => {
                  if (result2.stdout && evalOptions.returnStdout === true) {
                    return result2.stdout;
                  }
                  return void 0;
                });
              });
            }
            if (expressionResult.status === 0) {
              return _coerceScalarOutput(expressionResult.stdout);
            }
            const result = zuzu_run(sourceText, evalOptions);
            if (result.stdout && evalOptions.returnStdout === true) {
              return result.stdout;
            }
            return void 0;
          };
          if (evalOptions.async === true) {
            return Promise.resolve().then(run);
          }
          return run();
        }
        function zuzu_compile(source, _compileOptions = {}) {
          return transpile(String(source ?? ""), {
            transpiler: runtime.transpiler
          });
        }
        return {
          host,
          runtime,
          zuzu_eval,
          zuzu_run,
          zuzu_compile
        };
      }
      module2.exports = {
        createBrowserRuntime
      };
    }
  });

  // modules/std/marshal/graph.js
  var require_graph = __commonJS({
    "modules/std/marshal/graph.js"(exports2, module2) {
      "use strict";
      var {
        BinaryString: BinaryString2,
        ZuzuBinary,
        ZuzuBag,
        Pair,
        PairList,
        isPairListLike,
        isWeakCell,
        makeWeakValue,
        retainCollectionValue,
        retainValue,
        resolveWeakValue
      } = require_runtime_helpers();
      var cbor = require_cbor();
      var KIND_PAIR = 1;
      var KIND_ARRAY = 2;
      var KIND_DICT = 3;
      var KIND_PAIRLIST = 4;
      var KIND_SET = 5;
      var KIND_BAG = 6;
      var KIND_OBJECT = 7;
      var KIND_FUNCTION = 8;
      var KIND_CLASS = 9;
      var KIND_TRAIT = 10;
      var KIND_BOUND_METHOD = 11;
      var KIND_TIME = 12;
      var KIND_PATH = 13;
      var CODE_FUNCTION = 1;
      var CODE_CLASS = 2;
      var CODE_TRAIT = 3;
      var MAX_SAFE_INTEGER = 9007199254740991;
      var classRegistry = /* @__PURE__ */ new Map();
      var codeRegistry = /* @__PURE__ */ new Map();
      var runtimePolicy2 = {
        host_name: "node",
        repo_root: null,
        include_paths: [],
        deny_modules: [],
        debug_level: 0,
        transpiler: null
      };
      function setRuntimePolicy2(policy = {}) {
        runtimePolicy2 = {
          ...runtimePolicy2,
          ...policy,
          include_paths: Array.isArray(policy.include_paths) ? policy.include_paths.slice() : runtimePolicy2.include_paths,
          deny_modules: Array.isArray(policy.deny_modules) ? policy.deny_modules.slice() : runtimePolicy2.deny_modules
        };
      }
      function dumpGraph(value) {
        const state = {
          objects: [],
          ids: /* @__PURE__ */ new WeakMap(),
          code: [],
          codeIds: /* @__PURE__ */ new WeakMap(),
          onDump: /* @__PURE__ */ new WeakSet()
        };
        const root = encodeValue(value, state);
        return cbor.encodeOne(
          cbor.tag(cbor.SELF_DESCRIBED_TAG, [
            cbor.textString("ZUZU-MARSHAL"),
            1,
            /* @__PURE__ */ new Map(),
            root,
            state.objects,
            state.code
          ])
        );
      }
      function loadGraph(blob) {
        if (!(blob instanceof BinaryString2)) {
          throw new Error(
            `TypeException: std/marshal.load expects BinaryString, got ${typeName2(blob)}`
          );
        }
        const decoded = cbor.decodeOne(blob);
        const envelope = decodeEnvelope(decoded);
        const codeValues = loadCodeTable(envelope.code);
        const placeholders = allocatePlaceholders(envelope.objects, codeValues);
        fillPlaceholders(envelope.objects, placeholders);
        const value = decodeValue(envelope.root, placeholders, {
          allowWeak: false,
          context: "Envelope root"
        });
        runOnLoadHooks(envelope.objects, placeholders);
        return value;
      }
      function safeToDumpGraph(value) {
        try {
          dumpGraph(value);
          return true;
        } catch (_err) {
          return false;
        }
      }
      function encodeValue(value, state) {
        if (isWeakCell(value)) {
          return [1, encodeValue(resolveWeakValue(value), state)];
        }
        if (value == null) {
          return null;
        }
        if (typeof value === "boolean") {
          return value;
        }
        if (typeof value === "number") {
          return encodeNumber(value);
        }
        if (typeof value === "string") {
          return cbor.textString(value);
        }
        if (value instanceof ZuzuBinary) {
          return cbor.byteString(value.bytes);
        }
        if (isBoundMethodValue(value)) {
          return encodeBoundMethod(value, state);
        }
        if (isUserClassValue(value)) {
          return encodeClassReference(value, state);
        }
        if (isTraitValue(value)) {
          return encodeTraitReference(value, state);
        }
        if (isFunctionValue(value)) {
          return encodeFunctionReference(value, state);
        }
        if (value instanceof Pair) {
          return encodeObjectTableValue(value, KIND_PAIR, state, encodePairPayload);
        }
        if (Array.isArray(value)) {
          return encodeObjectTableValue(value, KIND_ARRAY, state, encodeArrayPayload);
        }
        if (isPairListLike(value)) {
          return encodeObjectTableValue(
            value,
            KIND_PAIRLIST,
            state,
            encodePairListPayload
          );
        }
        if (value instanceof Set) {
          return encodeObjectTableValue(value, KIND_SET, state, encodeSetPayload);
        }
        if (value instanceof ZuzuBag) {
          return encodeObjectTableValue(value, KIND_BAG, state, encodeBagPayload);
        }
        if (isTimeValue(value)) {
          return encodeObjectTableValue(value, KIND_TIME, state, encodeTimePayload);
        }
        if (isPathValue(value)) {
          return encodeObjectTableValue(value, KIND_PATH, state, encodePathPayload);
        }
        if (isPlainDict(value)) {
          return encodeObjectTableValue(value, KIND_DICT, state, encodeDictPayload);
        }
        if (isUserObjectValue(value)) {
          return encodeUserObject(value, state);
        }
        throw new Error(`Value of type ${typeName2(value)} is not marshalable in this phase`);
      }
      function encodeNumber(value) {
        if (!Number.isFinite(value)) {
          throw new Error("Number values must be finite");
        }
        if (!Object.is(value, -0) && Number.isInteger(value) && Math.abs(value) <= MAX_SAFE_INTEGER) {
          return value;
        }
        return Number(value);
      }
      function encodeObjectTableValue(value, kind, state, payloadEncoder) {
        if (state.ids.has(value)) {
          return [0, state.ids.get(value)];
        }
        const id = state.objects.length;
        state.ids.set(value, id);
        state.objects.push(null);
        state.objects[id] = [kind, payloadEncoder(value, state)];
        return [0, id];
      }
      function encodeArrayPayload(value, state) {
        return value.map((item) => encodeValue(item, state));
      }
      function encodeDictPayload(value, state) {
        return Object.keys(value).sort().map((key) => [
          cbor.textString(key),
          encodeValue(value[key], state)
        ]);
      }
      function encodePairListPayload(value, state) {
        return value.list.map((pair) => [
          cbor.textString(pair[0]),
          encodeValue(pair[1], state)
        ]);
      }
      function encodeSetPayload(value, state) {
        return [...value].map((item) => encodeValue(item, state));
      }
      function encodeBagPayload(value, state) {
        return value.items.map((item) => encodeValue(item, state));
      }
      function encodePairPayload(value, state) {
        return [
          cbor.textString(value.key()),
          encodeValue(value.value(), state)
        ];
      }
      function encodeTimePayload(value, _state) {
        const epoch = typeof value.epoch === "function" ? value.epoch() : value._epoch;
        if (typeof epoch !== "number" || !Number.isFinite(epoch)) {
          throw new Error("Time value has invalid internal epoch");
        }
        const zone = typeof value.timezone === "function" ? value.timezone().to_String() : value._timezone;
        if (zone == null) {
          return [encodeNumber(epoch)];
        }
        return [encodeNumber(epoch), cbor.textString(String(zone))];
      }
      function encodePathPayload(value, _state) {
        const pathText = typeof value.to_String === "function" ? value.to_String() : value.value;
        if (pathText == null) {
          throw new Error("Path value has invalid internal path");
        }
        return [cbor.textString(pathText)];
      }
      function encodeUserObject(value, state) {
        if (state.ids.has(value)) {
          return [0, state.ids.get(value)];
        }
        if (!state.onDump.has(value)) {
          state.onDump.add(value);
          if (typeof value.__on_dump__ === "function") {
            try {
              value.__on_dump__();
            } catch (err) {
              throw new Error(
                `__on_dump__ for ${typeName2(value)} failed: ${err.message || err}`
              );
            }
          }
        }
        const id = state.objects.length;
        state.ids.set(value, id);
        state.objects.push(null);
        const slots = Object.keys(value).filter((key) => isMarshalableObjectSlot(value[key])).sort().map((key) => [
          cbor.textString(key),
          encodeValue(value[key], state)
        ]);
        state.objects[id] = [
          KIND_OBJECT,
          [
            encodeClassReference(value.constructor, state),
            slots
          ]
        ];
        return [0, id];
      }
      function encodeBoundMethod(value, state) {
        if (state.ids.has(value)) {
          return [0, state.ids.get(value)];
        }
        const receiver = value.__zuzu_bound_receiver || value.receiver || null;
        const methodName = value.__zuzu_bound_method_name || value.name;
        if (!receiver || !methodName) {
          throw new Error("Bound method values are not marshalable in this phase");
        }
        const id = state.objects.length;
        state.ids.set(value, id);
        state.objects.push(null);
        state.objects[id] = [
          KIND_BOUND_METHOD,
          [
            encodeValue(receiver, state),
            cbor.textString(methodName)
          ]
        ];
        return [0, id];
      }
      function encodeFunctionReference(fn2, state) {
        return encodeCodeBackedObject(fn2, KIND_FUNCTION, state, encodeFunctionCode);
      }
      function encodeTraitReference(trait, state) {
        return encodeCodeBackedObject(trait, KIND_TRAIT, state, encodeTraitCode);
      }
      function encodeCodeBackedObject(value, kind, state, codeEncoder) {
        if (state.ids.has(value)) {
          return [0, state.ids.get(value)];
        }
        const id = state.objects.length;
        state.ids.set(value, id);
        state.objects.push(null);
        const codeId = codeEncoder(value, state);
        state.objects[id] = [kind, [codeId]];
        return [0, id];
      }
      function encodeClassReference(klass, state) {
        if (!isUserClassValue(klass)) {
          throw new Error("Object class is not marshalable in this phase");
        }
        return encodeCodeBackedObject(klass, KIND_CLASS, state, encodeClassCode);
      }
      function encodeClassCode(klass, state) {
        if (!klass.__zuzu_marshal_meta) {
          Object.defineProperty(klass, "__zuzu_marshal_meta", {
            value: {
              kind: "class",
              name: klass.__zuzu_class_name || klass.name,
              source: marshalClassSource(klass, klass.__zuzu_class_name || klass.name),
              captures: {}
            },
            enumerable: false,
            configurable: true,
            writable: true
          });
        }
        return encodeCodeRecord(klass, state, CODE_CLASS);
      }
      function encodeFunctionCode(fn2, state, preferredName = null) {
        return encodeCodeRecord(fn2, state, CODE_FUNCTION, preferredName);
      }
      function encodeTraitCode(trait, state, preferredName = null) {
        return encodeCodeRecord(trait, state, CODE_TRAIT, preferredName);
      }
      function encodeCodeRecord(value, state, kind, preferredName = null) {
        if (state.codeIds.has(value)) {
          return state.codeIds.get(value);
        }
        const meta = value.__zuzu_marshal_meta || {};
        if (!meta.source) {
          throw new Error(`Value of type ${typeName2(value)} is not marshalable in this phase`);
        }
        const id = state.code.length;
        state.codeIds.set(value, id);
        state.code.push(null);
        const bindingName = marshalBindingName(preferredName || meta.name, id);
        const captures = [];
        const dependencies = [];
        for (const [name2, captured] of Object.entries(meta.captures || {}).sort(
          (left, right) => left[0].localeCompare(right[0])
        )) {
          if (isFunctionValue(captured)) {
            dependencies.push([0, encodeFunctionCode(captured, state, name2)]);
          } else if (isUserClassValue(captured)) {
            dependencies.push([0, encodeClassCode(captured, state, name2)]);
          } else if (isTraitValue(captured)) {
            dependencies.push([0, encodeTraitCode(captured, state, name2)]);
          } else if (isScalarForCapture(captured)) {
            captures.push([cbor.textString(name2), encodeValue(captured, state)]);
          }
        }
        registerCodeValue(kind, bindingName, meta.source, value);
        state.code[id] = [
          kind,
          cbor.textString(bindingName),
          cbor.textString(meta.source),
          captures,
          dependencies
        ];
        return id;
      }
      function decodeEnvelope(decoded) {
        if (!cbor.isTagged(decoded) || cbor.tagNumber(decoded) !== cbor.SELF_DESCRIBED_TAG) {
          throw new Error("Top-level item is not tag 55799");
        }
        const envelope = cbor.tagValue(decoded);
        if (!Array.isArray(envelope)) {
          throw new Error("Envelope must be an array");
        }
        if (envelope.length !== 6) {
          throw new Error("Envelope must contain exactly 6 fields");
        }
        const [magic, version, options, root, objects, code] = envelope;
        if (!cbor.isTextString(magic) || cbor.textValue(magic) !== "ZUZU-MARSHAL") {
          throw new Error("Envelope magic is invalid");
        }
        if (typeof version !== "number" || version !== 1) {
          throw new Error("Unsupported Zuzu Marshal version");
        }
        if (!(options instanceof Map)) {
          throw new Error("Envelope options must be a map");
        }
        if (!Array.isArray(objects)) {
          throw new Error("Envelope object table must be an array");
        }
        if (!Array.isArray(code)) {
          throw new Error("Envelope code table must be an array");
        }
        return { root, objects, code };
      }
      function loadCodeTable(code) {
        const records = code.map(validateCodeRecord);
        const values = [];
        const loading = /* @__PURE__ */ new Set();
        function loadById(id) {
          if (values[id]) {
            return values[id];
          }
          if (loading.has(id)) {
            throw new Error(`Cyclic code dependency involving record ${id}`);
          }
          loading.add(id);
          const value = loadCodeRecord(records[id], id, loadById);
          values[id] = value;
          loading.delete(id);
          return value;
        }
        for (let id = 0; id < records.length; id++) {
          loadById(id);
        }
        return values;
      }
      function validateCodeRecord(record, id) {
        assertRecordArray(record, `Code table entry ${id}`, 5);
        const [kind, bindingNameValue, sourceValue, captures, dependencies] = record;
        assertInteger(kind, `Code table entry ${id} kind`);
        if (![CODE_FUNCTION, CODE_CLASS, CODE_TRAIT].includes(kind)) {
          throw new Error(`Unsupported code kind ${kind} in current loader`);
        }
        if (!cbor.isTextString(bindingNameValue)) {
          throw new Error(`Code table entry ${id} binding name must be a text string`);
        }
        if (!cbor.isTextString(sourceValue)) {
          throw new Error(`Code table entry ${id} source must be a text string`);
        }
        if (!Array.isArray(captures)) {
          throw new Error(`Code table entry ${id} captures must be an array`);
        }
        if (!Array.isArray(dependencies)) {
          throw new Error(`Code table entry ${id} dependencies must be an array`);
        }
        return {
          kind,
          bindingName: cbor.textValue(bindingNameValue),
          source: cbor.textValue(sourceValue),
          captures,
          dependencies
        };
      }
      function loadCodeRecord(record, id, loadById) {
        const registered = codeRegistry.get(
          codeRegistryKey(record.kind, record.bindingName, record.source)
        );
        if (registered) {
          return registered;
        }
        const env = /* @__PURE__ */ Object.create(null);
        for (const capture of record.captures) {
          assertRecordArray(capture, `Capture in code record ${id}`, 2);
          const [nameValue, encodedValue] = capture;
          if (!cbor.isTextString(nameValue)) {
            throw new Error(`Capture name in code record ${id} must be a text string`);
          }
          const name2 = cbor.textValue(nameValue);
          if (isWeakStorageRecord(encodedValue)) {
            throw new Error(
              `Capture '${name2}' in code record ${id} weak storage record is not allowed here`
            );
          }
          env[name2] = decodeScalar(encodedValue);
        }
        for (const dependency of record.dependencies) {
          assertRecordArray(dependency, `Code dependency in record ${id}`, 2);
          const [depKind, depId] = dependency;
          assertInteger(depKind, `Code dependency in record ${id} kind`);
          if (depKind !== 0) {
            throw new Error(`Unsupported code dependency kind ${depKind} in record ${id}`);
          }
          assertInteger(depId, `Internal dependency in record ${id}`);
          const value = loadById(depId);
          const name2 = value.__zuzu_class_name || value.__zuzu_trait_name || value.__zuzu_marshal_meta && value.__zuzu_marshal_meta.name;
          if (name2) {
            env[name2] = value;
          }
        }
        if (record.kind === CODE_FUNCTION) {
          return buildFunctionFromSource(record.bindingName, record.source, env);
        }
        if (record.kind === CODE_CLASS) {
          return buildClassFromSource(record.bindingName, record.source, env);
        }
        return buildTraitFromSource(record.bindingName, record.source, env);
      }
      function allocatePlaceholders(objects, codeValues) {
        const placeholders = [];
        for (let id = 0; id < objects.length; id++) {
          const entry = objects[id];
          assertRecordArray(entry, `Object table entry ${id}`, 2);
          const kind = entry[0];
          assertInteger(kind, `Object table entry ${id} kind`);
          switch (kind) {
            case KIND_PAIR:
              placeholders[id] = new Pair({ pair: [] });
              break;
            case KIND_ARRAY:
              placeholders[id] = [];
              break;
            case KIND_DICT:
              placeholders[id] = {};
              break;
            case KIND_PAIRLIST:
              placeholders[id] = new PairList([]);
              break;
            case KIND_SET:
              placeholders[id] = /* @__PURE__ */ new Set();
              break;
            case KIND_BAG:
              placeholders[id] = new ZuzuBag([]);
              break;
            case KIND_OBJECT:
              placeholders[id] = {};
              break;
            case KIND_FUNCTION:
              placeholders[id] = decodeFunctionPayload(id, entry[1], codeValues);
              break;
            case KIND_CLASS:
              placeholders[id] = decodeClassPayload(id, entry[1], codeValues);
              break;
            case KIND_TRAIT:
              placeholders[id] = decodeTraitPayload(id, entry[1], codeValues);
              break;
            case KIND_BOUND_METHOD:
              placeholders[id] = createBoundMethodPlaceholder(id);
              break;
            case KIND_TIME:
              placeholders[id] = new (timeClass())(0);
              break;
            case KIND_PATH:
              placeholders[id] = new (pathClass())(".");
              break;
            default:
              throw new Error(`Unsupported object kind ${kind} in current loader`);
          }
        }
        return placeholders;
      }
      function fillPlaceholders(objects, placeholders) {
        for (let id = 0; id < objects.length; id++) {
          const [kind, payload] = objects[id];
          switch (kind) {
            case KIND_PAIR:
              fillPair(id, payload, placeholders);
              break;
            case KIND_ARRAY:
              fillArray(id, payload, placeholders);
              break;
            case KIND_DICT:
              fillDict(id, payload, placeholders);
              break;
            case KIND_PAIRLIST:
              fillPairList(id, payload, placeholders);
              break;
            case KIND_SET:
              fillSet(id, payload, placeholders);
              break;
            case KIND_BAG:
              fillBag(id, payload, placeholders);
              break;
            case KIND_OBJECT:
              fillObject(id, payload, placeholders);
              break;
            case KIND_FUNCTION:
              break;
            case KIND_CLASS:
              break;
            case KIND_TRAIT:
              break;
            case KIND_BOUND_METHOD:
              break;
            case KIND_TIME:
              fillTime(id, payload, placeholders);
              break;
            case KIND_PATH:
              fillPath(id, payload, placeholders);
              break;
            default:
              throw new Error(`Unsupported object kind ${kind} in current loader`);
          }
        }
        for (let id = 0; id < objects.length; id++) {
          const [kind, payload] = objects[id];
          if (kind === KIND_BOUND_METHOD) {
            fillBoundMethodPayload(id, payload, placeholders);
          }
        }
      }
      function fillPair(id, payload, placeholders) {
        assertRecordArray(payload, `Pair object payload ${id}`, 2);
        const [key, value] = payload;
        if (!cbor.isTextString(key)) {
          throw new Error(`Pair object payload ${id} key must be a text string`);
        }
        placeholders[id].pair = [
          cbor.textValue(key),
          storeStrongLoadedValue(decodeValue(value, placeholders, {
            context: `Pair object payload ${id} value`
          }))
        ];
      }
      function fillArray(id, payload, placeholders) {
        if (!Array.isArray(payload)) {
          throw new Error(`Array object payload ${id} must be an array`);
        }
        placeholders[id].splice(
          0,
          placeholders[id].length,
          ...payload.map((item) => storeCollectionLoadedValue(
            placeholders[id],
            decodeValue(
              item,
              placeholders,
              { context: `Array object payload ${id} item` }
            )
          ))
        );
      }
      function fillDict(id, payload, placeholders) {
        if (!Array.isArray(payload)) {
          throw new Error(`Dict object payload ${id} must be an array`);
        }
        const target = placeholders[id];
        for (const pair of payload) {
          const [key, value] = decodeKeyValueRecord(
            `Dict object payload ${id}`,
            pair,
            placeholders
          );
          if (Object.prototype.hasOwnProperty.call(target, key)) {
            throw new Error(`Dict object payload ${id} contains duplicate key '${key}'`);
          }
          target[key] = storeCollectionLoadedValue(target, value);
        }
      }
      function fillPairList(id, payload, placeholders) {
        if (!Array.isArray(payload)) {
          throw new Error(`PairList object payload ${id} must be an array`);
        }
        placeholders[id].list = payload.map((pair) => {
          const [key, value] = decodeKeyValueRecord(
            `PairList object payload ${id}`,
            pair,
            placeholders
          );
          return [key, storeCollectionLoadedValue(placeholders[id], value)];
        });
      }
      function fillSet(id, payload, placeholders) {
        for (const item of decodeItemPayload(
          `Set object payload ${id}`,
          payload,
          placeholders
        )) {
          placeholders[id].add(storeCollectionLoadedValue(placeholders[id], item));
        }
      }
      function fillBag(id, payload, placeholders) {
        placeholders[id].items = decodeItemPayload(
          `Bag object payload ${id}`,
          payload,
          placeholders
        ).map((item) => storeCollectionLoadedValue(placeholders[id], item));
      }
      function fillTime(id, payload, placeholders) {
        if (!Array.isArray(payload) || payload.length !== 1 && payload.length !== 2) {
          throw new Error(`Time object payload ${id} must contain epoch and optional timezone`);
        }
        const epoch = payload[0];
        if (typeof epoch !== "number") {
          throw new Error(`Time object payload ${id} epoch must be a number`);
        }
        placeholders[id]._epoch = epoch;
        placeholders[id]._timezone = payload.length > 1 && cbor.isTextString(payload[1]) ? cbor.textValue(payload[1]) : "UTC";
      }
      function fillPath(id, payload, placeholders) {
        assertRecordArray(payload, `Path object payload ${id}`, 1);
        const pathValue = payload[0];
        if (!cbor.isTextString(pathValue)) {
          throw new Error(`Path object payload ${id} path must be a text string`);
        }
        placeholders[id].value = cbor.textValue(pathValue);
      }
      function decodeFunctionPayload(id, payload, codeValues) {
        return decodeCodeBackedPayload("Function", id, payload, codeValues);
      }
      function decodeClassPayload(id, payload, codeValues) {
        return decodeCodeBackedPayload("Class", id, payload, codeValues);
      }
      function decodeTraitPayload(id, payload, codeValues) {
        return decodeCodeBackedPayload("Trait", id, payload, codeValues);
      }
      function decodeCodeBackedPayload(label, id, payload, codeValues) {
        assertRecordArray(payload, `${label} object payload ${id}`, 1);
        const codeId = payload[0];
        if (isWeakStorageRecord(codeId)) {
          throw new Error(`${label} object payload ${id} code id weak storage record is not allowed here`);
        }
        assertInteger(codeId, `${label} object payload ${id} code id`);
        if (codeId < 0 || codeId >= codeValues.length) {
          throw new Error(`${label} object payload ${id} code id is outside the code table`);
        }
        return codeValues[codeId];
      }
      function createBoundMethodPlaceholder(id) {
        const fn2 = function __zuzu_loaded_bound_method(...args) {
          const receiver = fn2.__zuzu_bound_receiver;
          const methodName = fn2.__zuzu_bound_method_name;
          if (receiver == null || typeof receiver[methodName] !== "function") {
            throw new Error(`Bound method object payload ${id} method is not loaded`);
          }
          return receiver[methodName](...args);
        };
        Object.defineProperty(fn2, "__zuzu_method", {
          value: true,
          enumerable: false,
          configurable: true
        });
        fn2.invoke = function invoke(_self, args = []) {
          return fn2(...args);
        };
        return fn2;
      }
      function fillBoundMethodPayload(id, payload, placeholders) {
        assertRecordArray(payload, `Bound method object payload ${id}`, 2);
        const receiver = decodeValue(payload[0], placeholders, {
          allowWeak: false,
          context: `Bound method object payload ${id} receiver`
        });
        if (receiver == null || typeof receiver !== "object") {
          throw new Error(`Bound method object payload ${id} receiver must resolve to an Object`);
        }
        if (!cbor.isTextString(payload[1])) {
          throw new Error(`Bound method object payload ${id} method name must be a text string`);
        }
        const methodName = cbor.textValue(payload[1]);
        if (typeof receiver[methodName] !== "function") {
          throw new Error(
            `Bound method object payload ${id} method '${methodName}' was not found`
          );
        }
        const fn2 = placeholders[id];
        Object.defineProperty(fn2, "__zuzu_bound_receiver", {
          value: receiver,
          enumerable: false,
          configurable: true,
          writable: true
        });
        Object.defineProperty(fn2, "__zuzu_bound_method_name", {
          value: methodName,
          enumerable: false,
          configurable: true,
          writable: true
        });
        fn2.invoke = function invoke(_self, args = []) {
          return receiver[methodName](...args);
        };
      }
      function fillObject(id, payload, placeholders) {
        assertRecordArray(payload, `Object payload ${id}`, 2);
        const [classRef, slotPayload] = payload;
        const klass = decodeValue(classRef, placeholders, {
          allowWeak: false,
          context: `Object payload ${id} class`
        });
        if (typeof klass !== "function") {
          throw new Error(`Object payload ${id} class must resolve to a Class`);
        }
        if (!Array.isArray(slotPayload)) {
          throw new Error(`Object payload ${id} slots must be an array`);
        }
        const object = placeholders[id];
        Object.setPrototypeOf(object, klass.prototype);
        const seen = /* @__PURE__ */ new Set();
        for (const record of slotPayload) {
          assertRecordArray(record, `Object payload ${id} slot records`, 2);
          const [nameValue, encodedValue] = record;
          if (!cbor.isTextString(nameValue)) {
            throw new Error(`Object payload ${id} slot names must be text strings`);
          }
          const name2 = cbor.textValue(nameValue);
          if (seen.has(name2)) {
            throw new Error(`Object payload ${id} contains duplicate slot '${name2}'`);
          }
          seen.add(name2);
          object[name2] = storeStrongLoadedValue(decodeValue(encodedValue, placeholders, {
            context: `Object payload ${id} slot '${name2}'`
          }));
        }
      }
      function runOnLoadHooks(objects, placeholders) {
        for (let id = 0; id < objects.length; id++) {
          const [kind] = objects[id];
          if (kind !== KIND_OBJECT) {
            continue;
          }
          const object = placeholders[id];
          if (typeof object.__on_load__ === "function") {
            try {
              object.__on_load__();
            } catch (err) {
              throw new Error(
                `__on_load__ for ${typeName2(object)} failed: ${err.message || err}`
              );
            }
          }
        }
      }
      function decodeItemPayload(context, payload, placeholders) {
        if (!Array.isArray(payload)) {
          throw new Error(`${context} must be an array`);
        }
        return payload.map((item) => decodeValue(item, placeholders, {
          context: `${context} item`
        }));
      }
      function decodeKeyValueRecord(context, pair, placeholders) {
        assertRecordArray(pair, `${context} entries`, 2);
        const [key, value] = pair;
        if (!cbor.isTextString(key)) {
          throw new Error(`${context} keys must be text strings`);
        }
        return [
          cbor.textValue(key),
          decodeValue(value, placeholders, {
            context: `${context} value`
          })
        ];
      }
      function decodeValue(value, placeholders, opts = {}) {
        const allowWeak = Object.prototype.hasOwnProperty.call(opts, "allowWeak") ? opts.allowWeak : true;
        const context = opts.context || "Encoded value";
        if (isEncodedScalar(value)) {
          return decodeScalar(value);
        }
        if (Array.isArray(value)) {
          if (value.length !== 2) {
            throw new Error(`${context} array must be [0, id] or [1, value]`);
          }
          const [marker, id] = value;
          if (!isInteger(marker) || marker !== 0 && marker !== 1) {
            throw new Error(`${context} marker must be 0 or 1`);
          }
          if (marker === 1) {
            validateWeakStorageRecord(value, placeholders, context);
            if (!allowWeak) {
              throw new Error(`${context} weak storage record is not allowed here`);
            }
            return makeWeakValue(decodeValue(id, placeholders, {
              allowWeak: false,
              context: `${context} weak storage value`
            }));
          }
          if (!isInteger(id)) {
            throw new Error("Encoded reference id must be an integer");
          }
          if (id < 0 || id >= placeholders.length) {
            throw new Error(`Reference id ${id} is outside the object table`);
          }
          return placeholders[id];
        }
        throw new Error("Envelope root is not a scalar or supported reference");
      }
      function storeStrongLoadedValue(value) {
        return isWeakCell(value) ? value : retainValue(value);
      }
      function storeCollectionLoadedValue(owner, value) {
        return isWeakCell(value) ? value : retainCollectionValue(owner, value);
      }
      function validateWeakStorageRecord(record, placeholders, context) {
        assertRecordArray(record, `${context} weak storage record`, 2);
        const inner = record[1];
        if (isWeakStorageRecord(inner)) {
          throw new Error(`${context} nested weak storage records are invalid`);
        }
        decodeValue(inner, placeholders, {
          allowWeak: false,
          context: `${context} weak storage value`
        });
      }
      function isWeakStorageRecord(value) {
        return Array.isArray(value) && value.length === 2 && value[0] === 1;
      }
      function isEncodedScalar(value) {
        return value == null || typeof value === "boolean" || typeof value === "number" || cbor.isTextString(value) || cbor.isByteString(value);
      }
      function decodeScalar(value) {
        if (value == null) {
          return null;
        }
        if (typeof value === "boolean" || typeof value === "number") {
          return value;
        }
        if (cbor.isTextString(value)) {
          return cbor.textValue(value);
        }
        if (cbor.isByteString(value)) {
          return new BinaryString2(cbor.bytesValue(value));
        }
        throw new Error("Envelope root is not a scalar value");
      }
      function assertRecordArray(value, context, length) {
        if (!Array.isArray(value) || value.length !== length) {
          const item = length === 1 ? "one-item" : `${length}-item`;
          throw new Error(`${context} must be a ${item} array`);
        }
      }
      function assertInteger(value, context) {
        if (!isInteger(value)) {
          throw new Error(`${context} must be an integer`);
        }
      }
      function isInteger(value) {
        return typeof value === "number" && Number.isInteger(value);
      }
      function isPlainDict(value) {
        if (value == null || typeof value !== "object") {
          return false;
        }
        if (value instanceof ZuzuBinary || value instanceof Pair || isPairListLike(value)) {
          return false;
        }
        if (value instanceof Set || value instanceof ZuzuBag || Array.isArray(value)) {
          return false;
        }
        if (isTimeValue(value) || isPathValue(value)) {
          return false;
        }
        const proto = Object.getPrototypeOf(value);
        if (proto === null || proto === Object.prototype) {
          return true;
        }
        return Object.prototype.toString.call(value) === "[object Object]" && value.constructor && value.constructor.name === "Object";
      }
      function isUserObjectValue(value) {
        return value && typeof value === "object" && !Array.isArray(value) && isUserClassValue(value.constructor) && !isTimeValue(value) && !isPathValue(value);
      }
      function isFunctionValue(value) {
        return typeof value === "function" && !isUserClassValue(value) && value.__zuzu_marshal_meta && value.__zuzu_marshal_meta.kind === "function";
      }
      function isUserClassValue(value) {
        return typeof value === "function" && typeof value.__zuzu_class_name === "string" && value.__zuzu_class_spec && typeof value.__zuzu_class_spec === "object";
      }
      function isTraitValue(value) {
        return value && typeof value === "object" && value.__zuzu_trait_methods && typeof value.__zuzu_trait_name === "string";
      }
      function isBoundMethodValue(value) {
        return value && (value.__zuzu_method || value.constructor && value.constructor.name === "ZuzuMethod");
      }
      function isScalarForCapture(value) {
        return value == null || typeof value === "boolean" || typeof value === "number" || typeof value === "string" || value instanceof ZuzuBinary;
      }
      function isMarshalableObjectSlot(value) {
        return typeof value !== "function";
      }
      function isTimeValue(value) {
        return value && typeof value === "object" && (value.__zuzu_type_name === "Time" || value.constructor && value.constructor.name === "Time") && (typeof value.epoch === "function" || typeof value._epoch === "number");
      }
      function isPathValue(value) {
        return value && typeof value === "object" && value.constructor && value.constructor.name === "Path" && (typeof value.to_String === "function" || typeof value.value === "string");
      }
      function timeClass() {
        return require_time().Time;
      }
      function pathClass() {
        if (runtimePolicy2.host_name === "browser") {
          throw new Error("UnmarshallingException: Path requires std/io");
        }
        const dynamicRequire = __require;
        return dynamicRequire("../io").Path;
      }
      function marshalBindingName(rawName, id) {
        const name2 = String(rawName || "");
        if (/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name2)) {
          return name2;
        }
        return `__zuzu_marshal_class_${id}`;
      }
      function marshalClassSource(klass, bindingName) {
        const fields = classFields(klass).map(sourceField).join("\n");
        return fields ? `class ${bindingName} {
${fields}
}` : `class ${bindingName} {}`;
      }
      function classFields(klass) {
        const spec = klass.__zuzu_class_spec || {};
        return Array.isArray(spec.fields) ? spec.fields : [];
      }
      function sourceField(field) {
        const kind = field.kind === "const" ? "const" : "let";
        const typeName3 = field.typeName ? `${field.typeName} ` : "";
        const accessors = Array.isArray(field.accessors) && field.accessors.length > 0 ? ` with ${field.accessors.join(", ")}` : "";
        return `	${kind} ${typeName3}${field.name}${accessors};`;
      }
      function registerCodeValue(kind, bindingName, source, value) {
        codeRegistry.set(codeRegistryKey(kind, bindingName, source), value);
        if (kind === CODE_CLASS) {
          classRegistry.set(classRegistryKey(bindingName, source), value);
        }
      }
      function classRegistryKey(bindingName, source) {
        return `${bindingName}\0${source}`;
      }
      function codeRegistryKey(kind, bindingName, source) {
        return `${kind}\0${bindingName}\0${source}`;
      }
      function buildFunctionFromSource(bindingName, source, env = {}) {
        const names = Object.keys(env);
        const values = names.map((name2) => env[name2]);
        let fn2;
        if (["node", "browser", "electron"].includes(runtimePolicy2.host_name)) {
          try {
            fn2 = buildFunctionWithRuntime(bindingName, source, env);
          } catch (runtimeErr) {
            try {
              fn2 = Function(...names, `return ( ${source} );`)(...values);
            } catch (rawErr) {
              fn2 = unloadedFunction(bindingName, runtimeErr, rawErr);
            }
          }
        } else {
          try {
            fn2 = Function(...names, `return ( ${source} );`)(...values);
          } catch (rawErr) {
            fn2 = unloadedFunction(bindingName, rawErr);
          }
        }
        Object.defineProperty(fn2, "__zuzu_marshal_meta", {
          value: {
            kind: "function",
            name: bindingName,
            source,
            captures: env
          },
          enumerable: false,
          configurable: true,
          writable: true
        });
        return fn2;
      }
      function unloadedFunction(bindingName, ...errors) {
        return function __zuzu_loaded_function() {
          const err = errors.find((item) => item && item.message);
          const message = err ? err.message : `Loaded function '${bindingName}' is not executable in JS`;
          throw new Error(message);
        };
      }
      function buildFunctionWithRuntime(bindingName, source, env = {}) {
        if (runtimePolicy2.host_name && !["node", "browser", "electron"].includes(runtimePolicy2.host_name)) {
          throw new Error(`Loaded function '${bindingName}' is not executable in JS`);
        }
        const denyCapabilities = [];
        for (const capability of [
          "fs",
          "net",
          "perl",
          "js",
          "proc",
          "db",
          "clib",
          "gui",
          "worker"
        ]) {
          if (runtimePolicy2[`deny_${capability}`]) {
            denyCapabilities.push(capability);
          }
        }
        const runtimeOptions = {
          repoRoot: runtimePolicy2.repo_root || void 0,
          includePaths: runtimePolicy2.include_paths || [],
          denyCapabilities,
          denyModules: runtimePolicy2.deny_modules || [],
          debugLevel: runtimePolicy2.debug_level || 0,
          transpiler: runtimePolicy2.transpiler || void 0
        };
        let runtime;
        if (runtimePolicy2.host_name === "browser") {
          const { createBrowserRuntime } = require_browser_runtime();
          const defaults = typeof globalThis !== "undefined" && globalThis.__ZUZU_BROWSER_DEFAULT_RUNTIME_OPTIONS__ && typeof globalThis.__ZUZU_BROWSER_DEFAULT_RUNTIME_OPTIONS__ === "object" ? globalThis.__ZUZU_BROWSER_DEFAULT_RUNTIME_OPTIONS__ : {};
          runtime = createBrowserRuntime({
            ...defaults,
            ...runtimeOptions
          }).runtime;
        } else {
          const entrypointsModule = "../../../lib/runtime-entrypoints";
          const { createNodeRuntime } = __require(entrypointsModule);
          runtime = createNodeRuntime(runtimeOptions);
        }
        const js = runtime.transpile(
          `let __zuzu_marshal_value := ${source};
__global__{__zuzu_marshal_result} := __zuzu_marshal_value;`
        );
        const context = runtime.buildContext({
          filename: "<std/marshal-code>",
          globals: env
        });
        context.__global__ = /* @__PURE__ */ Object.create(null);
        runtime.installCollectionMethods(context);
        runtime.host.runInContext(
          js,
          context,
          { filename: "<std/marshal-code>" }
        );
        const fn2 = context.__global__.__zuzu_marshal_result;
        if (typeof fn2 !== "function") {
          throw new Error(`Loaded function '${bindingName}' is not executable in JS`);
        }
        return fn2;
      }
      function buildClassFromSource(bindingName, source, env = {}) {
        const spec = parseClassSource(source, env);
        return buildMarshalClass(
          bindingName,
          spec.baseName ? env[spec.baseName] : null,
          spec.fields,
          spec.methods,
          spec.statics,
          spec.traitNames.map((name2) => env[name2]).filter(isTraitValue),
          env,
          source
        );
      }
      function buildTraitFromSource(bindingName, source, env = {}) {
        const trait = {
          __zuzu_trait_name: bindingName,
          __zuzu_trait_methods: parseMethods(source, env).methods
        };
        Object.defineProperty(trait, "__zuzu_marshal_meta", {
          value: {
            kind: "trait",
            name: bindingName,
            source,
            captures: env
          },
          enumerable: false,
          configurable: true,
          writable: true
        });
        return trait;
      }
      function parseClassSource(source, env = {}) {
        return {
          baseName: parseClassBaseName(source),
          fields: parseClassFields(source),
          traitNames: parseClassTraitNames(source),
          ...parseMethods(source, env)
        };
      }
      function parseClassBaseName(source) {
        const match = String(source || "").match(
          /\bclass\s+[A-Za-z_][A-Za-z0-9_]*\s+extends\s+([A-Za-z_][A-Za-z0-9_]*)/u
        );
        return match ? match[1] : null;
      }
      function parseClassFields(source) {
        const body = String(source || "").replace(/\/\*[\s\S]*?\*\//gu, "");
        const fields = [];
        const byName = /* @__PURE__ */ new Map();
        const rx = /\b(let|const)\s+(?:(Null|Any|Boolean|Number|String|BinaryString|Array|Dict|PairList|Set|Bag|Pair|Time|Path|Object)\s+)?([A-Za-z_][A-Za-z0-9_]*)(?:\s+with\s+([^;:=]+?))?\s*(?::=\s*([^;]*))?;/gu;
        let match = rx.exec(body);
        while (match) {
          const field = {
            kind: match[1],
            typeName: match[2] || null,
            name: match[3],
            accessors: match[4] ? match[4].split(",").map((item) => item.trim()).filter(Boolean) : [],
            defaultSource: match[5] ? match[5].trim() : null
          };
          fields.push(field);
          byName.set(field.name, field);
          match = rx.exec(body);
        }
        const methodRx = /\bmethod\s+(get|set|clear|has)_([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)/gu;
        let methodMatch = methodRx.exec(body);
        while (methodMatch) {
          const field = byName.get(methodMatch[2]);
          if (field && !field.accessors.includes(methodMatch[1])) {
            field.accessors.push(methodMatch[1]);
          }
          if (field && methodMatch[1] === "set" && !field.typeName) {
            const typeMatch = methodMatch[3].match(/\b(Null|Any|Boolean|Number|String|BinaryString|Array|Dict|PairList|Set|Bag|Pair|Time|Path|Object)\s+[A-Za-z_][A-Za-z0-9_]*\b/u);
            if (typeMatch) {
              field.typeName = typeMatch[1];
            }
          }
          methodMatch = methodRx.exec(body);
        }
        return fields;
      }
      function parseClassTraitNames(source) {
        const match = String(source || "").match(
          /\bclass\s+[A-Za-z_][A-Za-z0-9_]*(?:\s+extends\s+[A-Za-z_][A-Za-z0-9_]*)?\s+(?:with|but)\s+([^{;]+)/u
        );
        if (!match) {
          return [];
        }
        return match[1].split(",").map((item) => item.trim()).filter((item) => /^[A-Za-z_][A-Za-z0-9_]*$/u.test(item));
      }
      function parseMethods(source, env = {}) {
        const text = String(source || "").replace(/\/\*[\s\S]*?\*\//gu, "");
        const methods = {};
        const statics = {};
        const rx = /\b(static\s+)?method\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)\s*(?:->\s*[A-Za-z_][A-Za-z0-9_]*)?\s*\{([\s\S]*?)\}/gu;
        let match = rx.exec(text);
        while (match) {
          const target = match[1] ? statics : methods;
          target[match[2]] = compileSimpleMethod(
            match[2],
            parseParamNames(match[3]),
            match[4],
            env
          );
          match = rx.exec(text);
        }
        return { methods, statics };
      }
      function parseParamNames(source) {
        return String(source || "").split(",").map((item) => item.trim()).filter(Boolean).map((item) => {
          const match = item.match(/([A-Za-z_][A-Za-z0-9_]*)$/u);
          return match ? match[1] : null;
        }).filter(Boolean);
      }
      function compileSimpleMethod(name2, paramNames, body, env) {
        const match = String(body || "").match(/\breturn\s+([\s\S]*?)\s*;/u);
        if (!match) {
          return function _loaded_method() {
            return null;
          };
        }
        const expression = match[1];
        return {
          [name2]: function _loaded_method(...args) {
            const params = /* @__PURE__ */ Object.create(null);
            for (let i = 0; i < paramNames.length; i++) {
              params[paramNames[i]] = args[i];
            }
            return evalSimpleExpression(expression, this, env, params);
          }
        }[name2];
      }
      function evalSimpleExpression(source, self, env = {}, params = {}) {
        const expression = normalizeSimpleExpression(source);
        const envNames = Object.keys(env);
        const paramNames = Object.keys(params);
        const fn2 = Function(
          "self",
          ...envNames,
          ...paramNames,
          `with ( self ) { return ( ${expression} ); }`
        );
        return fn2(
          self || {},
          ...envNames.map((name2) => env[name2]),
          ...paramNames.map((name2) => params[name2])
        );
      }
      function normalizeSimpleExpression(source) {
        return String(source || "null").replace(/\s+_\s+/gu, " + ");
      }
      function buildMarshalClass(name2, base = null, fields, methods = {}, statics = {}, traits = [], env = {}, source = "") {
        const parent = typeof base === "function" ? base : Object;
        const ctor = {
          [name2]: class extends parent {
            constructor(initial = {}) {
              super(initial);
              for (const field of fields) {
                let value = field.defaultSource ? evalSimpleExpression(field.defaultSource, this, env) : null;
                if (isPairListLike(initial)) {
                  value = initial.get(field.name, value);
                } else if (initial && typeof initial === "object" && Object.prototype.hasOwnProperty.call(initial, field.name)) {
                  value = initial[field.name];
                }
                this[field.name] = value;
              }
            }
          }
        }[name2];
        for (const field of fields) {
          if (!Array.isArray(field.accessors)) {
            continue;
          }
          if (field.accessors.includes("get")) {
            ctor.prototype[`get_${field.name}`] = function _get_field() {
              return this[field.name];
            };
          }
          if (field.accessors.includes("set")) {
            ctor.prototype[`set_${field.name}`] = function _set_field(value) {
              if (field.typeName && value != null && !typeMatches(value, field.typeName)) {
                throw new Error(
                  `TypeException: field '${field.name}' must be ${field.typeName}, got ${typeName2(value)}`
                );
              }
              this[field.name] = value;
              return this;
            };
          }
        }
        for (const trait of traits) {
          for (const [methodName, fn2] of Object.entries(trait.__zuzu_trait_methods)) {
            if (typeof fn2 === "function" && typeof ctor.prototype[methodName] !== "function") {
              ctor.prototype[methodName] = fn2;
            }
          }
        }
        const generatedAccessors = /* @__PURE__ */ new Set();
        for (const field of fields) {
          for (const accessor of field.accessors || []) {
            generatedAccessors.add(`${accessor}_${field.name}`);
          }
        }
        for (const [methodName, fn2] of Object.entries(methods)) {
          if (generatedAccessors.has(methodName)) {
            continue;
          }
          ctor.prototype[methodName] = fn2;
        }
        for (const [methodName, fn2] of Object.entries(statics)) {
          ctor[methodName] = fn2;
        }
        Object.defineProperty(ctor, "__zuzu_class_name", {
          value: name2,
          enumerable: false,
          configurable: true,
          writable: true
        });
        Object.defineProperty(ctor, "__zuzu_class_spec", {
          value: { fields, traits, methods, statics, nested: {} },
          enumerable: false,
          configurable: true,
          writable: true
        });
        Object.defineProperty(ctor, "__zuzu_marshal_meta", {
          value: {
            kind: "class",
            name: name2,
            source,
            captures: env
          },
          enumerable: false,
          configurable: true,
          writable: true
        });
        return ctor;
      }
      function typeMatches(value, expected) {
        if (expected === "Any" || expected == null) {
          return true;
        }
        if (expected === "Null") {
          return value == null;
        }
        if (expected === "Boolean") {
          return typeof value === "boolean";
        }
        if (expected === "Number") {
          return typeof value === "number";
        }
        if (expected === "String") {
          return typeof value === "string";
        }
        if (expected === "BinaryString") {
          return value instanceof BinaryString2;
        }
        if (expected === "Array") {
          return Array.isArray(value);
        }
        if (expected === "Dict") {
          return isPlainDict(value);
        }
        if (expected === "PairList") {
          return isPairListLike(value);
        }
        if (expected === "Set") {
          return value instanceof Set;
        }
        if (expected === "Bag") {
          return value instanceof ZuzuBag;
        }
        if (expected === "Pair") {
          return value instanceof Pair;
        }
        if (expected === "Time") {
          return isTimeValue(value);
        }
        if (expected === "Path") {
          return isPathValue(value);
        }
        return true;
      }
      function typeName2(value) {
        if (value == null) {
          return "Null";
        }
        if (value instanceof BinaryString2) {
          return "BinaryString";
        }
        if (typeof value === "boolean") {
          return "Boolean";
        }
        if (typeof value === "number") {
          return "Number";
        }
        if (typeof value === "string") {
          return "String";
        }
        if (Array.isArray(value)) {
          return "Array";
        }
        if (value && value.constructor && value.constructor.name) {
          return value.constructor.name;
        }
        return typeof value;
      }
      module2.exports = {
        dumpGraph,
        loadGraph,
        safeToDumpGraph,
        setRuntimePolicy: setRuntimePolicy2
      };
    }
  });

  // modules/std/marshal.js
  var require_marshal = __commonJS({
    "modules/std/marshal.js"(exports2, module2) {
      "use strict";
      var cbor = require_cbor();
      var {
        dumpGraph,
        loadGraph,
        safeToDumpGraph,
        setRuntimePolicy: setRuntimePolicy2
      } = require_graph();
      var MarshallingException = class extends Error {
        constructor(message = "std/marshal.dump failed") {
          super(String(message));
          this.name = "MarshallingException";
        }
        to_String() {
          return `${this.name}: ${this.message}`;
        }
      };
      var UnmarshallingException = class extends Error {
        constructor(message = "std/marshal.load failed") {
          super(String(message));
          this.name = "UnmarshallingException";
        }
        to_String() {
          return `${this.name}: ${this.message}`;
        }
      };
      function dump(value) {
        assertArity("dump", arguments.length, 1);
        try {
          return dumpGraph(value);
        } catch (err) {
          throw new MarshallingException(
            `std/marshal.dump failed: ${err.message || err}`
          );
        }
      }
      function load(blob) {
        assertArity("load", arguments.length, 1);
        try {
          return loadGraph(blob);
        } catch (err) {
          if (String(err && err.message || err).startsWith("TypeException:")) {
            throw err;
          }
          throw new UnmarshallingException(
            `std/marshal.load failed: ${err.message || err}`
          );
        }
      }
      function safe_to_dump(value) {
        assertArity("safe_to_dump", arguments.length, 1);
        return safeToDumpGraph(value);
      }
      function assertArity(name2, got, expected) {
        if (got !== expected) {
          throw new Error(
            `TypeException: ${name2} expects ${expected} argument, got ${got}`
          );
        }
      }
      module2.exports = {
        dump,
        load,
        safe_to_dump,
        MarshallingException,
        UnmarshallingException,
        __zuzu_set_runtime_policy: setRuntimePolicy2
      };
      Object.defineProperty(module2.exports, "__cbor", {
        value: cbor,
        enumerable: false,
        configurable: false,
        writable: false
      });
    }
  });

  // modules/std/worker.js
  var require_worker = __commonJS({
    "modules/std/worker.js"(exports2, module2) {
      "use strict";
      var { BinaryString: BinaryString2, PairList } = require_runtime_helpers();
      var taskRuntime2 = require_task();
      var { CancelledException, ChannelClosedException, Task } = taskRuntime2;
      var marshal = require_marshal();
      var DENIAL_CAPABILITIES = [
        "fs",
        "net",
        "perl",
        "js",
        "proc",
        "db",
        "clib",
        "gui",
        "worker"
      ];
      var runtimePolicy2 = {
        host_name: "node",
        repo_root: null,
        include_paths: [],
        deny_modules: [],
        debug_level: 0,
        transpiler: null,
        browser_worker_source: null,
        browser_worker_url: null,
        browser_worker_factory: null
      };
      function setRuntimePolicy2(policy = {}) {
        runtimePolicy2 = {
          ...runtimePolicy2,
          ...policy,
          include_paths: Array.isArray(policy.include_paths) ? policy.include_paths.slice() : runtimePolicy2.include_paths,
          deny_modules: Array.isArray(policy.deny_modules) ? policy.deny_modules.slice() : runtimePolicy2.deny_modules
        };
        marshal.__zuzu_set_runtime_policy(runtimePolicy2);
      }
      function loadWorkerThreads() {
        if (runtimePolicy2.host_name === "browser") {
          return null;
        }
        try {
          return __require("node:worker_threads");
        } catch (_err) {
          return null;
        }
      }
      function loadNodePath() {
        try {
          return __require("node:path");
        } catch (_err) {
          return null;
        }
      }
      function browserRoot() {
        return typeof globalThis !== "undefined" ? globalThis : null;
      }
      function browserWorkerSource() {
        const root = browserRoot();
        return runtimePolicy2.browser_worker_source || root && root.__ZUZU_BROWSER_WORKER_SOURCE__ || null;
      }
      function browserWorkerUrl() {
        const root = browserRoot();
        return runtimePolicy2.browser_worker_url || root && root.__ZUZU_BROWSER_WORKER_URL__ || null;
      }
      function loadBrowserWorkerFactory() {
        if (runtimePolicy2.host_name !== "browser") {
          return null;
        }
        if (typeof runtimePolicy2.browser_worker_factory === "function") {
          return runtimePolicy2.browser_worker_factory;
        }
        const root = browserRoot();
        if (root && typeof root.__ZUZU_BROWSER_WORKER_FACTORY__ === "function") {
          return root.__ZUZU_BROWSER_WORKER_FACTORY__;
        }
        return null;
      }
      function assertWorkerCapability(label) {
        if (runtimePolicy2.deny_worker) {
          throw new Error(`${label} is denied by runtime policy`);
        }
      }
      function createBrowserWorker() {
        const factory = loadBrowserWorkerFactory();
        const source = browserWorkerSource();
        const url = browserWorkerUrl();
        if (factory) {
          return factory({
            source,
            url,
            name: "zuzu-browser-worker"
          });
        }
        const root = browserRoot();
        if (!root || typeof root.Worker !== "function") {
          return null;
        }
        if (url) {
          return new root.Worker(url);
        }
        if (source && typeof root.Blob === "function" && root.URL && typeof root.URL.createObjectURL === "function") {
          const blob = new root.Blob([source], { type: "text/javascript" });
          const objectUrl = root.URL.createObjectURL(blob);
          return new root.Worker(objectUrl);
        }
        return null;
      }
      function isPairList(value) {
        return value instanceof PairList || value && typeof value === "object" && Array.isArray(value.list) && typeof value.has === "function" && typeof value.get === "function";
      }
      function typeName2(value) {
        if (value == null) {
          return "Null";
        }
        if (isPairList(value)) {
          return "PairList";
        }
        if (Array.isArray(value)) {
          return "Array";
        }
        if (typeof value === "function") {
          return "Function";
        }
        if (typeof value === "boolean") {
          return "Boolean";
        }
        if (typeof value === "number") {
          return "Number";
        }
        if (typeof value === "string") {
          return "String";
        }
        if (value && value.__zuzu_type_name) {
          return String(value.__zuzu_type_name);
        }
        if (value && value.constructor && value.constructor.name) {
          return value.constructor.name;
        }
        return "Object";
      }
      function namedOptionMap(namedArgs) {
        const out = /* @__PURE__ */ Object.create(null);
        if (!namedArgs) {
          return out;
        }
        for (const pair of namedArgs.list || []) {
          if (Array.isArray(pair) && pair.length >= 2) {
            out[String(pair[0])] = pair[1];
          }
        }
        return out;
      }
      function parseWorkerOptions(namedArgs) {
        const named = namedOptionMap(namedArgs);
        const extraDenials = [];
        const refusedRelaxations = [];
        for (const key of Object.keys(named).sort()) {
          if (!key.startsWith("deny_")) {
            throw new Error(`Unknown named argument '${key}' for Worker.spawn`);
          }
          const capability = key.slice("deny_".length);
          if (!DENIAL_CAPABILITIES.includes(capability)) {
            throw new Error(`Unknown named argument '${key}' for Worker.spawn`);
          }
          if (typeof named[key] !== "boolean") {
            throw new Error(
              `TypeException: Worker.spawn named argument '${key}' expects Boolean, got ${typeName2(named[key])}`
            );
          }
          if (named[key]) {
            extraDenials.push(capability);
          } else if (runtimePolicy2[key]) {
            refusedRelaxations.push(capability);
          }
        }
        return { extraDenials, refusedRelaxations };
      }
      function effectivePolicy(extraDenials) {
        const policy = {
          host_name: runtimePolicy2.host_name,
          repo_root: runtimePolicy2.repo_root,
          include_paths: (runtimePolicy2.include_paths || []).slice(),
          deny_modules: (runtimePolicy2.deny_modules || []).slice(),
          debug_level: runtimePolicy2.debug_level,
          transpiler: runtimePolicy2.transpiler
        };
        for (const capability of DENIAL_CAPABILITIES) {
          policy[`deny_${capability}`] = Boolean(runtimePolicy2[`deny_${capability}`]) || extraDenials.includes(capability);
        }
        return policy;
      }
      function taskException(message) {
        const err = new Error(String(message || "worker failed"));
        err.name = "Exception";
        err.to_String = function toString() {
          return `Exception: ${this.message}`;
        };
        return err;
      }
      var Worker = class {
        static spawn(...rawArgs) {
          assertWorkerCapability("Worker.spawn");
          let namedArgs = null;
          if (rawArgs.length > 0 && isPairList(rawArgs[rawArgs.length - 1])) {
            namedArgs = rawArgs.pop();
          }
          if (rawArgs.length < 1 || rawArgs.length > 2) {
            throw new Error("Worker.spawn expects Callable and optional Array arguments");
          }
          const callable = rawArgs[0];
          if (typeof callable !== "function") {
            throw new Error(
              `TypeException: Worker.spawn expects Function, got ${typeName2(callable)}`
            );
          }
          const workerArgs = rawArgs.length > 1 ? rawArgs[1] : [];
          if (!Array.isArray(workerArgs)) {
            throw new Error(
              `TypeException: Worker.spawn expects Array arguments, got ${typeName2(workerArgs)}`
            );
          }
          const threads = loadWorkerThreads();
          const browserMode = runtimePolicy2.host_name === "browser";
          if (!threads && !browserMode) {
            throw new Error("std/worker transport is unavailable");
          }
          const { extraDenials, refusedRelaxations } = parseWorkerOptions(namedArgs);
          if (refusedRelaxations.length > 0) {
            return Task.failed(taskException(
              `Denied capability '${refusedRelaxations[0]}' cannot be relaxed for worker`
            ));
          }
          let requestBytes;
          try {
            requestBytes = marshal.dump([callable, workerArgs]);
          } catch (err) {
            throw err;
          }
          if (browserMode) {
            return spawnBrowserWorker(requestBytes, extraDenials);
          }
          return spawnNodeWorker(threads, requestBytes, extraDenials);
        }
        static spawn_handle(...rawArgs) {
          assertWorkerCapability("Worker.spawn_handle");
          let namedArgs = null;
          if (rawArgs.length > 0 && isPairList(rawArgs[rawArgs.length - 1])) {
            namedArgs = rawArgs.pop();
          }
          if (rawArgs.length < 1 || rawArgs.length > 2) {
            throw new Error(
              "Worker.spawn_handle expects Callable and optional Array arguments"
            );
          }
          const callable = rawArgs[0];
          if (typeof callable !== "function") {
            throw new Error(
              `TypeException: Worker.spawn_handle expects Function, got ${typeName2(callable)}`
            );
          }
          const workerArgs = rawArgs.length > 1 ? rawArgs[1] : [];
          if (!Array.isArray(workerArgs)) {
            throw new Error(
              `TypeException: Worker.spawn_handle expects Array arguments, got ${typeName2(workerArgs)}`
            );
          }
          const threads = loadWorkerThreads();
          const browserMode = runtimePolicy2.host_name === "browser";
          if (!threads && !browserMode) {
            throw new Error("std/worker transport is unavailable");
          }
          const { extraDenials, refusedRelaxations } = parseWorkerOptions(namedArgs);
          if (refusedRelaxations.length > 0) {
            const task = Task.failed(taskException(
              `Denied capability '${refusedRelaxations[0]}' cannot be relaxed for worker`
            ));
            return new WorkerHandle(null, {
              resultTask: task,
              remoteClosed: true
            });
          }
          const requestBytes = marshal.dump([callable, workerArgs]);
          if (browserMode) {
            return spawnBrowserWorkerHandle(requestBytes, extraDenials);
          }
          return spawnNodeWorkerHandle(threads, requestBytes, extraDenials);
        }
      };
      var WorkerHandle = class {
        constructor(transport, options = {}) {
          this._transport = transport;
          this._queue = [];
          this._receivers = [];
          this._localClosed = false;
          this._remoteClosed = Boolean(options.remoteClosed);
          this._cancelled = false;
          this._remoteError = null;
          this._nextOutgoingSeq = 1;
          this._nextIncomingSeq = 1;
          this._incomingFrames = /* @__PURE__ */ new Map();
          this._resultTask = options.resultTask || new Task(null, {
            status: "running",
            name: "WorkerHandle.result",
            cancel: (reason) => this.cancel(reason)
          });
        }
        send(value = null) {
          if (this._localClosed || this._remoteClosed || this._cancelled) {
            return Task.failed(
              new ChannelClosedException("send on closed worker handle")
            );
          }
          let bytes;
          try {
            bytes = marshal.dump(value);
          } catch (err) {
            return Task.failed(err);
          }
          try {
            this._post({
              type: "message",
              bytes: Array.from(bytes.bytes)
            });
          } catch (err) {
            this._closeRemote(err);
            return Task.failed(err);
          }
          return Task.resolved(value);
        }
        recv() {
          if (this._queue.length > 0) {
            return Task.resolved(this._queue.shift());
          }
          if (this._cancelled) {
            return Task.failed(new CancelledException("worker cancelled"));
          }
          if (this._remoteClosed) {
            return Task.failed(
              new ChannelClosedException("worker handle closed")
            );
          }
          const task = new Task(null, {
            status: "waiting",
            name: "WorkerHandle.recv",
            cancel: () => {
              this._receivers = this._receivers.filter((item) => item !== task);
            }
          });
          this._receivers.push(task);
          return task;
        }
        close() {
          if (this._localClosed) {
            return Task.resolved(null);
          }
          this._localClosed = true;
          try {
            this._post({ type: "close" });
          } catch (_err) {
          }
          return Task.resolved(null);
        }
        cancel(reason = null) {
          if (this._cancelled) {
            return this;
          }
          this._cancelled = true;
          this._localClosed = true;
          this._remoteClosed = true;
          const err = reason instanceof Error ? reason : new CancelledException(reason == null ? "worker cancelled" : reason);
          this._rejectReceivers(err, true);
          try {
            this._post({
              type: "cancel",
              reason: err.message || String(err)
            });
          } catch (_err) {
          }
          if (this._transport && typeof this._transport.terminate === "function") {
            this._transport.terminate();
          }
          if (!this._resultTask.done()) {
            this._resultTask.cancel(err);
          }
          return this;
        }
        result() {
          return this._resultTask;
        }
        status() {
          return this._resultTask.status();
        }
        done() {
          return this._resultTask.done();
        }
        _post(message) {
          if (!this._transport || typeof this._transport.postMessage !== "function") {
            throw taskException("worker transport is closed");
          }
          const payload = { ...message };
          if (["message", "close", "cancel"].includes(payload.type) && !Number.isInteger(payload.seq)) {
            payload.seq = this._nextOutgoingSeq++;
          }
          this._transport.postMessage(payload);
        }
        _deliverBytes(bytes) {
          let value;
          try {
            value = marshal.load(new BinaryString2(bytes || []));
          } catch (err) {
            this._closeRemote(err);
            return;
          }
          const receiver = this._receivers.shift();
          if (receiver) {
            receiver._resolve(value);
          } else {
            this._queue.push(value);
          }
        }
        _resolveResultBytes(bytes) {
          try {
            this._resultTask._resolve(
              marshal.load(new BinaryString2(bytes || []))
            );
          } catch (err) {
            this._resultTask._reject(err);
          }
        }
        _rejectResult(err) {
          if (!this._resultTask.done()) {
            this._resultTask._reject(err);
          }
        }
        _closeRemote(err = null) {
          this._remoteClosed = true;
          if (err) {
            this._remoteError = err;
          }
          this._rejectReceivers(
            err || this._remoteError || new ChannelClosedException("worker handle closed"),
            false
          );
        }
        _rejectReceivers(err, forceCancel = false) {
          while (this._receivers.length > 0) {
            this._receivers.shift()._reject(
              err,
              forceCancel ? "cancelled" : null
            );
          }
        }
        _receiveFrame(message) {
          if (Number.isInteger(message.seq)) {
            this._incomingFrames.set(message.seq, message);
            while (this._incomingFrames.has(this._nextIncomingSeq)) {
              const next = this._incomingFrames.get(this._nextIncomingSeq);
              this._incomingFrames.delete(this._nextIncomingSeq);
              this._nextIncomingSeq++;
              processWorkerHandleMessage(this, next);
            }
            return;
          }
          processWorkerHandleMessage(this, message);
        }
      };
      Object.defineProperty(WorkerHandle.prototype, "__zuzu_type_name", {
        value: "WorkerHandle",
        enumerable: false,
        configurable: true,
        writable: true
      });
      function spawnNodeWorker(threads, requestBytes, extraDenials) {
        const nodePath = loadNodePath();
        if (!threads || !nodePath) {
          throw new Error("std/worker transport is unavailable");
        }
        const task = new Task(null, {
          status: "running",
          name: "Worker.spawn"
        });
        const nodeWorker = new threads.Worker(
          nodePath.join(__dirname, "worker-thread.js"),
          {
            workerData: {
              request_bytes: Array.from(requestBytes.bytes),
              policy: effectivePolicy(extraDenials)
            }
          }
        );
        task._cancelHook = function cancelWorker() {
          nodeWorker.terminate().catch(() => {
          });
        };
        let settled = false;
        nodeWorker.once("message", (message) => {
          settled = true;
          handleWorkerMessage(task, message);
        });
        nodeWorker.once("error", (err) => {
          settled = true;
          if (!task.done()) {
            task._reject(taskException(err && err.message ? err.message : err));
          }
        });
        nodeWorker.once("exit", (code) => {
          if (!settled && !task.done() && code !== 0) {
            task._reject(taskException(`Worker exited with code ${code}`));
          }
        });
        return task;
      }
      function spawnBrowserWorker(requestBytes, extraDenials) {
        const browserWorker = createBrowserWorker();
        if (!browserWorker) {
          throw new Error("std/worker transport is unavailable");
        }
        const task = new Task(null, {
          status: "running",
          name: "Worker.spawn"
        });
        task._cancelHook = function cancelWorker() {
          if (browserWorker && typeof browserWorker.terminate === "function") {
            browserWorker.terminate();
          }
        };
        const onMessage = (event) => handleWorkerMessage(
          task,
          event && Object.prototype.hasOwnProperty.call(event, "data") ? event.data : event
        );
        const onError = (err) => {
          const root = browserRoot();
          const reject = () => {
            if (!task.done()) {
              task._reject(taskException(err && err.message ? err.message : err));
            }
          };
          if (root && typeof root.setTimeout === "function") {
            root.setTimeout(reject, 25);
            return;
          }
          reject();
        };
        if (typeof browserWorker.addEventListener === "function") {
          browserWorker.addEventListener("message", onMessage);
          browserWorker.addEventListener("error", onError);
        } else {
          browserWorker.onmessage = onMessage;
          browserWorker.onerror = onError;
        }
        browserWorker.postMessage({
          request_bytes: Array.from(requestBytes.bytes),
          policy: effectivePolicy(extraDenials)
        });
        return task;
      }
      function spawnNodeWorkerHandle(threads, requestBytes, extraDenials) {
        const nodePath = loadNodePath();
        if (!threads || !nodePath) {
          throw new Error("std/worker transport is unavailable");
        }
        const nodeWorker = new threads.Worker(
          nodePath.join(__dirname, "worker-thread.js"),
          {
            workerData: {
              mode: "handle",
              request_bytes: Array.from(requestBytes.bytes),
              policy: effectivePolicy(extraDenials)
            }
          }
        );
        const handle = new WorkerHandle({
          postMessage: (message) => nodeWorker.postMessage(message),
          terminate: () => nodeWorker.terminate().catch(() => {
          })
        });
        let settled = false;
        nodeWorker.on("message", (message) => handleWorkerHandleMessage(handle, message));
        nodeWorker.once("error", (err) => {
          settled = true;
          const wrapped = taskException(err && err.message ? err.message : err);
          handle._closeRemote(wrapped);
          handle._rejectResult(wrapped);
        });
        nodeWorker.once("exit", (code) => {
          if (settled) {
            return;
          }
          if (code !== 0 && !handle._cancelled) {
            const err = taskException(`Worker exited with code ${code}`);
            handle._closeRemote(err);
            handle._rejectResult(err);
            return;
          }
          handle._closeRemote();
          if (!handle._resultTask.done() && !handle._cancelled) {
            handle._rejectResult(taskException("Worker exited without result"));
          }
        });
        return handle;
      }
      function spawnBrowserWorkerHandle(requestBytes, extraDenials) {
        const browserWorker = createBrowserWorker();
        if (!browserWorker) {
          throw new Error("std/worker transport is unavailable");
        }
        const handle = new WorkerHandle({
          postMessage: (message) => browserWorker.postMessage(message),
          terminate: () => {
            if (typeof browserWorker.terminate === "function") {
              browserWorker.terminate();
            }
          }
        });
        const onMessage = (event) => handleWorkerHandleMessage(
          handle,
          event && Object.prototype.hasOwnProperty.call(event, "data") ? event.data : event
        );
        const onError = (err) => {
          const wrapped = taskException(err && err.message ? err.message : err);
          handle._closeRemote(wrapped);
          handle._rejectResult(wrapped);
        };
        if (typeof browserWorker.addEventListener === "function") {
          browserWorker.addEventListener("message", onMessage);
          browserWorker.addEventListener("error", onError);
        } else {
          browserWorker.onmessage = onMessage;
          browserWorker.onerror = onError;
        }
        browserWorker.postMessage({
          type: "start_handle",
          request_bytes: Array.from(requestBytes.bytes),
          policy: effectivePolicy(extraDenials)
        });
        return handle;
      }
      function handleWorkerMessage(task, message) {
        if (task.done()) {
          return;
        }
        if (!message || typeof message !== "object") {
          task._reject(taskException("Worker returned invalid reply"));
          return;
        }
        if (!message.ok) {
          task._reject(taskException(message.error || "worker failed"));
          return;
        }
        try {
          task._resolve(marshal.load(new BinaryString2(message.bytes || [])));
        } catch (err) {
          task._reject(err);
        }
      }
      function handleWorkerHandleMessage(handle, message) {
        if (!message || typeof message !== "object") {
          const err = taskException("Worker returned invalid reply");
          handle._closeRemote(err);
          handle._rejectResult(err);
          return;
        }
        handle._receiveFrame(message);
      }
      function processWorkerHandleMessage(handle, message) {
        if (message.type === "message") {
          handle._deliverBytes(message.bytes || []);
          return;
        }
        if (message.type === "close") {
          handle._closeRemote();
          return;
        }
        if (message.type === "result") {
          if (message.ok) {
            handle._resolveResultBytes(message.bytes || []);
          } else {
            const err2 = taskException(message.error || "worker failed");
            handle._remoteError = err2;
            handle._rejectResult(err2);
          }
          return;
        }
        const err = taskException("Worker returned invalid reply");
        handle._closeRemote(err);
        handle._rejectResult(err);
      }
      module2.exports = {
        Worker,
        __zuzu_set_runtime_policy: setRuntimePolicy2
      };
    }
  });

  // modules/std/digest/_hash.js
  var require_hash = __commonJS({
    "modules/std/digest/_hash.js"(exports2, module2) {
      "use strict";
      var { BinaryString: BinaryString2 } = require_runtime_helpers();
      function valueType(value) {
        if (value == null) {
          return "Null";
        }
        if (typeof value === "string") {
          return "String";
        }
        return value.constructor && value.constructor.name ? value.constructor.name : typeof value;
      }
      function assertBinary(value, fnName, label = "BinaryString") {
        if (!value || !(value.bytes instanceof Uint8Array)) {
          throw new Error(`TypeException: ${fnName} expects ${label}, got ${valueType(value)}`);
        }
      }
      function toBinary(bytes) {
        return new BinaryString2(Uint8Array.from(bytes));
      }
      function bytesToHex(bytes) {
        return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
      }
      function bytesToBase64(bytes) {
        if (typeof Buffer !== "undefined") {
          return Buffer.from(bytes).toString("base64").replace(/=+$/u, "");
        }
        let text = "";
        for (let i = 0; i < bytes.length; i++) {
          text += String.fromCharCode(bytes[i]);
        }
        return btoa(text).replace(/=+$/u, "");
      }
      function concatBytes2(...items) {
        const total = items.reduce((sum, item) => sum + item.length, 0);
        const out = new Uint8Array(total);
        let offset = 0;
        for (const item of items) {
          out.set(item, offset);
          offset += item.length;
        }
        return out;
      }
      function padded64(bytes, littleEndianLength = false) {
        const bitLength = bytes.length * 8;
        const total = Math.ceil((bytes.length + 9) / 64) * 64;
        const out = new Uint8Array(total);
        out.set(bytes);
        out[bytes.length] = 128;
        if (littleEndianLength) {
          let n = bitLength;
          for (let i = 0; i < 8; i++) {
            out[total - 8 + i] = n & 255;
            n = Math.floor(n / 256);
          }
        } else {
          let n = bitLength;
          for (let i = 7; i >= 0; i--) {
            out[total - 8 + i] = n & 255;
            n = Math.floor(n / 256);
          }
        }
        return out;
      }
      function padded128(bytes) {
        const bitLength = BigInt(bytes.length) * 8n;
        const total = Math.ceil((bytes.length + 17) / 128) * 128;
        const out = new Uint8Array(total);
        out.set(bytes);
        out[bytes.length] = 128;
        let n = bitLength;
        for (let i = 15; i >= 0; i--) {
          out[total - 16 + i] = Number(n & 0xffn);
          n >>= 8n;
        }
        return out;
      }
      function rotl32(value, bits) {
        return (value << bits | value >>> 32 - bits) >>> 0;
      }
      function rotr32(value, bits) {
        return (value >>> bits | value << 32 - bits) >>> 0;
      }
      function add32(...values) {
        return values.reduce((sum, value) => sum + value >>> 0, 0);
      }
      function md5Bytes(bytes) {
        const s = [
          7,
          12,
          17,
          22,
          7,
          12,
          17,
          22,
          7,
          12,
          17,
          22,
          7,
          12,
          17,
          22,
          5,
          9,
          14,
          20,
          5,
          9,
          14,
          20,
          5,
          9,
          14,
          20,
          5,
          9,
          14,
          20,
          4,
          11,
          16,
          23,
          4,
          11,
          16,
          23,
          4,
          11,
          16,
          23,
          4,
          11,
          16,
          23,
          6,
          10,
          15,
          21,
          6,
          10,
          15,
          21,
          6,
          10,
          15,
          21,
          6,
          10,
          15,
          21
        ];
        const k = Array.from(
          { length: 64 },
          (_value, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296) >>> 0
        );
        const data = padded64(bytes, true);
        let a0 = 1732584193;
        let b0 = 4023233417;
        let c0 = 2562383102;
        let d0 = 271733878;
        for (let offset = 0; offset < data.length; offset += 64) {
          const m = new Uint32Array(16);
          for (let i = 0; i < 16; i++) {
            const j = offset + i * 4;
            m[i] = data[j] | data[j + 1] << 8 | data[j + 2] << 16 | data[j + 3] << 24;
          }
          let a = a0;
          let b = b0;
          let c = c0;
          let d = d0;
          for (let i = 0; i < 64; i++) {
            let f;
            let g;
            if (i < 16) {
              f = b & c | ~b & d;
              g = i;
            } else if (i < 32) {
              f = d & b | ~d & c;
              g = (5 * i + 1) % 16;
            } else if (i < 48) {
              f = b ^ c ^ d;
              g = (3 * i + 5) % 16;
            } else {
              f = c ^ (b | ~d);
              g = 7 * i % 16;
            }
            const tmp = d;
            d = c;
            c = b;
            b = add32(b, rotl32(add32(a, f, k[i], m[g]), s[i]));
            a = tmp;
          }
          a0 = add32(a0, a);
          b0 = add32(b0, b);
          c0 = add32(c0, c);
          d0 = add32(d0, d);
        }
        const out = new Uint8Array(16);
        for (const [index, value] of [a0, b0, c0, d0].entries()) {
          out[index * 4] = value & 255;
          out[index * 4 + 1] = value >>> 8 & 255;
          out[index * 4 + 2] = value >>> 16 & 255;
          out[index * 4 + 3] = value >>> 24 & 255;
        }
        return out;
      }
      function sha1Bytes(bytes) {
        const data = padded64(bytes);
        let h0 = 1732584193;
        let h1 = 4023233417;
        let h2 = 2562383102;
        let h3 = 271733878;
        let h4 = 3285377520;
        for (let offset = 0; offset < data.length; offset += 64) {
          const w = new Uint32Array(80);
          for (let i = 0; i < 16; i++) {
            const j = offset + i * 4;
            w[i] = data[j] << 24 | data[j + 1] << 16 | data[j + 2] << 8 | data[j + 3];
          }
          for (let i = 16; i < 80; i++) {
            w[i] = rotl32(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
          }
          let a = h0;
          let b = h1;
          let c = h2;
          let d = h3;
          let e = h4;
          for (let i = 0; i < 80; i++) {
            let f;
            let k;
            if (i < 20) {
              f = b & c | ~b & d;
              k = 1518500249;
            } else if (i < 40) {
              f = b ^ c ^ d;
              k = 1859775393;
            } else if (i < 60) {
              f = b & c | b & d | c & d;
              k = 2400959708;
            } else {
              f = b ^ c ^ d;
              k = 3395469782;
            }
            const temp = add32(rotl32(a, 5), f, e, k, w[i]);
            e = d;
            d = c;
            c = rotl32(b, 30);
            b = a;
            a = temp;
          }
          h0 = add32(h0, a);
          h1 = add32(h1, b);
          h2 = add32(h2, c);
          h3 = add32(h3, d);
          h4 = add32(h4, e);
        }
        return words32ToBytes([h0, h1, h2, h3, h4]);
      }
      var SHA256_K = [
        1116352408,
        1899447441,
        3049323471,
        3921009573,
        961987163,
        1508970993,
        2453635748,
        2870763221,
        3624381080,
        310598401,
        607225278,
        1426881987,
        1925078388,
        2162078206,
        2614888103,
        3248222580,
        3835390401,
        4022224774,
        264347078,
        604807628,
        770255983,
        1249150122,
        1555081692,
        1996064986,
        2554220882,
        2821834349,
        2952996808,
        3210313671,
        3336571891,
        3584528711,
        113926993,
        338241895,
        666307205,
        773529912,
        1294757372,
        1396182291,
        1695183700,
        1986661051,
        2177026350,
        2456956037,
        2730485921,
        2820302411,
        3259730800,
        3345764771,
        3516065817,
        3600352804,
        4094571909,
        275423344,
        430227734,
        506948616,
        659060556,
        883997877,
        958139571,
        1322822218,
        1537002063,
        1747873779,
        1955562222,
        2024104815,
        2227730452,
        2361852424,
        2428436474,
        2756734187,
        3204031479,
        3329325298
      ];
      function words32ToBytes(words) {
        const out = new Uint8Array(words.length * 4);
        for (let i = 0; i < words.length; i++) {
          out[i * 4] = words[i] >>> 24 & 255;
          out[i * 4 + 1] = words[i] >>> 16 & 255;
          out[i * 4 + 2] = words[i] >>> 8 & 255;
          out[i * 4 + 3] = words[i] & 255;
        }
        return out;
      }
      function sha256Core(bytes, initial) {
        const data = padded64(bytes);
        const h = initial.slice();
        for (let offset = 0; offset < data.length; offset += 64) {
          const w = new Uint32Array(64);
          for (let i = 0; i < 16; i++) {
            const j = offset + i * 4;
            w[i] = data[j] << 24 | data[j + 1] << 16 | data[j + 2] << 8 | data[j + 3];
          }
          for (let i = 16; i < 64; i++) {
            const s0 = rotr32(w[i - 15], 7) ^ rotr32(w[i - 15], 18) ^ w[i - 15] >>> 3;
            const s1 = rotr32(w[i - 2], 17) ^ rotr32(w[i - 2], 19) ^ w[i - 2] >>> 10;
            w[i] = add32(w[i - 16], s0, w[i - 7], s1);
          }
          let [a, b, c, d, e, f, g, hh] = h;
          for (let i = 0; i < 64; i++) {
            const s1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25);
            const ch = e & f ^ ~e & g;
            const temp1 = add32(hh, s1, ch, SHA256_K[i], w[i]);
            const s0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22);
            const maj = a & b ^ a & c ^ b & c;
            const temp2 = add32(s0, maj);
            hh = g;
            g = f;
            f = e;
            e = add32(d, temp1);
            d = c;
            c = b;
            b = a;
            a = add32(temp1, temp2);
          }
          for (const [i, value] of [a, b, c, d, e, f, g, hh].entries()) {
            h[i] = add32(h[i], value);
          }
        }
        return words32ToBytes(h);
      }
      function sha224Bytes(bytes) {
        return sha256Core(
          bytes,
          [3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428]
        ).slice(0, 28);
      }
      function sha256Bytes(bytes) {
        return sha256Core(
          bytes,
          [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]
        );
      }
      var MASK64 = (1n << 64n) - 1n;
      var SHA512_K = [
        0x428a2f98d728ae22n,
        0x7137449123ef65cdn,
        0xb5c0fbcfec4d3b2fn,
        0xe9b5dba58189dbbcn,
        0x3956c25bf348b538n,
        0x59f111f1b605d019n,
        0x923f82a4af194f9bn,
        0xab1c5ed5da6d8118n,
        0xd807aa98a3030242n,
        0x12835b0145706fben,
        0x243185be4ee4b28cn,
        0x550c7dc3d5ffb4e2n,
        0x72be5d74f27b896fn,
        0x80deb1fe3b1696b1n,
        0x9bdc06a725c71235n,
        0xc19bf174cf692694n,
        0xe49b69c19ef14ad2n,
        0xefbe4786384f25e3n,
        0x0fc19dc68b8cd5b5n,
        0x240ca1cc77ac9c65n,
        0x2de92c6f592b0275n,
        0x4a7484aa6ea6e483n,
        0x5cb0a9dcbd41fbd4n,
        0x76f988da831153b5n,
        0x983e5152ee66dfabn,
        0xa831c66d2db43210n,
        0xb00327c898fb213fn,
        0xbf597fc7beef0ee4n,
        0xc6e00bf33da88fc2n,
        0xd5a79147930aa725n,
        0x06ca6351e003826fn,
        0x142929670a0e6e70n,
        0x27b70a8546d22ffcn,
        0x2e1b21385c26c926n,
        0x4d2c6dfc5ac42aedn,
        0x53380d139d95b3dfn,
        0x650a73548baf63den,
        0x766a0abb3c77b2a8n,
        0x81c2c92e47edaee6n,
        0x92722c851482353bn,
        0xa2bfe8a14cf10364n,
        0xa81a664bbc423001n,
        0xc24b8b70d0f89791n,
        0xc76c51a30654be30n,
        0xd192e819d6ef5218n,
        0xd69906245565a910n,
        0xf40e35855771202an,
        0x106aa07032bbd1b8n,
        0x19a4c116b8d2d0c8n,
        0x1e376c085141ab53n,
        0x2748774cdf8eeb99n,
        0x34b0bcb5e19b48a8n,
        0x391c0cb3c5c95a63n,
        0x4ed8aa4ae3418acbn,
        0x5b9cca4f7763e373n,
        0x682e6ff3d6b2b8a3n,
        0x748f82ee5defb2fcn,
        0x78a5636f43172f60n,
        0x84c87814a1f0ab72n,
        0x8cc702081a6439ecn,
        0x90befffa23631e28n,
        0xa4506cebde82bde9n,
        0xbef9a3f7b2c67915n,
        0xc67178f2e372532bn,
        0xca273eceea26619cn,
        0xd186b8c721c0c207n,
        0xeada7dd6cde0eb1en,
        0xf57d4f7fee6ed178n,
        0x06f067aa72176fban,
        0x0a637dc5a2c898a6n,
        0x113f9804bef90daen,
        0x1b710b35131c471bn,
        0x28db77f523047d84n,
        0x32caab7b40c72493n,
        0x3c9ebe0a15c9bebcn,
        0x431d67c49c100d4cn,
        0x4cc5d4becb3e42b6n,
        0x597f299cfc657e2an,
        0x5fcb6fab3ad6faecn,
        0x6c44198c4a475817n
      ];
      function rotr64(value, bits) {
        const n = BigInt(bits);
        return (value >> n | value << 64n - n) & MASK64;
      }
      function add64(...values) {
        return values.reduce((sum, value) => sum + value & MASK64, 0n);
      }
      function words64ToBytes(words) {
        const out = new Uint8Array(words.length * 8);
        for (let i = 0; i < words.length; i++) {
          let value = words[i];
          for (let j = 7; j >= 0; j--) {
            out[i * 8 + j] = Number(value & 0xffn);
            value >>= 8n;
          }
        }
        return out;
      }
      function sha512Core(bytes, initial) {
        const data = padded128(bytes);
        const h = initial.slice();
        for (let offset = 0; offset < data.length; offset += 128) {
          const w = new Array(80).fill(0n);
          for (let i = 0; i < 16; i++) {
            let value = 0n;
            for (let j = 0; j < 8; j++) {
              value = value << 8n | BigInt(data[offset + i * 8 + j]);
            }
            w[i] = value;
          }
          for (let i = 16; i < 80; i++) {
            const s0 = rotr64(w[i - 15], 1) ^ rotr64(w[i - 15], 8) ^ w[i - 15] >> 7n;
            const s1 = rotr64(w[i - 2], 19) ^ rotr64(w[i - 2], 61) ^ w[i - 2] >> 6n;
            w[i] = add64(w[i - 16], s0, w[i - 7], s1);
          }
          let [a, b, c, d, e, f, g, hh] = h;
          for (let i = 0; i < 80; i++) {
            const s1 = rotr64(e, 14) ^ rotr64(e, 18) ^ rotr64(e, 41);
            const ch = e & f ^ ~e & g;
            const temp1 = add64(hh, s1, ch, SHA512_K[i], w[i]);
            const s0 = rotr64(a, 28) ^ rotr64(a, 34) ^ rotr64(a, 39);
            const maj = a & b ^ a & c ^ b & c;
            const temp2 = add64(s0, maj);
            hh = g;
            g = f;
            f = e;
            e = add64(d, temp1);
            d = c;
            c = b;
            b = a;
            a = add64(temp1, temp2);
          }
          for (const [i, value] of [a, b, c, d, e, f, g, hh].entries()) {
            h[i] = add64(h[i], value);
          }
        }
        return words64ToBytes(h);
      }
      function sha384Bytes(bytes) {
        return sha512Core(
          bytes,
          [
            0xcbbb9d5dc1059ed8n,
            0x629a292a367cd507n,
            0x9159015a3070dd17n,
            0x152fecd8f70e5939n,
            0x67332667ffc00b31n,
            0x8eb44a8768581511n,
            0xdb0c2e0d64f98fa7n,
            0x47b5481dbefa4fa4n
          ]
        ).slice(0, 48);
      }
      function sha512Bytes(bytes) {
        return sha512Core(
          bytes,
          [
            0x6a09e667f3bcc908n,
            0xbb67ae8584caa73bn,
            0x3c6ef372fe94f82bn,
            0xa54ff53a5f1d36f1n,
            0x510e527fade682d1n,
            0x9b05688c2b3e6c1fn,
            0x1f83d9abfb41bd6bn,
            0x5be0cd19137e2179n
          ]
        );
      }
      var ALGORITHMS = {
        md5: { blockSize: 64, digest: md5Bytes },
        sha1: { blockSize: 64, digest: sha1Bytes },
        sha224: { blockSize: 64, digest: sha224Bytes },
        sha256: { blockSize: 64, digest: sha256Bytes },
        sha384: { blockSize: 128, digest: sha384Bytes },
        sha512: { blockSize: 128, digest: sha512Bytes }
      };
      function digestBytes2(algorithm, value, fnName) {
        assertBinary(value, fnName);
        return ALGORITHMS[algorithm].digest(value.bytes);
      }
      function hmacBytes2(algorithm, value, key, fnName) {
        assertBinary(value, fnName);
        assertBinary(key, fnName, "BinaryString key");
        const spec = ALGORITHMS[algorithm];
        let keyBytes = key.bytes;
        if (keyBytes.length > spec.blockSize) {
          keyBytes = spec.digest(keyBytes);
        }
        const paddedKey = new Uint8Array(spec.blockSize);
        paddedKey.set(keyBytes);
        const innerKey = new Uint8Array(spec.blockSize);
        const outerKey = new Uint8Array(spec.blockSize);
        for (let i = 0; i < spec.blockSize; i++) {
          innerKey[i] = paddedKey[i] ^ 54;
          outerKey[i] = paddedKey[i] ^ 92;
        }
        return spec.digest(concatBytes2(outerKey, spec.digest(concatBytes2(innerKey, value.bytes))));
      }
      module2.exports = {
        digestBytes: digestBytes2,
        hmacBytes: hmacBytes2,
        toBinary,
        bytesToHex,
        bytesToBase64
      };
    }
  });

  // modules/std/secure.js
  var require_secure = __commonJS({
    "modules/std/secure.js"(exports, module) {
      "use strict";
      var { BinaryString } = require_runtime_helpers();
      var taskRuntime = require_task();
      var { digestBytes, hmacBytes } = require_hash();
      var { Time } = require_time();
      var BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
      var MAX_SAFE_INT = 9007199254740992;
      var RANDOM_CAPABILITIES = /* @__PURE__ */ new Set(["bytes", "token", "int"]);
      var KDF_CAPABILITIES = /* @__PURE__ */ new Set(["hkdf-sha256"]);
      var CIPHER_CAPABILITIES = /* @__PURE__ */ new Set([
        "aes-256-gcm",
        "chacha20-poly1305"
      ]);
      var BROWSER_CIPHER_CAPABILITIES = /* @__PURE__ */ new Set(["aes-256-gcm"]);
      var KEY_AGREEMENT_CAPABILITIES = /* @__PURE__ */ new Set(["x25519"]);
      var CERTIFICATE_CAPABILITIES = /* @__PURE__ */ new Set([
        "parse-x509",
        "parse-x509-der",
        "fingerprint-sha256",
        "public-key",
        "verify-chain"
      ]);
      var BROWSER_CERTIFICATE_CAPABILITIES = /* @__PURE__ */ new Set([
        "parse-x509-der",
        "fingerprint-sha256"
      ]);
      var TLS_IDENTITY_CAPABILITIES = /* @__PURE__ */ new Set(["pem", "pkcs12"]);
      var BROWSER_TLS_IDENTITY_CAPABILITIES = /* @__PURE__ */ new Set(["pem"]);
      var SIGNING_CAPABILITIES = /* @__PURE__ */ new Set([
        "ed25519",
        "ecdsa-p256-sha256",
        "ecdsa-p384-sha384"
      ]);
      var SIGNING_ALGORITHMS = {
        ed25519: {
          type: "ed25519",
          privateLength: 32,
          publicLength: 32
        },
        "ecdsa-p256-sha256": {
          type: "ecdsa",
          privateLength: 32,
          publicLength: 65,
          signatureLength: 64,
          nodeCurve: "prime256v1",
          webCurve: "P-256",
          jwkCurve: "P-256",
          nodeHash: "sha256",
          webHash: "SHA-256"
        },
        "ecdsa-p384-sha384": {
          type: "ecdsa",
          privateLength: 48,
          publicLength: 97,
          signatureLength: 96,
          nodeCurve: "secp384r1",
          webCurve: "P-384",
          jwkCurve: "P-384",
          nodeHash: "sha384",
          webHash: "SHA-384"
        }
      };
      var KEY_AGREEMENT_ALGORITHMS = {
        x25519: {
          privateLength: 32,
          publicLength: 32
        }
      };
      var DEFAULT_PASSWORD_HASH_ALGORITHM = "pbkdf2-sha256";
      var HKDF_SHA256_HASH_LENGTH = 32;
      var HKDF_SHA256_MAX_LENGTH = 255 * HKDF_SHA256_HASH_LENGTH;
      var CIPHER_ALGORITHMS = {
        "aes-256-gcm": {
          keyLength: 32,
          nonceLength: 12,
          tagLength: 16,
          nodeName: "aes-256-gcm",
          webName: "AES-GCM"
        },
        "chacha20-poly1305": {
          keyLength: 32,
          nonceLength: 12,
          tagLength: 16,
          nodeName: "chacha20-poly1305",
          webName: null
        }
      };
      var PASSWORD_HASH_SALT_LENGTH = 16;
      var PASSWORD_HASH_LENGTH = 32;
      var PBKDF2_SHA256_ITERATIONS = 6e5;
      var SCRYPT_LOG_N = 17;
      var SCRYPT_R = 8;
      var SCRYPT_P = 1;
      var runtimePolicy = {
        host_name: "node"
      };
      function setRuntimePolicy(policy = {}) {
        runtimePolicy = {
          ...runtimePolicy,
          ...policy
        };
      }
      function capabilities() {
        return {
          host: hostName(),
          random: hasRandomSource(),
          password_hash: passwordHashCapabilities(),
          kdf: [...KDF_CAPABILITIES],
          cipher: cipherCapabilities(),
          key_agreement: keyAgreementCapabilities(),
          signing: signingCapabilities(),
          certificate: certificateCapabilities(),
          tls_identity: tlsIdentityCapabilities(),
          async_required: {
            cipher: hostName() === "browser",
            kdf: false,
            password_hash: hostName() === "browser",
            signing: hostName() === "browser",
            key_agreement: hostName() === "browser" && keyAgreementCapabilities().length > 0
          }
        };
      }
      function hostName() {
        return runtimePolicy.host_name || "node";
      }
      function capabilityPart(value) {
        return value == null ? "" : String(value);
      }
      function passwordHashCapabilities() {
        return hostName() === "browser" ? ["pbkdf2-sha256"] : ["pbkdf2-sha256", "scrypt"];
      }
      function signingCapabilities() {
        if (hostName() === "browser") {
          return ["ecdsa-p256-sha256", "ecdsa-p384-sha384"];
        }
        return [...SIGNING_CAPABILITIES];
      }
      function keyAgreementCapabilities() {
        if (hostName() === "browser") {
          return subtleKeyAgreementCrypto() ? ["x25519"] : [];
        }
        const crypto = nodeCrypto();
        return crypto && typeof crypto.generateKeyPairSync === "function" && typeof crypto.diffieHellman === "function" ? [...KEY_AGREEMENT_CAPABILITIES] : [];
      }
      function cipherCapabilities() {
        if (hostName() === "browser") {
          return [...BROWSER_CIPHER_CAPABILITIES];
        }
        const crypto = nodeCrypto();
        if (!crypto || typeof crypto.getCiphers !== "function") {
          return [];
        }
        const supported = new Set(crypto.getCiphers());
        return [...CIPHER_CAPABILITIES].filter((algorithm) => {
          const meta = CIPHER_ALGORITHMS[algorithm];
          return meta && supported.has(meta.nodeName);
        });
      }
      function certificateCapabilities() {
        return hostName() === "browser" ? [...BROWSER_CERTIFICATE_CAPABILITIES] : [...CERTIFICATE_CAPABILITIES];
      }
      function tlsIdentityCapabilities() {
        return hostName() === "browser" ? [...BROWSER_TLS_IDENTITY_CAPABILITIES] : [...TLS_IDENTITY_CAPABILITIES];
      }
      function hasCapability(area, name2) {
        area = capabilityPart(area);
        name2 = capabilityPart(name2);
        if (area === "random") {
          return hasRandomSource() && RANDOM_CAPABILITIES.has(name2);
        }
        if (area === "password_hash") {
          return passwordHashCapabilities().includes(name2);
        }
        if (area === "kdf") {
          return KDF_CAPABILITIES.has(name2);
        }
        if (area === "cipher") {
          return cipherCapabilities().includes(name2);
        }
        if (area === "key_agreement") {
          return keyAgreementCapabilities().includes(name2);
        }
        if (area === "signing") {
          return signingCapabilities().includes(name2);
        }
        if (area === "certificate") {
          return certificateCapabilities().includes(name2);
        }
        if (area === "tls_identity") {
          return tlsIdentityCapabilities().includes(name2);
        }
        return false;
      }
      function requireCapability(area, name2) {
        area = capabilityPart(area);
        name2 = capabilityPart(name2);
        if (hasCapability(area, name2)) {
          return true;
        }
        throw new Error(
          `Secure capability '${area}/${name2}' is not available on host '${hostName()}'`
        );
      }
      function hasRandomSource() {
        if (globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") {
          return true;
        }
        const crypto = nodeCrypto();
        return !!(crypto && typeof crypto.randomBytes === "function");
      }
      function nodeCrypto() {
        if (typeof __require !== "function") {
          return null;
        }
        try {
          return __require("node:crypto");
        } catch (_err) {
          return null;
        }
      }
      function nodeForge() {
        if (hostName() === "browser" || typeof __require !== "function") {
          return null;
        }
        try {
          const nodeRequire = eval("require");
          return nodeRequire("node-forge");
        } catch (_err) {
          return null;
        }
      }
      function nodeTls() {
        if (hostName() === "browser" || typeof __require !== "function") {
          return null;
        }
        try {
          const nodeRequire = eval("require");
          return nodeRequire("node:tls");
        } catch (_err) {
          return null;
        }
      }
      function fillRandom(bytes) {
        if (globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") {
          for (let offset = 0; offset < bytes.length; offset += 65536) {
            globalThis.crypto.getRandomValues(
              bytes.subarray(offset, Math.min(offset + 65536, bytes.length))
            );
          }
          return bytes;
        }
        const crypto = nodeCrypto();
        if (crypto && typeof crypto.randomBytes === "function") {
          bytes.set(crypto.randomBytes(bytes.length));
          return bytes;
        }
        throw new Error("Secure random source is unavailable");
      }
      function nonNegativeInteger(value, label) {
        const number = Number(value ?? 0);
        if (!Number.isInteger(number) || number < 0) {
          throw new Error(`${label} expects a non-negative integer`);
        }
        return number;
      }
      function positiveInteger(value, label) {
        const number = Number(value ?? 0);
        if (!Number.isInteger(number) || number <= 0) {
          throw new Error(`${label} expects a positive integer`);
        }
        if (number > MAX_SAFE_INT) {
          throw new Error(`${label} maximum is too large`);
        }
        return number;
      }
      function randomBytes(length) {
        return fillRandom(new Uint8Array(length));
      }
      function base64url(bytes) {
        let out = "";
        for (let i = 0; i < bytes.length; i += 3) {
          const b0 = bytes[i];
          const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;
          const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;
          const triple = b0 << 16 | b1 << 8 | b2;
          out += BASE64URL[triple >> 18 & 63];
          out += BASE64URL[triple >> 12 & 63];
          if (i + 1 < bytes.length) {
            out += BASE64URL[triple >> 6 & 63];
          }
          if (i + 2 < bytes.length) {
            out += BASE64URL[triple & 63];
          }
        }
        return out;
      }
      function base64urlDecode(text) {
        if (typeof text !== "string" || /[^A-Za-z0-9_-]/u.test(text)) {
          return null;
        }
        const alphabet = new Map(BASE64URL.split("").map(
          (value, index) => [value, index]
        ));
        const out = [];
        let bits = 0;
        let bitLength = 0;
        for (const char of text) {
          bits = bits << 6 | alphabet.get(char);
          bitLength += 6;
          while (bitLength >= 8) {
            bitLength -= 8;
            out.push(bits >> bitLength & 255);
          }
        }
        if (bitLength > 0 && (bits & (1 << bitLength) - 1) !== 0) {
          return null;
        }
        return Uint8Array.from(out);
      }
      function base64(bytes) {
        const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        let out = "";
        for (let i = 0; i < bytes.length; i += 3) {
          const b0 = bytes[i];
          const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;
          const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;
          const triple = b0 << 16 | b1 << 8 | b2;
          out += alphabet[triple >> 18 & 63];
          out += alphabet[triple >> 12 & 63];
          out += i + 1 < bytes.length ? alphabet[triple >> 6 & 63] : "=";
          out += i + 2 < bytes.length ? alphabet[triple & 63] : "=";
        }
        return out;
      }
      function base64Decode(text) {
        if (typeof text !== "string" || /[^A-Za-z0-9+/=]/u.test(text)) {
          return null;
        }
        const clean = text.replace(/=+$/u, "");
        const alphabet = new Map(
          "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").map((value, index) => [value, index])
        );
        const out = [];
        let bits = 0;
        let bitLength = 0;
        for (const char of clean) {
          if (!alphabet.has(char)) {
            return null;
          }
          bits = bits << 6 | alphabet.get(char);
          bitLength += 6;
          while (bitLength >= 8) {
            bitLength -= 8;
            out.push(bits >> bitLength & 255);
          }
        }
        return Uint8Array.from(out);
      }
      function pemToDer(pem, label) {
        const text = assertString(pem, label, "String key");
        const body = text.replace(/-----BEGIN [^-]+-----/gu, "").replace(/-----END [^-]+-----/gu, "").replace(/\s+/gu, "");
        const bytes = base64Decode(body);
        if (!bytes) {
          throw new Error(`${label} expects PEM key text`);
        }
        return bytes;
      }
      function derToPem(label, der) {
        const encoded = base64(der);
        const lines = [];
        for (let i = 0; i < encoded.length; i += 64) {
          lines.push(encoded.slice(i, i + 64));
        }
        return `-----BEGIN ${label}-----
${lines.join("\n")}
-----END ${label}-----
`;
      }
      function certificateDerToPem(der) {
        return derToPem("CERTIFICATE", der);
      }
      function certificatePemBlocks(pem, label) {
        const text = assertString(pem, label, "String pem");
        const blocks = [];
        const re = /-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/gu;
        let match;
        while (match = re.exec(text)) {
          const bytes = base64Decode(match[1].replace(/\s+/gu, ""));
          if (!bytes) {
            throw new Error(`${label} expects PEM certificate text`);
          }
          blocks.push(bytes);
        }
        if (blocks.length === 0) {
          throw new Error(`${label} expects PEM certificate text`);
        }
        return blocks;
      }
      function randomInt(max) {
        if (max === 1) {
          return 0;
        }
        const space = 2 ** 56;
        const limit = space - space % max;
        while (true) {
          const bytes = randomBytes(7);
          let value = 0;
          for (const byte of bytes) {
            value = value * 256 + byte;
          }
          if (value < limit) {
            return value % max;
          }
        }
      }
      function typeName(value) {
        if (value == null) {
          return "Null";
        }
        if (value && value.bytes instanceof Uint8Array) {
          return "BinaryString";
        }
        if (typeof value === "string") {
          return "String";
        }
        return value.constructor && value.constructor.name ? value.constructor.name : typeof value;
      }
      function isPlainObject(value) {
        return value != null && typeof value === "object" && !Array.isArray(value) && !(value.bytes instanceof Uint8Array);
      }
      function assertBinaryString(value, label, argName = "BinaryString") {
        if (value && value.bytes instanceof Uint8Array) {
          return value.bytes;
        }
        throw new Error(
          `TypeException: ${label} expects ${argName}, got ${typeName(value)}`
        );
      }
      function optionalBinaryString(value, label, argName) {
        if (value == null) {
          return new Uint8Array(0);
        }
        return assertBinaryString(value, label, argName);
      }
      function optionalDict(value, label, argName = "Dict") {
        if (value == null) {
          return {};
        }
        if (isPlainObject(value)) {
          return value;
        }
        throw new Error(
          `TypeException: ${label} expects ${argName}, got ${typeName(value)}`
        );
      }
      function assertString(value, label, argName = "String") {
        if (typeof value === "string") {
          return value;
        }
        throw new Error(
          `TypeException: ${label} expects ${argName}, got ${typeName(value)}`
        );
      }
      function cipherAlgorithm(value, label) {
        const algorithm = value == null ? "aes-256-gcm" : String(value);
        if (!CIPHER_ALGORITHMS[algorithm] || !cipherCapabilities().includes(algorithm)) {
          throw new Error(`${label} cipher algorithm '${algorithm}' is not available`);
        }
        return algorithm;
      }
      function cipherOptions(value, label) {
        const options = optionalDict(value, label, "Dict options");
        const algorithmValue = options.algorithm;
        return {
          algorithm: cipherAlgorithm(algorithmValue, label),
          algorithmSupplied: algorithmValue != null,
          aad: optionalBinaryString(options.aad, label, "BinaryString aad")
        };
      }
      function cipherMeta(algorithm) {
        return CIPHER_ALGORITHMS[algorithm];
      }
      function cipherKey(value, label, meta) {
        const key = assertBinaryString(value, label, "BinaryString key");
        if (key.length !== meta.keyLength) {
          throw new Error(`${label} expects a ${meta.keyLength}-byte key`);
        }
        return key;
      }
      function envelopeBytes(envelope, field, label, length = null) {
        const bytes = assertBinaryString(
          envelope[field],
          label,
          `BinaryString envelope.${field}`
        );
        if (length != null && bytes.length !== length) {
          throw new Error(`${label} expects envelope.${field} to be ${length} bytes`);
        }
        return bytes;
      }
      function cipherEnvelope(value, label) {
        const envelope = optionalDict(value, label, "Dict envelope");
        if (envelope.version !== 1) {
          throw new Error(`${label} expects envelope.version 1`);
        }
        const algorithm = cipherAlgorithm(envelope.algorithm, label);
        const meta = cipherMeta(algorithm);
        return {
          algorithm,
          nonce: envelopeBytes(envelope, "nonce", label, meta.nonceLength),
          ciphertext: envelopeBytes(envelope, "ciphertext", label),
          tag: envelopeBytes(envelope, "tag", label, meta.tagLength)
        };
      }
      function cipherEnvelopeValue(algorithm, nonce, ciphertext, tag) {
        return {
          version: 1,
          algorithm,
          nonce: new BinaryString(nonce),
          ciphertext: new BinaryString(ciphertext),
          tag: new BinaryString(tag)
        };
      }
      function hkdfLength(value, label) {
        const number = Number(value);
        if (!Number.isInteger(number) || number < 0 || number > HKDF_SHA256_MAX_LENGTH) {
          throw new Error(
            `${label} expects length between 0 and ${HKDF_SHA256_MAX_LENGTH}`
          );
        }
        return number;
      }
      function concatBytes(...items) {
        const total = items.reduce((sum, item) => sum + item.length, 0);
        const out = new Uint8Array(total);
        let offset = 0;
        for (const item of items) {
          out.set(item, offset);
          offset += item.length;
        }
        return out;
      }
      function hmacSha256(key, value) {
        return hmacBytes(
          "sha256",
          new BinaryString(value),
          new BinaryString(key),
          "KeyDerivation.hkdf_sha256"
        );
      }
      function hkdfSha256Bytes(inputKeyMaterial, length, salt, info) {
        if (length === 0) {
          return new Uint8Array(0);
        }
        const prk = hmacSha256(salt, inputKeyMaterial);
        let previous = new Uint8Array(0);
        let out = new Uint8Array(0);
        let counter = 1;
        while (out.length < length) {
          previous = hmacSha256(
            prk,
            concatBytes(previous, info, Uint8Array.of(counter))
          );
          out = concatBytes(out, previous);
          counter++;
        }
        return out.slice(0, length);
      }
      function hkdfSha256Inputs(inputKeyMaterial, length, salt, info) {
        const label = "KeyDerivation.hkdf_sha256";
        return {
          inputKeyMaterial: assertBinaryString(inputKeyMaterial, label),
          length: hkdfLength(length, label),
          salt: optionalBinaryString(salt, label, "BinaryString salt"),
          info: optionalBinaryString(info, label, "BinaryString info")
        };
      }
      function hkdfSha256(inputKeyMaterial, length, salt = null, info = null) {
        const args = hkdfSha256Inputs(inputKeyMaterial, length, salt, info);
        return new BinaryString(
          hkdfSha256Bytes(
            args.inputKeyMaterial,
            args.length,
            args.salt,
            args.info
          )
        );
      }
      function passwordBytes(value, label) {
        return new TextEncoder().encode(
          assertString(value, label, "String password")
        );
      }
      function optionString(options, key, fallback) {
        return options[key] == null ? fallback : String(options[key]);
      }
      function optionPositiveInteger(options, key, fallback, label) {
        if (options[key] == null) {
          return fallback;
        }
        return positiveInteger(options[key], `${label} option '${key}'`);
      }
      function passwordHashAlgorithm(options, label) {
        const algorithm = optionString(
          options,
          "algorithm",
          DEFAULT_PASSWORD_HASH_ALGORITHM
        );
        if (!passwordHashCapabilities().includes(algorithm)) {
          throw new Error(
            `${label} password hash algorithm '${algorithm}' is not available`
          );
        }
        return algorithm;
      }
      function pbkdf2Options(options, label) {
        return {
          iterations: optionPositiveInteger(
            options,
            "iterations",
            PBKDF2_SHA256_ITERATIONS,
            label
          ),
          length: optionPositiveInteger(
            options,
            "length",
            PASSWORD_HASH_LENGTH,
            label
          )
        };
      }
      function scryptOptions(options, label) {
        let logN = optionPositiveInteger(options, "log_n", SCRYPT_LOG_N, label);
        const defaultCost = 2 ** logN;
        const cost = optionPositiveInteger(options, "cost", defaultCost, label);
        if (cost < 2 || (cost & cost - 1) !== 0) {
          throw new Error(`${label} option 'cost' must be a power of two`);
        }
        logN = Math.log2(cost);
        return {
          logN,
          cost,
          r: optionPositiveInteger(options, "r", SCRYPT_R, label),
          p: optionPositiveInteger(options, "p", SCRYPT_P, label),
          length: optionPositiveInteger(
            options,
            "length",
            PASSWORD_HASH_LENGTH,
            label
          )
        };
      }
      function constantTimeEqual(left, right) {
        if (!left || !right || left.length !== right.length) {
          return false;
        }
        let diff = 0;
        for (let i = 0; i < left.length; i++) {
          diff |= left[i] ^ right[i];
        }
        return diff === 0;
      }
      function parseParamList(text) {
        const out = {};
        for (const part of text.split(",")) {
          const index = part.indexOf("=");
          if (index <= 0) {
            return null;
          }
          out[part.slice(0, index)] = part.slice(index + 1);
        }
        return out;
      }
      function parsePasswordHash(encoded) {
        if (typeof encoded !== "string") {
          return null;
        }
        let match = encoded.match(
          /^\$zuzu-pbkdf2-sha256\$v=1\$([^$]+)\$([^$]+)\$([^$]+)$/u
        );
        if (match) {
          const params = parseParamList(match[1]);
          if (!params || !/^\d+$/u.test(params.i || "") || !/^\d+$/u.test(params.l || "")) {
            return null;
          }
          const salt = base64urlDecode(match[2]);
          const hash = base64urlDecode(match[3]);
          if (!salt || !hash) {
            return null;
          }
          return {
            algorithm: "pbkdf2-sha256",
            iterations: Number(params.i),
            length: Number(params.l),
            salt,
            hash
          };
        }
        match = encoded.match(
          /^\$scrypt\$([^$]+)\$([^$]+)\$([^$]+)$/u
        );
        if (match) {
          const params = parseParamList(match[1]);
          if (!params || !/^\d+$/u.test(params.ln || "") || !/^\d+$/u.test(params.r || "") || !/^\d+$/u.test(params.p || "") || !/^\d+$/u.test(params.l || "")) {
            return null;
          }
          const salt = base64urlDecode(match[2]);
          const hash = base64urlDecode(match[3]);
          if (!salt || !hash) {
            return null;
          }
          return {
            algorithm: "scrypt",
            log_n: Number(params.ln),
            r: Number(params.r),
            p: Number(params.p),
            length: Number(params.l),
            salt,
            hash
          };
        }
        return null;
      }
      function nodePbkdf2(password, salt, iterations, length) {
        const crypto = nodeCrypto();
        if (!crypto || typeof crypto.pbkdf2Sync !== "function") {
          throw new Error("PBKDF2-SHA256 is unavailable on this host");
        }
        return new Uint8Array(
          crypto.pbkdf2Sync(password, salt, iterations, length, "sha256")
        );
      }
      function nodeScrypt(password, salt, options) {
        const crypto = nodeCrypto();
        if (!crypto || typeof crypto.scryptSync !== "function") {
          throw new Error("scrypt is unavailable on this host");
        }
        return new Uint8Array(
          crypto.scryptSync(
            password,
            salt,
            options.length,
            {
              N: options.cost,
              r: options.r,
              p: options.p,
              maxmem: Math.max(
                32 * 1024 * 1024,
                128 * options.cost * options.r + 64 * 1024 * 1024
              )
            }
          )
        );
      }
      function passwordHashDeriveBytes(password, algorithm, salt, options, label) {
        if (algorithm === "pbkdf2-sha256") {
          const pbkdf2Opts = pbkdf2Options(options, label);
          return nodePbkdf2(
            password,
            salt,
            pbkdf2Opts.iterations,
            pbkdf2Opts.length
          );
        }
        if (algorithm === "scrypt") {
          return nodeScrypt(password, salt, scryptOptions(options, label));
        }
        throw new Error(`${label} does not support algorithm '${algorithm}'`);
      }
      async function webCryptoPbkdf2(password, salt, iterations, length) {
        const subtle = subtleCrypto();
        if (!subtle) {
          throw new Error("Web Crypto PBKDF2-SHA256 is unavailable");
        }
        const key = await subtle.importKey(
          "raw",
          password,
          "PBKDF2",
          false,
          ["deriveBits"]
        );
        const bits = await subtle.deriveBits(
          {
            name: "PBKDF2",
            hash: "SHA-256",
            salt,
            iterations
          },
          key,
          length * 8
        );
        return new Uint8Array(bits);
      }
      async function passwordHashDeriveBytesAsync(password, algorithm, salt, options, label) {
        if (algorithm === "pbkdf2-sha256" && hostName() === "browser") {
          const pbkdf2Opts = pbkdf2Options(options, label);
          return webCryptoPbkdf2(
            password,
            salt,
            pbkdf2Opts.iterations,
            pbkdf2Opts.length
          );
        }
        return passwordHashDeriveBytes(password, algorithm, salt, options, label);
      }
      function passwordHash(passwordValue, optionsValue = null) {
        const label = "PasswordHash.hash";
        if (hostName() === "browser") {
          throw new Error(
            "PasswordHash.hash is not available synchronously on host browser; use PasswordHash.hash_async"
          );
        }
        const password = passwordBytes(passwordValue, label);
        const options = optionalDict(optionsValue, label, "Dict options");
        const algorithm = passwordHashAlgorithm(options, label);
        const salt = options.salt == null ? randomBytes(PASSWORD_HASH_SALT_LENGTH) : assertBinaryString(options.salt, label, "BinaryString salt");
        const hash = passwordHashDeriveBytes(
          password,
          algorithm,
          salt,
          options,
          label
        );
        if (algorithm === "pbkdf2-sha256") {
          const pbkdf2Opts = pbkdf2Options(options, label);
          return [
            "",
            "zuzu-pbkdf2-sha256",
            "v=1",
            `i=${pbkdf2Opts.iterations},l=${pbkdf2Opts.length}`,
            base64url(salt),
            base64url(hash)
          ].join("$");
        }
        const scryptOpts = scryptOptions(options, label);
        return [
          "",
          "scrypt",
          `ln=${scryptOpts.logN},r=${scryptOpts.r},p=${scryptOpts.p},l=${scryptOpts.length}`,
          base64url(salt),
          base64url(hash)
        ].join("$");
      }
      async function passwordHashAsyncValue(passwordValue, optionsValue = null) {
        const label = "PasswordHash.hash";
        const password = passwordBytes(passwordValue, label);
        const options = optionalDict(optionsValue, label, "Dict options");
        const algorithm = passwordHashAlgorithm(options, label);
        const salt = options.salt == null ? randomBytes(PASSWORD_HASH_SALT_LENGTH) : assertBinaryString(options.salt, label, "BinaryString salt");
        const hash = await passwordHashDeriveBytesAsync(
          password,
          algorithm,
          salt,
          options,
          label
        );
        if (algorithm === "pbkdf2-sha256") {
          const pbkdf2Opts = pbkdf2Options(options, label);
          return [
            "",
            "zuzu-pbkdf2-sha256",
            "v=1",
            `i=${pbkdf2Opts.iterations},l=${pbkdf2Opts.length}`,
            base64url(salt),
            base64url(hash)
          ].join("$");
        }
        const scryptOpts = scryptOptions(options, label);
        return [
          "",
          "scrypt",
          `ln=${scryptOpts.logN},r=${scryptOpts.r},p=${scryptOpts.p},l=${scryptOpts.length}`,
          base64url(salt),
          base64url(hash)
        ].join("$");
      }
      function passwordHashVerify(passwordValue, encodedValue) {
        const label = "PasswordHash.verify";
        if (hostName() === "browser") {
          throw new Error(
            "PasswordHash.verify is not available synchronously on host browser; use PasswordHash.verify_async"
          );
        }
        const password = passwordBytes(passwordValue, label);
        const encoded = assertString(encodedValue, label, "String encoded_hash");
        const parsed = parsePasswordHash(encoded);
        if (!parsed || !passwordHashCapabilities().includes(parsed.algorithm)) {
          return false;
        }
        try {
          const hash = passwordHashDeriveBytes(
            password,
            parsed.algorithm,
            parsed.salt,
            parsed,
            label
          );
          return constantTimeEqual(hash, parsed.hash);
        } catch (_err) {
          return false;
        }
      }
      async function passwordHashVerifyAsyncValue(passwordValue, encodedValue) {
        const label = "PasswordHash.verify";
        const password = passwordBytes(passwordValue, label);
        const encoded = assertString(encodedValue, label, "String encoded_hash");
        const parsed = parsePasswordHash(encoded);
        if (!parsed || !passwordHashCapabilities().includes(parsed.algorithm)) {
          return false;
        }
        try {
          const hash = await passwordHashDeriveBytesAsync(
            password,
            parsed.algorithm,
            parsed.salt,
            parsed,
            label
          );
          return constantTimeEqual(hash, parsed.hash);
        } catch (_err) {
          return false;
        }
      }
      function passwordHashNeedsRehash(encodedValue, optionsValue = null) {
        const label = "PasswordHash.needs_rehash";
        const encoded = assertString(encodedValue, label, "String encoded_hash");
        const options = optionalDict(optionsValue, label, "Dict options");
        const target = passwordHashAlgorithm(options, label);
        const parsed = parsePasswordHash(encoded);
        if (!parsed || parsed.algorithm !== target) {
          return true;
        }
        if (target === "pbkdf2-sha256") {
          const pbkdf2Opts = pbkdf2Options(options, label);
          return parsed.iterations < pbkdf2Opts.iterations || parsed.length !== pbkdf2Opts.length;
        }
        if (target === "scrypt") {
          const scryptOpts = scryptOptions(options, label);
          return parsed.log_n < scryptOpts.logN || parsed.r !== scryptOpts.r || parsed.p !== scryptOpts.p || parsed.length !== scryptOpts.length;
        }
        return true;
      }
      function passwordHashDeriveKey(passwordValue, optionsValue = null) {
        const label = "PasswordHash.derive_key";
        if (hostName() === "browser") {
          throw new Error(
            "PasswordHash.derive_key is not available synchronously on host browser; use PasswordHash.derive_key_async"
          );
        }
        const password = passwordBytes(passwordValue, label);
        const options = optionalDict(optionsValue, label, "Dict options");
        const algorithm = passwordHashAlgorithm(options, label);
        if (options.salt == null) {
          throw new Error(`${label} expects BinaryString salt`);
        }
        const salt = assertBinaryString(options.salt, label, "BinaryString salt");
        return new BinaryString(
          passwordHashDeriveBytes(password, algorithm, salt, options, label)
        );
      }
      async function passwordHashDeriveKeyAsyncValue(passwordValue, optionsValue = null) {
        const label = "PasswordHash.derive_key";
        const password = passwordBytes(passwordValue, label);
        const options = optionalDict(optionsValue, label, "Dict options");
        const algorithm = passwordHashAlgorithm(options, label);
        if (options.salt == null) {
          throw new Error(`${label} expects BinaryString salt`);
        }
        const salt = assertBinaryString(options.salt, label, "BinaryString salt");
        return new BinaryString(
          await passwordHashDeriveBytesAsync(
            password,
            algorithm,
            salt,
            options,
            label
          )
        );
      }
      function subtleCrypto() {
        return globalThis.crypto && globalThis.crypto.subtle && typeof globalThis.crypto.subtle.importKey === "function" && typeof globalThis.crypto.subtle.deriveBits === "function" ? globalThis.crypto.subtle : null;
      }
      function subtleAesCrypto() {
        return globalThis.crypto && globalThis.crypto.subtle && typeof globalThis.crypto.subtle.importKey === "function" && typeof globalThis.crypto.subtle.encrypt === "function" && typeof globalThis.crypto.subtle.decrypt === "function" ? globalThis.crypto.subtle : null;
      }
      function cipherGenerateKey(algorithm = "aes-256-gcm") {
        const actual = cipherAlgorithm(algorithm, "Cipher.generate_key");
        return new BinaryString(randomBytes(cipherMeta(actual).keyLength));
      }
      function nodeCipherEncrypt(plaintext, key, options) {
        const crypto = nodeCrypto();
        const meta = cipherMeta(options.algorithm);
        if (!crypto || typeof crypto.createCipheriv !== "function" || !crypto.getCiphers().includes(meta.nodeName)) {
          throw new Error(`${options.algorithm} is unavailable on this host`);
        }
        const nonce = randomBytes(meta.nonceLength);
        const cipher = crypto.createCipheriv(
          meta.nodeName,
          key,
          nonce,
          { authTagLength: meta.tagLength }
        );
        cipher.setAAD(options.aad);
        const ciphertext = concatBytes(
          cipher.update(plaintext),
          cipher.final()
        );
        const tag = new Uint8Array(cipher.getAuthTag());
        return cipherEnvelopeValue(options.algorithm, nonce, ciphertext, tag);
      }
      function nodeCipherDecrypt(envelope, key, options) {
        const crypto = nodeCrypto();
        const meta = cipherMeta(envelope.algorithm);
        if (!crypto || typeof crypto.createDecipheriv !== "function" || !crypto.getCiphers().includes(meta.nodeName)) {
          throw new Error(`${envelope.algorithm} is unavailable on this host`);
        }
        try {
          const decipher = crypto.createDecipheriv(
            meta.nodeName,
            key,
            envelope.nonce,
            { authTagLength: meta.tagLength }
          );
          decipher.setAAD(options.aad);
          decipher.setAuthTag(envelope.tag);
          return new BinaryString(
            concatBytes(
              decipher.update(envelope.ciphertext),
              decipher.final()
            )
          );
        } catch (_err) {
          throw new Error("Cipher.decrypt authentication failed");
        }
      }
      function cipherEncrypt(plaintext, key, options = null) {
        const label = "Cipher.encrypt";
        const bytes = assertBinaryString(plaintext, label, "BinaryString plaintext");
        const cipherOpts = cipherOptions(options, label);
        const keyBytes = cipherKey(key, label, cipherMeta(cipherOpts.algorithm));
        if (hostName() === "browser") {
          throw new Error(
            "Cipher.encrypt is not available synchronously on host browser; use Cipher.encrypt_async"
          );
        }
        return nodeCipherEncrypt(bytes, keyBytes, cipherOpts);
      }
      function cipherDecrypt(envelope, key, options = null) {
        const label = "Cipher.decrypt";
        const cipherOpts = cipherOptions(options, label);
        const cipherEnv = cipherEnvelope(envelope, label);
        if (cipherOpts.algorithmSupplied && cipherOpts.algorithm !== cipherEnv.algorithm) {
          throw new Error(
            `${label} options.algorithm does not match envelope.algorithm`
          );
        }
        const keyBytes = cipherKey(key, label, cipherMeta(cipherEnv.algorithm));
        if (hostName() === "browser") {
          throw new Error(
            "Cipher.decrypt is not available synchronously on host browser; use Cipher.decrypt_async"
          );
        }
        return nodeCipherDecrypt(cipherEnv, keyBytes, cipherOpts);
      }
      async function webCryptoCipherEncrypt(plaintext, key, options) {
        if (options.algorithm !== "aes-256-gcm") {
          throw new Error(`${options.algorithm} is unavailable on host browser`);
        }
        const subtle = subtleAesCrypto();
        if (!subtle) {
          throw new Error("Web Crypto AES-GCM is unavailable");
        }
        const meta = cipherMeta(options.algorithm);
        const nonce = randomBytes(meta.nonceLength);
        const cryptoKey = await subtle.importKey(
          "raw",
          key,
          "AES-GCM",
          false,
          ["encrypt"]
        );
        const sealed = new Uint8Array(await subtle.encrypt(
          {
            name: "AES-GCM",
            iv: nonce,
            additionalData: options.aad,
            tagLength: 128
          },
          cryptoKey,
          plaintext
        ));
        return cipherEnvelopeValue(
          options.algorithm,
          nonce,
          sealed.slice(0, sealed.length - meta.tagLength),
          sealed.slice(sealed.length - meta.tagLength)
        );
      }
      async function webCryptoCipherDecrypt(envelope, key, options) {
        if (envelope.algorithm !== "aes-256-gcm") {
          throw new Error(`${envelope.algorithm} is unavailable on host browser`);
        }
        const subtle = subtleAesCrypto();
        if (!subtle) {
          throw new Error("Web Crypto AES-GCM is unavailable");
        }
        const cryptoKey = await subtle.importKey(
          "raw",
          key,
          "AES-GCM",
          false,
          ["decrypt"]
        );
        try {
          const plaintext = await subtle.decrypt(
            {
              name: "AES-GCM",
              iv: envelope.nonce,
              additionalData: options.aad,
              tagLength: 128
            },
            cryptoKey,
            concatBytes(envelope.ciphertext, envelope.tag)
          );
          return new BinaryString(new Uint8Array(plaintext));
        } catch (_err) {
          throw new Error("Cipher.decrypt authentication failed");
        }
      }
      function cipherEncryptAsync(plaintext, key, options = null) {
        const label = "Cipher.encrypt";
        const bytes = assertBinaryString(plaintext, label, "BinaryString plaintext");
        const cipherOpts = cipherOptions(options, label);
        const keyBytes = cipherKey(key, label, cipherMeta(cipherOpts.algorithm));
        if (hostName() === "browser") {
          return taskRuntime.Task.from(
            webCryptoCipherEncrypt(bytes, keyBytes, cipherOpts)
          );
        }
        return taskRuntime.Task.resolved(
          nodeCipherEncrypt(bytes, keyBytes, cipherOpts)
        );
      }
      function cipherDecryptAsync(envelope, key, options = null) {
        const label = "Cipher.decrypt";
        const cipherOpts = cipherOptions(options, label);
        const cipherEnv = cipherEnvelope(envelope, label);
        if (cipherOpts.algorithmSupplied && cipherOpts.algorithm !== cipherEnv.algorithm) {
          throw new Error(
            `${label} options.algorithm does not match envelope.algorithm`
          );
        }
        const keyBytes = cipherKey(key, label, cipherMeta(cipherEnv.algorithm));
        if (hostName() === "browser") {
          return taskRuntime.Task.from(
            webCryptoCipherDecrypt(cipherEnv, keyBytes, cipherOpts)
          );
        }
        return taskRuntime.Task.resolved(
          nodeCipherDecrypt(cipherEnv, keyBytes, cipherOpts)
        );
      }
      async function webCryptoHkdfSha256(args) {
        if (args.length === 0) {
          return new BinaryString();
        }
        const subtle = subtleCrypto();
        if (!subtle) {
          return hkdfSha256(
            new BinaryString(args.inputKeyMaterial),
            args.length,
            new BinaryString(args.salt),
            new BinaryString(args.info)
          );
        }
        const key = await subtle.importKey(
          "raw",
          args.inputKeyMaterial,
          "HKDF",
          false,
          ["deriveBits"]
        );
        const bits = await subtle.deriveBits(
          {
            name: "HKDF",
            hash: "SHA-256",
            salt: args.salt,
            info: args.info
          },
          key,
          args.length * 8
        );
        return new BinaryString(new Uint8Array(bits));
      }
      function signingAlgorithm(algorithm, label) {
        const value = algorithm == null ? "ed25519" : String(algorithm);
        if (!SIGNING_ALGORITHMS[value]) {
          throw new Error(
            `${label} only supports ed25519, ecdsa-p256-sha256, and ecdsa-p384-sha384`
          );
        }
        return value;
      }
      function signingAlgorithmOption(options, label) {
        return options.algorithm == null ? null : signingAlgorithm(options.algorithm, label);
      }
      function browserSigningAlgorithm(algorithm, label) {
        if (!signingCapabilities().includes(algorithm)) {
          throw new Error(
            `${label} signing algorithm '${algorithm}' is not available on host browser`
          );
        }
        return algorithm;
      }
      function signingMeta(algorithm) {
        return SIGNING_ALGORITHMS[algorithm];
      }
      function keyAgreementAlgorithm(value = "x25519", label) {
        if (value == null) {
          value = "x25519";
        }
        value = String(value);
        if (!KEY_AGREEMENT_ALGORITHMS[value]) {
          throw new Error(`${label} only supports x25519`);
        }
        return value;
      }
      function keyAgreementAlgorithmOption(options, label) {
        return options.algorithm == null ? null : keyAgreementAlgorithm(options.algorithm, label);
      }
      function keyAgreementMeta(algorithm) {
        return KEY_AGREEMENT_ALGORITHMS[algorithm];
      }
      function keyFormat(key, optionsValue, label) {
        const options = optionalDict(optionsValue, label, "Dict options");
        if (options.format != null) {
          return String(options.format);
        }
        return key && key.bytes instanceof Uint8Array ? "raw" : "pem";
      }
      function nodeUnsupported(label) {
        throw new Error(`${label} signing is unavailable on this host`);
      }
      function keyAgreementUnsupported(label) {
        throw new Error(`${label} key agreement is unavailable on this host`);
      }
      function derLength(length) {
        if (length < 128) {
          return Uint8Array.of(length);
        }
        const bytes = [];
        while (length > 0) {
          bytes.unshift(length & 255);
          length >>= 8;
        }
        return Uint8Array.of(128 | bytes.length, ...bytes);
      }
      function derElement(tag, body) {
        return concatBytes(Uint8Array.of(tag), derLength(body.length), body);
      }
      function derSequence(...items) {
        return derElement(48, concatBytes(...items));
      }
      function derIntegerSmall(value) {
        return derElement(2, Uint8Array.of(value));
      }
      function derOctetString(bytes) {
        return derElement(4, bytes);
      }
      function derOid(bytes) {
        return derElement(6, Uint8Array.from(bytes));
      }
      function derBitString(bytes) {
        return derElement(3, concatBytes(Uint8Array.of(0), bytes));
      }
      function ecCurveOid(algorithm) {
        return algorithm === "ecdsa-p256-sha256" ? [42, 134, 72, 206, 61, 3, 1, 7] : [43, 129, 4, 0, 34];
      }
      function pkcs8DerFromRawSeed(seed) {
        return concatBytes(
          Uint8Array.from([
            48,
            46,
            2,
            1,
            0,
            48,
            5,
            6,
            3,
            43,
            101,
            112,
            4,
            34,
            4,
            32
          ]),
          seed
        );
      }
      function x25519Pkcs8DerFromRawPrivate(bytes) {
        return concatBytes(
          Uint8Array.from([
            48,
            46,
            2,
            1,
            0,
            48,
            5,
            6,
            3,
            43,
            101,
            110,
            4,
            34,
            4,
            32
          ]),
          bytes
        );
      }
      function x25519SpkiDerFromRawPublic(bytes) {
        return concatBytes(
          Uint8Array.from([
            48,
            42,
            48,
            5,
            6,
            3,
            43,
            101,
            110,
            3,
            33,
            0
          ]),
          bytes
        );
      }
      function ecdsaPkcs8DerFromRawScalar(scalar, algorithm) {
        return derSequence(
          derIntegerSmall(0),
          derSequence(
            derOid([42, 134, 72, 206, 61, 2, 1]),
            derOid(ecCurveOid(algorithm))
          ),
          derOctetString(derSequence(
            derIntegerSmall(1),
            derOctetString(scalar)
          ))
        );
      }
      function ecdsaSpkiDerFromRawPublic(publicKey, algorithm) {
        return derSequence(
          derSequence(
            derOid([42, 134, 72, 206, 61, 2, 1]),
            derOid(ecCurveOid(algorithm))
          ),
          derBitString(publicKey)
        );
      }
      function derReader(bytes) {
        return {
          bytes,
          offset: 0,
          readElement(expectedTag = null) {
            if (this.offset + 2 > this.bytes.length) {
              throw new Error("truncated DER");
            }
            const tag = this.bytes[this.offset++];
            if (expectedTag != null && tag !== expectedTag) {
              throw new Error("unexpected DER tag");
            }
            let length = this.bytes[this.offset++];
            if (length & 128) {
              const count = length & 127;
              if (count === 0 || count > 4 || this.offset + count > this.bytes.length) {
                throw new Error("invalid DER length");
              }
              length = 0;
              for (let i = 0; i < count; ++i) {
                length = length << 8 | this.bytes[this.offset++];
              }
            }
            if (this.offset + length > this.bytes.length) {
              throw new Error("truncated DER value");
            }
            const body = this.bytes.slice(this.offset, this.offset + length);
            this.offset += length;
            return body;
          }
        };
      }
      function derIntegerToFixed(integer, length) {
        let value = integer;
        while (value.length > 0 && value[0] === 0) {
          value = value.slice(1);
        }
        if (value.length > length) {
          throw new Error("ECDSA integer too long");
        }
        const out = new Uint8Array(length);
        out.set(value, length - value.length);
        return out;
      }
      function derToEcdsaRawSignature(signature, algorithm) {
        const meta = signingMeta(algorithm);
        const reader = derReader(signature);
        const seqReader = derReader(reader.readElement(48));
        const r = derIntegerToFixed(
          seqReader.readElement(2),
          meta.signatureLength / 2
        );
        const s = derIntegerToFixed(
          seqReader.readElement(2),
          meta.signatureLength / 2
        );
        if (reader.offset !== signature.length || seqReader.offset !== seqReader.bytes.length) {
          throw new Error("trailing DER data");
        }
        return concatBytes(r, s);
      }
      function ecdsaIntegerFromRaw(bytes) {
        let value = bytes;
        while (value.length > 0 && value[0] === 0) {
          value = value.slice(1);
        }
        if (value.length === 0) {
          value = Uint8Array.of(0);
        }
        if (value[0] & 128) {
          value = concatBytes(Uint8Array.of(0), value);
        }
        return derElement(2, value);
      }
      function ecdsaRawSignatureToDer(signature) {
        const half = signature.length / 2;
        return derSequence(
          ecdsaIntegerFromRaw(signature.slice(0, half)),
          ecdsaIntegerFromRaw(signature.slice(half))
        );
      }
      function algorithmFromJwk(jwk, label) {
        if (jwk.kty === "OKP" && jwk.crv === "Ed25519") {
          return "ed25519";
        }
        if (jwk.kty === "OKP" && jwk.crv === "X25519") {
          return "x25519";
        }
        if (jwk.kty === "EC" && jwk.crv === "P-256") {
          return "ecdsa-p256-sha256";
        }
        if (jwk.kty === "EC" && jwk.crv === "P-384") {
          return "ecdsa-p384-sha384";
        }
        throw new Error(`${label} expects an Ed25519, P-256, P-384, or X25519 key`);
      }
      function algorithmFromNodeKey(key, label) {
        if (key.asymmetricKeyType === "ed25519") {
          return "ed25519";
        }
        if (key.asymmetricKeyType === "ec") {
          const curve = key.asymmetricKeyDetails?.namedCurve;
          if (curve === "prime256v1") {
            return "ecdsa-p256-sha256";
          }
          if (curve === "secp384r1") {
            return "ecdsa-p384-sha384";
          }
        }
        if (key.asymmetricKeyType === "x25519") {
          return "x25519";
        }
        return algorithmFromJwk(key.export({ format: "jwk" }), label);
      }
      function rawPublicFromJwk(jwk, label) {
        const algorithm = algorithmFromJwk(jwk, label);
        if (algorithm === "ed25519") {
          return base64urlDecode(jwk.x);
        }
        if (algorithm === "x25519") {
          const x2 = base64urlDecode(jwk.x);
          if (!x2 || x2.length !== 32) {
            throw new Error(`${label} has invalid X25519 public key`);
          }
          return x2;
        }
        const x = base64urlDecode(jwk.x);
        const y = base64urlDecode(jwk.y);
        const meta = signingMeta(algorithm);
        const width = (meta.publicLength - 1) / 2;
        if (!x || !y || x.length !== width || y.length !== width) {
          throw new Error(`${label} has invalid EC public key coordinates`);
        }
        return concatBytes(Uint8Array.of(4), x, y);
      }
      function rawPrivateFromJwk(jwk, label) {
        const algorithm = algorithmFromJwk(jwk, label);
        const d = base64urlDecode(jwk.d);
        if (algorithm === "x25519") {
          if (!d || d.length !== 32) {
            throw new Error(`${label} has invalid X25519 private key`);
          }
          return d;
        }
        if (!d || d.length !== signingMeta(algorithm).privateLength) {
          throw new Error(`${label} has invalid private key scalar`);
        }
        return d;
      }
      function jwkFromRawPrivate(bytes, algorithm, label) {
        const meta = signingMeta(algorithm);
        if (bytes.length !== meta.privateLength) {
          throw new Error(`${label} expects a ${meta.privateLength}-byte raw private key`);
        }
        if (meta.type === "ed25519") {
          return {
            kty: "OKP",
            crv: "Ed25519",
            d: base64url(bytes)
          };
        }
        return null;
      }
      function jwkFromRawPublic(bytes, algorithm, label) {
        const meta = signingMeta(algorithm);
        if (bytes.length !== meta.publicLength) {
          throw new Error(`${label} expects a ${meta.publicLength}-byte raw public key`);
        }
        if (meta.type === "ed25519") {
          return { kty: "OKP", crv: "Ed25519", x: base64url(bytes) };
        }
        if (bytes[0] !== 4) {
          throw new Error(`${label} expects an uncompressed EC public key`);
        }
        const width = (meta.publicLength - 1) / 2;
        return {
          kty: "EC",
          crv: meta.jwkCurve,
          x: base64url(bytes.slice(1, 1 + width)),
          y: base64url(bytes.slice(1 + width))
        };
      }
      function algorithmFromRawPublic(bytes, label) {
        if (bytes.length === 32) {
          return "ed25519";
        }
        if (bytes.length === 65 && bytes[0] === 4) {
          return "ecdsa-p256-sha256";
        }
        if (bytes.length === 97 && bytes[0] === 4) {
          return "ecdsa-p384-sha384";
        }
        throw new Error(
          `${label} expects a 32-byte Ed25519 key, 65-byte P-256 public key, or 97-byte P-384 public key`
        );
      }
      function nodePrivateKeyFromRaw(key, algorithm, label) {
        const bytes = assertBinaryString(key, label, "BinaryString key");
        const meta = signingMeta(algorithm);
        if (bytes.length !== meta.privateLength) {
          throw new Error(`${label} expects a ${meta.privateLength}-byte raw private key`);
        }
        const crypto = nodeCrypto();
        if (!crypto || typeof crypto.createPrivateKey !== "function") {
          nodeUnsupported(label);
        }
        if (meta.type === "ed25519") {
          return crypto.createPrivateKey({
            key: Buffer.from(pkcs8DerFromRawSeed(bytes)),
            format: "der",
            type: "pkcs8"
          });
        }
        return crypto.createPrivateKey({
          key: Buffer.from(ecdsaPkcs8DerFromRawScalar(bytes, algorithm)),
          format: "der",
          type: "pkcs8"
        });
      }
      function nodePublicKeyFromRaw(key, algorithm, label) {
        const bytes = assertBinaryString(key, label, "BinaryString key");
        const crypto = nodeCrypto();
        if (!crypto || typeof crypto.createPublicKey !== "function") {
          nodeUnsupported(label);
        }
        return crypto.createPublicKey({
          key: jwkFromRawPublic(bytes, algorithm, label),
          format: "jwk"
        });
      }
      function x25519PrivateBytes(key, label) {
        const bytes = assertBinaryString(key, label, "BinaryString key");
        if (bytes.length !== 32) {
          throw new Error(`${label} expects a 32-byte raw private key`);
        }
        return bytes;
      }
      function x25519PublicBytes(key, label) {
        const bytes = assertBinaryString(key, label, "BinaryString key");
        if (bytes.length !== 32) {
          throw new Error(`${label} expects a 32-byte raw public key`);
        }
        return bytes;
      }
      function nodeX25519PrivateKeyFromRaw(key, label) {
        const bytes = x25519PrivateBytes(key, label);
        const crypto = nodeCrypto();
        if (!crypto || typeof crypto.createPrivateKey !== "function") {
          keyAgreementUnsupported(label);
        }
        return crypto.createPrivateKey({
          key: Buffer.from(x25519Pkcs8DerFromRawPrivate(bytes)),
          format: "der",
          type: "pkcs8"
        });
      }
      function nodeX25519PublicKeyFromRaw(key, label) {
        const bytes = x25519PublicBytes(key, label);
        const crypto = nodeCrypto();
        if (!crypto || typeof crypto.createPublicKey !== "function") {
          keyAgreementUnsupported(label);
        }
        return crypto.createPublicKey({
          key: Buffer.from(x25519SpkiDerFromRawPublic(bytes)),
          format: "der",
          type: "spki"
        });
      }
      function syncBrowserSigningError(label, asyncName) {
        throw new Error(
          `${label} is not available synchronously on host browser; use ${asyncName}`
        );
      }
      function syncBrowserKeyAgreementError(label, asyncName) {
        throw new Error(
          `${label} is not available synchronously on host browser; use ${asyncName}`
        );
      }
      function browserSigningUnsupported(label) {
        throw new Error(`${label} signing is unavailable on this host`);
      }
      function subtleSigningCrypto() {
        return globalThis.crypto && globalThis.crypto.subtle && typeof globalThis.crypto.subtle.generateKey === "function" && typeof globalThis.crypto.subtle.importKey === "function" && typeof globalThis.crypto.subtle.exportKey === "function" && typeof globalThis.crypto.subtle.sign === "function" && typeof globalThis.crypto.subtle.verify === "function" ? globalThis.crypto.subtle : null;
      }
      function subtleKeyAgreementCrypto() {
        return globalThis.crypto && globalThis.crypto.subtle && typeof globalThis.crypto.subtle.generateKey === "function" && typeof globalThis.crypto.subtle.importKey === "function" && typeof globalThis.crypto.subtle.exportKey === "function" && typeof globalThis.crypto.subtle.deriveBits === "function" ? globalThis.crypto.subtle : null;
      }
      var X509_OIDS = {
        "2.5.4.3": "CN",
        "2.5.4.6": "C",
        "2.5.4.7": "L",
        "2.5.4.8": "ST",
        "2.5.4.10": "O",
        "2.5.4.11": "OU",
        "1.2.840.10045.2.1": "ecPublicKey",
        "1.2.840.10045.3.1.7": "prime256v1",
        "1.3.132.0.34": "secp384r1",
        "1.3.101.112": "ed25519"
      };
      function derError(label) {
        throw new Error(`${label} expects DER X.509 certificate data`);
      }
      function x509DerReader(bytes, label) {
        return {
          bytes,
          offset: 0,
          readElement(expectedTag = null) {
            if (this.offset + 2 > this.bytes.length) {
              derError(label);
            }
            const start = this.offset;
            const tag = this.bytes[this.offset++];
            if (expectedTag != null && tag !== expectedTag) {
              derError(label);
            }
            let length = this.bytes[this.offset++];
            if (length & 128) {
              const count = length & 127;
              if (count === 0 || count > 4 || this.offset + count > this.bytes.length) {
                derError(label);
              }
              length = 0;
              for (let i = 0; i < count; ++i) {
                length = length << 8 | this.bytes[this.offset++];
              }
            }
            if (this.offset + length > this.bytes.length) {
              derError(label);
            }
            const headerLength = this.offset - start;
            const body = this.bytes.slice(this.offset, this.offset + length);
            const raw = this.bytes.slice(start, this.offset + length);
            this.offset += length;
            return { tag, body, raw, headerLength };
          },
          readBody(expectedTag = null) {
            return this.readElement(expectedTag).body;
          },
          empty() {
            return this.offset >= this.bytes.length;
          }
        };
      }
      function oidFromDer(bytes) {
        if (bytes.length === 0) {
          return "";
        }
        const parts = [Math.floor(bytes[0] / 40), bytes[0] % 40];
        let value = 0;
        for (let i = 1; i < bytes.length; ++i) {
          value = value << 7 | bytes[i] & 127;
          if ((bytes[i] & 128) === 0) {
            parts.push(value);
            value = 0;
          }
        }
        return parts.join(".");
      }
      function x509TextValue(tag, body) {
        if (tag === 12 || tag === 19 || tag === 22 || tag === 20) {
          return new TextDecoder().decode(body);
        }
        if (tag === 30) {
          let out = "";
          for (let i = 0; i + 1 < body.length; i += 2) {
            out += String.fromCharCode(body[i] << 8 | body[i + 1]);
          }
          return out;
        }
        return Array.from(body, (byte) => byte.toString(16).padStart(2, "0")).join("").toUpperCase();
      }
      function x509NameString(bytes, label) {
        const seq = x509DerReader(bytes, label);
        const parts = [];
        while (!seq.empty()) {
          const set = x509DerReader(seq.readBody(49), label);
          while (!set.empty()) {
            const attr = x509DerReader(set.readBody(48), label);
            const oid = oidFromDer(attr.readBody(6));
            const value = attr.readElement();
            const name2 = X509_OIDS[oid] || oid;
            parts.push(`${name2}=${x509TextValue(value.tag, value.body)}`);
          }
        }
        return parts.join(", ");
      }
      function x509SerialHex(bytes) {
        let value = bytes;
        while (value.length > 1 && value[0] === 0) {
          value = value.slice(1);
        }
        return Array.from(value, (byte) => byte.toString(16).padStart(2, "0")).join("").toUpperCase();
      }
      function x509TimeEpoch(element, label) {
        const text = new TextDecoder().decode(element.body);
        let year;
        let month;
        let day;
        let hour;
        let minute;
        let second;
        if (element.tag === 23) {
          const match = text.match(/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/u);
          if (!match) {
            derError(label);
          }
          year = Number(match[1]);
          year += year >= 50 ? 1900 : 2e3;
          month = Number(match[2]);
          day = Number(match[3]);
          hour = Number(match[4]);
          minute = Number(match[5]);
          second = Number(match[6]);
        } else if (element.tag === 24) {
          const match = text.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/u);
          if (!match) {
            derError(label);
          }
          year = Number(match[1]);
          month = Number(match[2]);
          day = Number(match[3]);
          hour = Number(match[4]);
          minute = Number(match[5]);
          second = Number(match[6]);
        } else {
          derError(label);
        }
        return Math.floor(Date.UTC(year, month - 1, day, hour, minute, second) / 1e3);
      }
      function x509BitStringPayload(bytes, label) {
        if (bytes.length === 0 || bytes[0] !== 0) {
          derError(label);
        }
        return bytes.slice(1);
      }
      function x509Spki(bytes, label) {
        const seq = x509DerReader(bytes, label);
        const alg = x509DerReader(seq.readBody(48), label);
        const algOid = oidFromDer(alg.readBody(6));
        let curveOid = null;
        if (!alg.empty()) {
          const param = alg.readElement();
          if (param.tag === 6) {
            curveOid = oidFromDer(param.body);
          }
        }
        const publicBytes = x509BitStringPayload(seq.readBody(3), label);
        return { algOid, curveOid, publicBytes };
      }
      function parseX509Der(der, label = "Certificate.parse") {
        const bytes = Uint8Array.from(der);
        const cert = x509DerReader(bytes, label);
        const certSeq = x509DerReader(cert.readBody(48), label);
        const tbs = x509DerReader(certSeq.readBody(48), label);
        if (!cert.empty()) {
          derError(label);
        }
        if (!tbs.empty()) {
          const next = tbs.readElement();
          if (next.tag !== 160) {
            tbs.offset = 0;
          }
        }
        const serial = x509SerialHex(tbs.readBody(2));
        tbs.readElement(48);
        const issuer = x509NameString(tbs.readBody(48), label);
        const validity = x509DerReader(tbs.readBody(48), label);
        const notBefore = x509TimeEpoch(validity.readElement(), label);
        const notAfter = x509TimeEpoch(validity.readElement(), label);
        const subject = x509NameString(tbs.readBody(48), label);
        const spki = x509Spki(tbs.readBody(48), label);
        return new Certificate(new SecureCertificate(
          bytes,
          subject,
          issuer,
          serial,
          notBefore,
          notAfter,
          spki
        ));
      }
      var SecureCertificate = class {
        constructor(der, subject, issuer, serial, notBefore, notAfter, spki) {
          this.der = der;
          this.subject = subject;
          this.issuer = issuer;
          this.serial = serial;
          this.notBefore = notBefore;
          this.notAfter = notAfter;
          this.spki = spki;
        }
      };
      var SecureTlsIdentity = class {
        constructor(certPem, keyPem, password = "", source = "pem", chainPem = certPem) {
          this.certPem = certPem;
          this.keyPem = keyPem;
          this.password = password;
          this.source = source;
          this.chainPem = chainPem;
        }
      };
      var SecureKeyAgreement = class {
        constructor(algorithm, key, publicKey = null, rawPrivate = null, rawPublic = null) {
          this.algorithm = algorithm;
          this.key = key;
          this.publicKey = publicKey;
          this.rawPrivate = rawPrivate;
          this.rawPublic = rawPublic;
        }
      };
      var SecureSigningKey = class {
        constructor(algorithm, key, publicKey = null, rawPrivate = null, rawPublic = null) {
          this.algorithm = algorithm;
          this.key = key;
          this.publicKey = publicKey;
          this.rawPrivate = rawPrivate;
          this.rawPublic = rawPublic;
        }
      };
      var SecurePublicKey = class {
        constructor(algorithm, key, rawPublic = null) {
          this.algorithm = algorithm;
          this.key = key;
          this.rawPublic = rawPublic;
        }
      };
      function signingGenerate(algorithm = "ed25519") {
        algorithm = signingAlgorithm(algorithm, "SigningKey.generate");
        if (hostName() === "browser") {
          syncBrowserSigningError(
            "SigningKey.generate",
            "SigningKey.generate_async"
          );
        }
        const crypto = nodeCrypto();
        if (!crypto || typeof crypto.generateKeyPairSync !== "function") {
          nodeUnsupported("SigningKey.generate");
        }
        const meta = signingMeta(algorithm);
        const pair = meta.type === "ed25519" ? crypto.generateKeyPairSync("ed25519") : crypto.generateKeyPairSync("ec", { namedCurve: meta.nodeCurve });
        return new SigningKey(new SecureSigningKey(algorithm, pair.privateKey));
      }
      async function browserSigningKeyFromPair(algorithm, pair) {
        const privateJwk = await globalThis.crypto.subtle.exportKey(
          "jwk",
          pair.privateKey
        );
        const publicJwk = await globalThis.crypto.subtle.exportKey(
          "jwk",
          pair.publicKey
        );
        return new SigningKey(new SecureSigningKey(
          algorithm,
          pair.privateKey,
          pair.publicKey,
          rawPrivateFromJwk(privateJwk, "SigningKey.generate_async"),
          rawPublicFromJwk(publicJwk, "SigningKey.generate_async")
        ));
      }
      async function signingGenerateAsyncValue(algorithm = "ed25519") {
        algorithm = signingAlgorithm(algorithm, "SigningKey.generate");
        if (hostName() !== "browser") {
          return signingGenerate(algorithm);
        }
        browserSigningAlgorithm(algorithm, "SigningKey.generate_async");
        const subtle = subtleSigningCrypto();
        if (!subtle) {
          browserSigningUnsupported("SigningKey.generate_async");
        }
        const meta = signingMeta(algorithm);
        try {
          const pair = await subtle.generateKey(
            meta.type === "ed25519" ? { name: "Ed25519" } : { name: "ECDSA", namedCurve: meta.webCurve },
            true,
            ["sign", "verify"]
          );
          return await browserSigningKeyFromPair(algorithm, pair);
        } catch (_err) {
          browserSigningUnsupported("SigningKey.generate_async");
        }
      }
      function signingImportPrivate(key, options = null) {
        const label = "SigningKey.import_private";
        if (hostName() === "browser") {
          syncBrowserSigningError(label, "SigningKey.import_private_async");
        }
        const opts = optionalDict(options, label, "Dict options");
        const format = keyFormat(key, options, label);
        const crypto = nodeCrypto();
        if (!crypto || typeof crypto.createPrivateKey !== "function") {
          nodeUnsupported(label);
        }
        let algorithm = signingAlgorithmOption(opts, label);
        let keyObject;
        if (format === "raw") {
          algorithm ??= "ed25519";
          keyObject = nodePrivateKeyFromRaw(key, algorithm, label);
        } else if (format === "pem") {
          const pem = assertString(key, label, "String key");
          const password = opts.password == null ? null : String(opts.password);
          keyObject = crypto.createPrivateKey(
            password == null ? pem : { key: pem, passphrase: password }
          );
          const actual = algorithmFromNodeKey(keyObject, label);
          if (algorithm && actual !== algorithm) {
            throw new Error(`${label} PEM key algorithm does not match ${algorithm}`);
          }
          algorithm = actual;
        } else {
          throw new Error(`${label} only supports raw and pem formats`);
        }
        return new SigningKey(new SecureSigningKey(algorithm, keyObject));
      }
      async function signingImportPrivateAsyncValue(key, options = null) {
        const label = "SigningKey.import_private";
        if (hostName() !== "browser") {
          return signingImportPrivate(key, options);
        }
        const subtle = subtleSigningCrypto();
        if (!subtle) {
          browserSigningUnsupported(`${label}_async`);
        }
        const opts = optionalDict(options, label, "Dict options");
        const format = keyFormat(key, options, label);
        let algorithm = signingAlgorithmOption(opts, label);
        let der;
        if (format === "raw") {
          const bytes = assertBinaryString(key, label, "BinaryString key");
          algorithm ??= "ed25519";
          browserSigningAlgorithm(algorithm, `${label}_async`);
          const meta = signingMeta(algorithm);
          if (bytes.length !== meta.privateLength) {
            throw new Error(`${label} expects a ${meta.privateLength}-byte raw private key`);
          }
          der = meta.type === "ed25519" ? pkcs8DerFromRawSeed(bytes) : ecdsaPkcs8DerFromRawScalar(bytes, algorithm);
        } else if (format === "pem") {
          der = pemToDer(key, label);
          if (algorithm) {
            browserSigningAlgorithm(algorithm, `${label}_async`);
          }
        } else {
          throw new Error(`${label} only supports raw and pem formats`);
        }
        try {
          let cryptoKey = null;
          let jwk = null;
          const candidates = algorithm ? [algorithm] : signingCapabilities();
          for (const candidate of candidates) {
            const meta = signingMeta(candidate);
            try {
              cryptoKey = await subtle.importKey(
                "pkcs8",
                der,
                meta.type === "ed25519" ? { name: "Ed25519" } : { name: "ECDSA", namedCurve: meta.webCurve },
                true,
                ["sign"]
              );
              jwk = await subtle.exportKey("jwk", cryptoKey);
              algorithm = algorithmFromJwk(jwk, label);
              break;
            } catch (_err) {
              cryptoKey = null;
            }
          }
          if (!cryptoKey) {
            browserSigningUnsupported(`${label}_async`);
          }
          const rawPublic = rawPublicFromJwk(jwk, label);
          const publicKey = await subtle.importKey(
            signingMeta(algorithm).type === "ed25519" ? "raw" : "jwk",
            signingMeta(algorithm).type === "ed25519" ? rawPublic : jwkFromRawPublic(rawPublic, algorithm, label),
            signingMeta(algorithm).type === "ed25519" ? { name: "Ed25519" } : { name: "ECDSA", namedCurve: signingMeta(algorithm).webCurve },
            true,
            ["verify"]
          );
          return new SigningKey(new SecureSigningKey(
            algorithm,
            cryptoKey,
            publicKey,
            rawPrivateFromJwk(jwk, label),
            rawPublic
          ));
        } catch (_err) {
          browserSigningUnsupported(`${label}_async`);
        }
      }
      function signingImportPublic(key, options = null) {
        const label = "SigningKey.import_public";
        if (hostName() === "browser") {
          syncBrowserSigningError(label, "SigningKey.import_public_async");
        }
        const opts = optionalDict(options, label, "Dict options");
        const format = keyFormat(key, options, label);
        const crypto = nodeCrypto();
        if (!crypto || typeof crypto.createPublicKey !== "function") {
          nodeUnsupported(label);
        }
        let algorithm = signingAlgorithmOption(opts, label);
        let keyObject;
        if (format === "raw") {
          const bytes = assertBinaryString(key, label, "BinaryString key");
          algorithm ??= algorithmFromRawPublic(bytes, label);
          keyObject = nodePublicKeyFromRaw(key, algorithm, label);
        } else if (format === "pem") {
          keyObject = crypto.createPublicKey(assertString(key, label, "String key"));
          const actual = algorithmFromNodeKey(keyObject, label);
          if (algorithm && actual !== algorithm) {
            throw new Error(`${label} PEM key algorithm does not match ${algorithm}`);
          }
          algorithm = actual;
        } else {
          throw new Error(`${label} only supports raw and pem formats`);
        }
        return new PublicKey(new SecurePublicKey(algorithm, keyObject));
      }
      async function signingImportPublicAsyncValue(key, options = null) {
        const label = "SigningKey.import_public";
        if (hostName() !== "browser") {
          return signingImportPublic(key, options);
        }
        const subtle = subtleSigningCrypto();
        if (!subtle) {
          browserSigningUnsupported(`${label}_async`);
        }
        const opts = optionalDict(options, label, "Dict options");
        const format = keyFormat(key, options, label);
        let algorithm = signingAlgorithmOption(opts, label);
        let importData;
        let importFormat;
        if (format === "raw") {
          importData = assertBinaryString(key, label, "BinaryString key");
          algorithm ??= algorithmFromRawPublic(importData, label);
          browserSigningAlgorithm(algorithm, `${label}_async`);
          importFormat = signingMeta(algorithm).type === "ed25519" ? "raw" : "jwk";
          if (importFormat === "jwk") {
            importData = jwkFromRawPublic(importData, algorithm, label);
          }
        } else if (format === "pem") {
          importData = pemToDer(key, label);
          importFormat = "spki";
          if (algorithm) {
            browserSigningAlgorithm(algorithm, `${label}_async`);
          }
        } else {
          throw new Error(`${label} only supports raw and pem formats`);
        }
        try {
          let cryptoKey = null;
          let jwk = null;
          const candidates = algorithm ? [algorithm] : signingCapabilities();
          for (const candidate of candidates) {
            const meta = signingMeta(candidate);
            try {
              cryptoKey = await subtle.importKey(
                importFormat,
                importData,
                meta.type === "ed25519" ? { name: "Ed25519" } : { name: "ECDSA", namedCurve: meta.webCurve },
                true,
                ["verify"]
              );
              jwk = await subtle.exportKey("jwk", cryptoKey);
              algorithm = algorithmFromJwk(jwk, label);
              break;
            } catch (_err) {
              cryptoKey = null;
            }
          }
          if (!cryptoKey) {
            browserSigningUnsupported(`${label}_async`);
          }
          return new PublicKey(new SecurePublicKey(
            algorithm,
            cryptoKey,
            rawPublicFromJwk(jwk, label)
          ));
        } catch (_err) {
          browserSigningUnsupported(`${label}_async`);
        }
      }
      function signingPublicKey(signingKey) {
        const secure = signingKey.__secureSigningKey;
        if (hostName() === "browser") {
          if (secure.publicKey && secure.rawPublic) {
            return new PublicKey(new SecurePublicKey(
              secure.algorithm,
              secure.publicKey,
              secure.rawPublic
            ));
          }
          throw new Error(
            "SigningKey.public_key is unavailable for this browser key"
          );
        }
        const crypto = nodeCrypto();
        return new PublicKey(new SecurePublicKey(
          secure.algorithm,
          crypto.createPublicKey(secure.key)
        ));
      }
      function signingSign(signingKey, message) {
        const label = "SigningKey.sign";
        if (hostName() === "browser") {
          syncBrowserSigningError(label, "SigningKey.sign_async");
        }
        const bytes = assertBinaryString(message, label, "BinaryString message");
        const crypto = nodeCrypto();
        if (!crypto || typeof crypto.sign !== "function") {
          nodeUnsupported(label);
        }
        const meta = signingMeta(signingKey.__secureSigningKey.algorithm);
        return new BinaryString(
          new Uint8Array(crypto.sign(meta.nodeHash ?? null, bytes, signingKey.__secureSigningKey.key))
        );
      }
      async function signingSignAsyncValue(signingKey, message) {
        const label = "SigningKey.sign";
        const bytes = assertBinaryString(message, label, "BinaryString message");
        if (hostName() !== "browser") {
          return signingSign(signingKey, message);
        }
        const subtle = subtleSigningCrypto();
        if (!subtle) {
          browserSigningUnsupported(`${label}_async`);
        }
        const meta = signingMeta(signingKey.__secureSigningKey.algorithm);
        try {
          const rawSignature = new Uint8Array(await subtle.sign(
            meta.type === "ed25519" ? { name: "Ed25519" } : { name: "ECDSA", hash: meta.webHash },
            signingKey.__secureSigningKey.key,
            bytes
          ));
          return new BinaryString(
            meta.type === "ed25519" ? rawSignature : ecdsaRawSignatureToDer(rawSignature)
          );
        } catch (_err) {
          browserSigningUnsupported(`${label}_async`);
        }
      }
      function signingExportPrivate(signingKey, optionsValue = null) {
        const label = "SigningKey.export_private";
        const options = optionalDict(optionsValue, label, "Dict options");
        const format = options.format == null ? "raw" : String(options.format);
        const secure = signingKey.__secureSigningKey;
        if (format === "raw") {
          if (secure.rawPrivate) {
            return new BinaryString(secure.rawPrivate);
          }
          return new BinaryString(
            rawPrivateFromJwk(secure.key.export({ format: "jwk" }), label)
          );
        }
        if (format === "pem") {
          if (hostName() !== "browser") {
            return String(secure.key.export({
              format: "pem",
              type: "pkcs8"
            }));
          }
          const meta = signingMeta(secure.algorithm);
          const der = meta.type === "ed25519" ? pkcs8DerFromRawSeed(secure.rawPrivate) : ecdsaPkcs8DerFromRawScalar(secure.rawPrivate, secure.algorithm);
          return derToPem("PRIVATE KEY", der);
        }
        throw new Error(`${label} only supports raw and pem formats`);
      }
      function certificateParse(input) {
        const label = "Certificate.parse";
        if (input && input.bytes instanceof Uint8Array) {
          return parseX509Der(input.bytes, label);
        }
        if (hostName() === "browser") {
          throw new Error(`${label} only supports DER BinaryString on host browser`);
        }
        return parseX509Der(certificatePemBlocks(input, label)[0], label);
      }
      function certificateParseChain(input) {
        const label = "Certificate.parse_chain";
        if (input && input.bytes instanceof Uint8Array) {
          return [parseX509Der(input.bytes, label)];
        }
        if (hostName() === "browser") {
          throw new Error(`${label} only supports DER BinaryString on host browser`);
        }
        return certificatePemBlocks(input, label).map((der) => parseX509Der(der, label));
      }
      function certificateState(certificate, label) {
        if (!(certificate instanceof Certificate)) {
          throw new Error(`TypeException: ${label} expects Certificate`);
        }
        return certificate.__secureCertificate;
      }
      function certificateFingerprint(certificate, algorithm) {
        const label = "Certificate.fingerprint";
        const state = certificateState(certificate, label);
        const value = algorithm == null ? "sha256" : String(algorithm).toLowerCase();
        if (value !== "sha256") {
          throw new Error(`${label} only supports sha256`);
        }
        return new BinaryString(
          digestBytes("sha256", new BinaryString(state.der), label)
        );
      }
      function certificatePublicKey(certificate) {
        const label = "Certificate.public_key";
        if (hostName() === "browser") {
          throw new Error(`${label} is not supported on host browser`);
        }
        const state = certificateState(certificate, label);
        const { algOid, curveOid, publicBytes } = state.spki;
        if (algOid === "1.3.101.112") {
          const raw = Uint8Array.from(publicBytes);
          return new PublicKey(new SecurePublicKey(
            "ed25519",
            nodePublicKeyFromRaw(new BinaryString(raw), "ed25519", label),
            raw
          ));
        }
        if (algOid === "1.2.840.10045.2.1" && curveOid === "1.2.840.10045.3.1.7") {
          const raw = Uint8Array.from(publicBytes);
          return new PublicKey(new SecurePublicKey(
            "ecdsa-p256-sha256",
            nodePublicKeyFromRaw(
              new BinaryString(raw),
              "ecdsa-p256-sha256",
              label
            ),
            raw
          ));
        }
        if (algOid === "1.2.840.10045.2.1" && curveOid === "1.3.132.0.34") {
          const raw = Uint8Array.from(publicBytes);
          return new PublicKey(new SecurePublicKey(
            "ecdsa-p384-sha384",
            nodePublicKeyFromRaw(
              new BinaryString(raw),
              "ecdsa-p384-sha384",
              label
            ),
            raw
          ));
        }
        throw new Error(`${label} certificate public-key algorithm is unsupported`);
      }
      function certificateVerifyChain(chain, options = null) {
        const label = "Certificate.verify_chain";
        if (hostName() === "browser") {
          throw new Error(`${label} is not supported on host browser`);
        }
        if (!Array.isArray(chain) || chain.length === 0) {
          throw new Error(`TypeException: ${label} expects non-empty Array chain`);
        }
        const states = chain.map((certificate) => certificateState(certificate, label));
        const opts = certificateVerifyOptions(options, label);
        const crypto = nodeCrypto();
        if (!crypto || typeof crypto.X509Certificate !== "function") {
          throw new Error(`${label} requires X509Certificate support on host node`);
        }
        const rootCerts = certificateRootNodeCerts(opts.roots, crypto, label);
        if (opts.use_system_roots) {
          const tls = nodeTls();
          if (tls && Array.isArray(tls.rootCertificates)) {
            for (const pem of tls.rootCertificates) {
              rootCerts.push(new crypto.X509Certificate(pem));
            }
          }
        }
        const nodeChain = states.map(
          (state) => new crypto.X509Certificate(Buffer.from(state.der))
        );
        const verifiedAt = opts.time;
        let valid = true;
        let error = null;
        error = certificateVerifyNodeChain(nodeChain, rootCerts, verifiedAt);
        valid = error == null;
        let reason = valid ? "ok" : certificateVerifyReason(error);
        if (valid && opts.hostname != null) {
          if (!certificateHostnameMatches(states[0], opts.hostname)) {
            valid = false;
            reason = "hostname-mismatch";
            error = "hostname mismatch";
          }
        }
        return {
          valid,
          reason,
          error: valid ? null : error,
          hostname: opts.hostname,
          verified_at: verifiedAt,
          chain_length: chain.length
        };
      }
      function certificateVerifyOptions(options, label) {
        if (options == null) {
          options = {};
        }
        if (typeof options !== "object" || Array.isArray(options)) {
          throw new Error(`TypeException: ${label} expects Dict options`);
        }
        const useSystemRoots = options.use_system_roots == null ? false : options.use_system_roots;
        if (typeof useSystemRoots !== "boolean") {
          throw new Error(
            `TypeException: ${label} option 'use_system_roots' expects Boolean`
          );
        }
        let hostname = options.hostname == null ? null : options.hostname;
        if (hostname != null && typeof hostname !== "string") {
          throw new Error(`TypeException: ${label} option 'hostname' expects String`);
        }
        let time = options.time;
        if (time == null) {
          time = Math.floor(Date.now() / 1e3);
        } else if (time instanceof Time) {
          time = time.epoch();
        } else if (typeof time === "number") {
          time = Math.floor(time);
        } else {
          throw new Error(
            `TypeException: ${label} option 'time' expects Time, Number, or null`
          );
        }
        return {
          roots: options.roots,
          use_system_roots: useSystemRoots,
          hostname,
          time
        };
      }
      function certificateRootNodeCerts(value, crypto, label) {
        if (value == null) {
          return [];
        }
        if (value instanceof Certificate) {
          const state = certificateState(value, label);
          return [new crypto.X509Certificate(Buffer.from(state.der))];
        }
        if (typeof value === "string") {
          return certificatePemBlocks(value, label).map((der) => new crypto.X509Certificate(Buffer.from(der)));
        }
        if (Array.isArray(value)) {
          return value.flatMap(
            (item) => certificateRootNodeCerts(item, crypto, label)
          );
        }
        throw new Error(
          `TypeException: ${label} expects roots to be Certificate, String PEM, Array, or null`
        );
      }
      function certificateVerifyNodeChain(chain, roots, verifiedAt) {
        const verifiedDate = new Date(verifiedAt * 1e3);
        for (const cert of chain) {
          const notBefore = new Date(cert.validFrom);
          const notAfter = new Date(cert.validTo);
          if (verifiedDate < notBefore) {
            return "certificate is not yet valid";
          }
          if (verifiedDate > notAfter) {
            return "certificate has expired";
          }
        }
        for (let i = 0; i < chain.length; i++) {
          const child = chain[i];
          const issuer = chain[i + 1] || roots.find(
            (root) => child.checkIssued(root) && child.verify(root.publicKey)
          );
          if (!issuer) {
            return "certificate is not trusted";
          }
          if (!child.checkIssued(issuer) || !child.verify(issuer.publicKey)) {
            return "certificate signature is invalid";
          }
          if (i > 0 && issuer !== child && !child.ca) {
            return "certificate is not a CA";
          }
        }
        return null;
      }
      function certificateVerifyReason(error) {
        const text = String(error || "").toLowerCase();
        if (text === "" || text === "ok") {
          return "ok";
        }
        if (text.includes("hostname")) {
          return "hostname-mismatch";
        }
        if (text.includes("not valid yet") || text.includes("not yet valid")) {
          return "not-yet-valid";
        }
        if (text.includes("expired") || text.includes("not valid")) {
          return "expired";
        }
        if (text.includes("unknown_ca") || text.includes("not trusted") || text.includes("unknown ca")) {
          return "untrusted-root";
        }
        return "invalid-chain";
      }
      function certificateHostnameMatches(state, hostname) {
        const crypto = nodeCrypto();
        if (crypto && typeof crypto.X509Certificate === "function") {
          const cert = new crypto.X509Certificate(Buffer.from(state.der));
          if (isIpAddress(hostname) && typeof cert.checkIP === "function") {
            return !!cert.checkIP(hostname);
          }
          if (typeof cert.checkHost === "function") {
            return !!cert.checkHost(hostname);
          }
        }
        return certificateHostnameMatchesFallback(state, hostname);
      }
      function isIpAddress(text) {
        return /^(\d{1,3}\.){3}\d{1,3}$/u.test(text) || text.includes(":");
      }
      function certificateHostnameMatchesFallback(state, hostname) {
        const extensions = state.extensions || [];
        const subjectAltName = extensions.find(
          (ext) => ext.oid === "2.5.29.17"
        );
        if (subjectAltName) {
          for (const name2 of subjectAltName.names || []) {
            if (name2.type === "dns" && dnsNameMatches(name2.value, hostname)) {
              return true;
            }
            if (name2.type === "ip" && name2.value === hostname) {
              return true;
            }
          }
          return false;
        }
        const match = state.subject.match(/(?:^|,\s*)CN=([^,]+)/u);
        return !!(match && dnsNameMatches(match[1], hostname));
      }
      function dnsNameMatches(pattern, hostname) {
        pattern = String(pattern).toLowerCase();
        hostname = String(hostname).toLowerCase();
        if (pattern === hostname) {
          return true;
        }
        if (!pattern.startsWith("*.")) {
          return false;
        }
        const suffix = pattern.slice(1);
        return hostname.endsWith(suffix) && hostname.slice(0, -suffix.length).indexOf(".") === -1;
      }
      function binaryStringFromBytes(bytes) {
        let out = "";
        for (let i = 0; i < bytes.length; i += 8192) {
          out += String.fromCharCode(...bytes.slice(i, i + 8192));
        }
        return out;
      }
      function bytesFromBinaryString(text) {
        const bytes = new Uint8Array(text.length);
        for (let i = 0; i < text.length; i++) {
          bytes[i] = text.charCodeAt(i) & 255;
        }
        return bytes;
      }
      function forgeAsn1Bytes(forge, asn1) {
        return bytesFromBinaryString(forge.asn1.toDer(asn1).getBytes());
      }
      function tlsIdentityFromPem(certificatePem, privateKeyPem, password = null) {
        const label = "TlsIdentity.from_pem";
        const certPem = assertString(
          certificatePem,
          label,
          "String certificate_pem"
        );
        const keyPem = assertString(
          privateKeyPem,
          label,
          "String private_key_pem"
        );
        const pass = password == null ? "" : assertString(
          password,
          label,
          "String password"
        );
        const blocks = certificatePemBlocks(certPem, label);
        parseX509Der(blocks[0], label);
        if (!/-----BEGIN [A-Z ]*PRIVATE KEY-----/u.test(keyPem)) {
          throw new Error(`${label} expects PEM private key text`);
        }
        return new TlsIdentity(new SecureTlsIdentity(
          certificateDerToPem(blocks[0]),
          keyPem,
          pass,
          "pem",
          blocks.map(certificateDerToPem).join("")
        ));
      }
      function tlsIdentityFromPkcs12(bytesValue, password = null) {
        const label = "TlsIdentity.from_pkcs12";
        if (hostName() === "browser") {
          throw new Error(`${label} is not supported on host browser`);
        }
        const bytes = assertBinaryString(bytesValue, label, "BinaryString bytes");
        const pass = password == null ? "" : assertString(
          password,
          label,
          "String password"
        );
        const forge = nodeForge();
        if (!forge) {
          nodeUnsupported(label);
        }
        try {
          const asn1 = forge.asn1.fromDer(
            forge.util.createBuffer(binaryStringFromBytes(bytes))
          );
          const p12 = forge.pkcs12.pkcs12FromAsn1(asn1, false, pass);
          const keyBags = [
            ...p12.getBags({
              bagType: forge.pki.oids.pkcs8ShroudedKeyBag
            })[forge.pki.oids.pkcs8ShroudedKeyBag] || [],
            ...p12.getBags({
              bagType: forge.pki.oids.keyBag
            })[forge.pki.oids.keyBag] || []
          ];
          const certBags = p12.getBags({
            bagType: forge.pki.oids.certBag
          })[forge.pki.oids.certBag] || [];
          if (keyBags.length === 0 || certBags.length === 0) {
            throw new Error("missing identity material");
          }
          const keyBag = keyBags[0];
          const certBag = certBags[0];
          const keyPem = keyBag.key ? forge.pki.privateKeyToPem(keyBag.key) : derToPem("PRIVATE KEY", forgeAsn1Bytes(forge, keyBag.asn1));
          const certPem = certBag.cert ? forge.pki.certificateToPem(certBag.cert) : derToPem("CERTIFICATE", forgeAsn1Bytes(forge, certBag.asn1));
          const chainPem = certBags.map(
            (bag) => bag.cert ? forge.pki.certificateToPem(bag.cert) : derToPem("CERTIFICATE", forgeAsn1Bytes(forge, bag.asn1))
          ).join("");
          return new TlsIdentity(new SecureTlsIdentity(
            certPem,
            keyPem,
            "",
            "pkcs12",
            chainPem
          ));
        } catch (err) {
          if (/password|decrypt|mac|integrity/iu.test(String(err.message))) {
            throw new Error(`${label} failed to decrypt PKCS#12 data`);
          }
          throw new Error(
            `${label} expects PKCS#12 data with certificate and private key`
          );
        }
      }
      function tlsIdentityState(identity, label) {
        if (!(identity instanceof TlsIdentity)) {
          throw new Error(`TypeException: ${label} expects TlsIdentity`);
        }
        return identity.__secureTlsIdentity;
      }
      function tlsIdentityCertificate(identity) {
        const label = "TlsIdentity.certificate";
        const state = tlsIdentityState(identity, label);
        return parseX509Der(certificatePemBlocks(state.certPem, label)[0], label);
      }
      function tlsIdentityPrivateKey(identity) {
        const label = "TlsIdentity.private_key";
        if (hostName() === "browser") {
          throw new Error(`${label} is not supported on host browser`);
        }
        const state = tlsIdentityState(identity, label);
        try {
          return signingImportPrivate(
            state.keyPem,
            { format: "pem", password: state.password }
          );
        } catch (_err) {
          throw new Error(
            `${label} only supports Ed25519, ECDSA P-256, and ECDSA P-384 private keys`
          );
        }
      }
      function publicKeyVerify(publicKey, message, signature) {
        const label = "PublicKey.verify";
        if (hostName() === "browser") {
          syncBrowserSigningError(label, "PublicKey.verify_async");
        }
        const messageBytes = assertBinaryString(
          message,
          label,
          "BinaryString message"
        );
        const signatureBytes = assertBinaryString(
          signature,
          label,
          "BinaryString signature"
        );
        const meta = signingMeta(publicKey.__securePublicKey.algorithm);
        if (!meta) {
          throw new Error(`${label} expects a signing public key`);
        }
        if (meta.type === "ed25519" && signatureBytes.length !== 64) {
          return false;
        }
        const crypto = nodeCrypto();
        if (!crypto || typeof crypto.verify !== "function") {
          nodeUnsupported(label);
        }
        return crypto.verify(
          meta.nodeHash ?? null,
          messageBytes,
          publicKey.__securePublicKey.key,
          signatureBytes
        );
      }
      async function publicKeyVerifyAsyncValue(publicKey, message, signature) {
        const label = "PublicKey.verify";
        const messageBytes = assertBinaryString(
          message,
          label,
          "BinaryString message"
        );
        const signatureBytes = assertBinaryString(
          signature,
          label,
          "BinaryString signature"
        );
        if (hostName() !== "browser") {
          return publicKeyVerify(publicKey, message, signature);
        }
        const subtle = subtleSigningCrypto();
        if (!subtle) {
          browserSigningUnsupported(`${label}_async`);
        }
        const meta = signingMeta(publicKey.__securePublicKey.algorithm);
        if (!meta) {
          throw new Error(`${label} expects a signing public key`);
        }
        let verifySignature = signatureBytes;
        if (meta.type === "ed25519") {
          if (signatureBytes.length !== 64) {
            return false;
          }
        } else {
          try {
            verifySignature = derToEcdsaRawSignature(
              signatureBytes,
              publicKey.__securePublicKey.algorithm
            );
          } catch (_err) {
            return false;
          }
        }
        try {
          return await subtle.verify(
            meta.type === "ed25519" ? { name: "Ed25519" } : { name: "ECDSA", hash: meta.webHash },
            publicKey.__securePublicKey.key,
            verifySignature,
            messageBytes
          );
        } catch (_err) {
          return false;
        }
      }
      function publicKeyExport(publicKey, optionsValue = null) {
        const label = "PublicKey.export";
        const options = optionalDict(optionsValue, label, "Dict options");
        const format = options.format == null ? "raw" : String(options.format);
        const secure = publicKey.__securePublicKey;
        if (format === "raw") {
          if (secure.rawPublic) {
            return new BinaryString(secure.rawPublic);
          }
          return new BinaryString(
            rawPublicFromJwk(secure.key.export({ format: "jwk" }), label)
          );
        }
        if (format === "pem") {
          if (secure.algorithm === "x25519") {
            throw new Error(
              `${label} only supports raw format for x25519 public keys`
            );
          }
          if (hostName() !== "browser") {
            return String(secure.key.export({
              format: "pem",
              type: "spki"
            }));
          }
          const meta = signingMeta(secure.algorithm);
          const der = meta.type === "ed25519" ? null : ecdsaSpkiDerFromRawPublic(secure.rawPublic, secure.algorithm);
          if (der == null) {
            throw new Error(`${label} PEM export is unavailable for this browser key`);
          }
          return derToPem("PUBLIC KEY", der);
        }
        throw new Error(`${label} only supports raw and pem formats`);
      }
      function keyAgreementGenerate(algorithm = "x25519") {
        const label = "KeyAgreement.generate";
        algorithm = keyAgreementAlgorithm(algorithm, label);
        if (hostName() === "browser") {
          syncBrowserKeyAgreementError(label, "KeyAgreement.generate_async");
        }
        const crypto = nodeCrypto();
        if (!crypto || typeof crypto.generateKeyPairSync !== "function") {
          keyAgreementUnsupported(label);
        }
        const pair = crypto.generateKeyPairSync(algorithm);
        return new KeyAgreement(new SecureKeyAgreement(
          algorithm,
          pair.privateKey
        ));
      }
      async function browserKeyAgreementFromPair(algorithm, pair, label) {
        const privateJwk = await globalThis.crypto.subtle.exportKey(
          "jwk",
          pair.privateKey
        );
        const publicJwk = await globalThis.crypto.subtle.exportKey(
          "jwk",
          pair.publicKey
        );
        return new KeyAgreement(new SecureKeyAgreement(
          algorithm,
          pair.privateKey,
          pair.publicKey,
          rawPrivateFromJwk(privateJwk, label),
          rawPublicFromJwk(publicJwk, label)
        ));
      }
      async function keyAgreementGenerateAsyncValue(algorithm = "x25519") {
        const label = "KeyAgreement.generate";
        algorithm = keyAgreementAlgorithm(algorithm, label);
        if (hostName() !== "browser") {
          return keyAgreementGenerate(algorithm);
        }
        const subtle = subtleKeyAgreementCrypto();
        if (!subtle) {
          keyAgreementUnsupported(`${label}_async`);
        }
        try {
          const pair = await subtle.generateKey(
            { name: "X25519" },
            true,
            ["deriveBits"]
          );
          return await browserKeyAgreementFromPair(algorithm, pair, label);
        } catch (_err) {
          keyAgreementUnsupported(`${label}_async`);
        }
      }
      function keyAgreementImportPrivate(key, options = null) {
        const label = "KeyAgreement.import_private";
        if (hostName() === "browser") {
          syncBrowserKeyAgreementError(
            label,
            "KeyAgreement.import_private_async"
          );
        }
        const opts = optionalDict(options, label, "Dict options");
        keyAgreementAlgorithmOption(opts, label);
        const format = keyFormat(key, options, label);
        if (format !== "raw") {
          throw new Error(`${label} only supports raw format`);
        }
        return new KeyAgreement(new SecureKeyAgreement(
          "x25519",
          nodeX25519PrivateKeyFromRaw(key, label)
        ));
      }
      async function keyAgreementImportPrivateAsyncValue(key, options = null) {
        const label = "KeyAgreement.import_private";
        if (hostName() !== "browser") {
          return keyAgreementImportPrivate(key, options);
        }
        const subtle = subtleKeyAgreementCrypto();
        if (!subtle) {
          keyAgreementUnsupported(`${label}_async`);
        }
        const opts = optionalDict(options, label, "Dict options");
        keyAgreementAlgorithmOption(opts, label);
        const format = keyFormat(key, options, label);
        if (format !== "raw") {
          throw new Error(`${label} only supports raw format`);
        }
        const rawPrivate = x25519PrivateBytes(key, label);
        try {
          const privateKey = await subtle.importKey(
            "pkcs8",
            x25519Pkcs8DerFromRawPrivate(rawPrivate),
            { name: "X25519" },
            true,
            ["deriveBits"]
          );
          const privateJwk = await subtle.exportKey("jwk", privateKey);
          const rawPublic = rawPublicFromJwk(privateJwk, label);
          const publicKey = await subtle.importKey(
            "raw",
            rawPublic,
            { name: "X25519" },
            true,
            []
          );
          return new KeyAgreement(new SecureKeyAgreement(
            "x25519",
            privateKey,
            publicKey,
            rawPrivateFromJwk(privateJwk, label),
            rawPublic
          ));
        } catch (_err) {
          keyAgreementUnsupported(`${label}_async`);
        }
      }
      function keyAgreementImportPublic(key, options = null) {
        const label = "KeyAgreement.import_public";
        if (hostName() === "browser") {
          syncBrowserKeyAgreementError(label, "KeyAgreement.import_public_async");
        }
        const opts = optionalDict(options, label, "Dict options");
        keyAgreementAlgorithmOption(opts, label);
        const format = keyFormat(key, options, label);
        if (format !== "raw") {
          throw new Error(`${label} only supports raw format`);
        }
        return new PublicKey(new SecurePublicKey(
          "x25519",
          nodeX25519PublicKeyFromRaw(key, label)
        ));
      }
      async function keyAgreementImportPublicAsyncValue(key, options = null) {
        const label = "KeyAgreement.import_public";
        if (hostName() !== "browser") {
          return keyAgreementImportPublic(key, options);
        }
        const subtle = subtleKeyAgreementCrypto();
        if (!subtle) {
          keyAgreementUnsupported(`${label}_async`);
        }
        const opts = optionalDict(options, label, "Dict options");
        keyAgreementAlgorithmOption(opts, label);
        const format = keyFormat(key, options, label);
        if (format !== "raw") {
          throw new Error(`${label} only supports raw format`);
        }
        const rawPublic = x25519PublicBytes(key, label);
        try {
          const publicKey = await subtle.importKey(
            "raw",
            rawPublic,
            { name: "X25519" },
            true,
            []
          );
          return new PublicKey(new SecurePublicKey(
            "x25519",
            publicKey,
            rawPublic
          ));
        } catch (_err) {
          keyAgreementUnsupported(`${label}_async`);
        }
      }
      function keyAgreementPublicKey(keyAgreement) {
        const secure = keyAgreement.__secureKeyAgreement;
        if (hostName() === "browser") {
          if (secure.publicKey && secure.rawPublic) {
            return new PublicKey(new SecurePublicKey(
              secure.algorithm,
              secure.publicKey,
              secure.rawPublic
            ));
          }
          throw new Error(
            "KeyAgreement.public_key is unavailable for this browser key"
          );
        }
        const crypto = nodeCrypto();
        return new PublicKey(new SecurePublicKey(
          secure.algorithm,
          crypto.createPublicKey(secure.key)
        ));
      }
      function keyAgreementExportPrivate(keyAgreement, optionsValue = null) {
        const label = "KeyAgreement.export_private";
        const options = optionalDict(optionsValue, label, "Dict options");
        const format = options.format == null ? "raw" : String(options.format);
        if (format !== "raw") {
          throw new Error(`${label} only supports raw format`);
        }
        const secure = keyAgreement.__secureKeyAgreement;
        if (secure.rawPrivate) {
          return new BinaryString(secure.rawPrivate);
        }
        return new BinaryString(
          rawPrivateFromJwk(secure.key.export({ format: "jwk" }), label)
        );
      }
      function keyAgreementDerive(keyAgreement, publicKey) {
        const label = "KeyAgreement.derive";
        if (hostName() === "browser") {
          syncBrowserKeyAgreementError(label, "KeyAgreement.derive_async");
        }
        if (!(publicKey instanceof PublicKey) || publicKey.__securePublicKey.algorithm !== "x25519") {
          throw new Error(`${label} expects an x25519 public key`);
        }
        const crypto = nodeCrypto();
        if (!crypto || typeof crypto.diffieHellman !== "function") {
          keyAgreementUnsupported(label);
        }
        return new BinaryString(
          new Uint8Array(crypto.diffieHellman({
            privateKey: keyAgreement.__secureKeyAgreement.key,
            publicKey: publicKey.__securePublicKey.key
          }))
        );
      }
      async function keyAgreementDeriveAsyncValue(keyAgreement, publicKey) {
        const label = "KeyAgreement.derive";
        if (hostName() !== "browser") {
          return keyAgreementDerive(keyAgreement, publicKey);
        }
        if (!(publicKey instanceof PublicKey) || publicKey.__securePublicKey.algorithm !== "x25519") {
          throw new Error(`${label} expects an x25519 public key`);
        }
        const subtle = subtleKeyAgreementCrypto();
        if (!subtle) {
          keyAgreementUnsupported(`${label}_async`);
        }
        try {
          return new BinaryString(new Uint8Array(await subtle.deriveBits(
            { name: "X25519", public: publicKey.__securePublicKey.key },
            keyAgreement.__secureKeyAgreement.key,
            256
          )));
        } catch (_err) {
          keyAgreementUnsupported(`${label}_async`);
        }
      }
      var Secure = class {
        static capabilities() {
          return capabilities();
        }
        static has(area, name2) {
          return hasCapability(area, name2);
        }
        static require(area, name2) {
          return requireCapability(area, name2);
        }
      };
      var KeyDerivation = class {
        static hkdf_sha256(inputKeyMaterial, length, salt = null, info = null) {
          return hkdfSha256(inputKeyMaterial, length, salt, info);
        }
        static hkdf_sha256_async(inputKeyMaterial, length, salt = null, info = null) {
          const args = hkdfSha256Inputs(inputKeyMaterial, length, salt, info);
          if (subtleCrypto()) {
            return taskRuntime.Task.from(webCryptoHkdfSha256(args));
          }
          return taskRuntime.Task.resolved(
            new BinaryString(
              hkdfSha256Bytes(
                args.inputKeyMaterial,
                args.length,
                args.salt,
                args.info
              )
            )
          );
        }
      };
      var SecureRandom = class {
        static bytes(length) {
          if (arguments.length !== 1 || length == null) {
            throw new Error("SecureRandom.bytes expects a non-negative integer");
          }
          return new BinaryString(
            randomBytes(nonNegativeInteger(length, "SecureRandom.bytes"))
          );
        }
        static token(length = 32) {
          if (length == null) {
            length = 32;
          }
          return base64url(
            randomBytes(nonNegativeInteger(length, "SecureRandom.token"))
          );
        }
        static int(max) {
          return randomInt(positiveInteger(max, "SecureRandom.int"));
        }
      };
      var PasswordHash = class {
        static default_algorithm() {
          return DEFAULT_PASSWORD_HASH_ALGORITHM;
        }
        static hash(password, options = null) {
          return passwordHash(password, options);
        }
        static hash_async(password, options = null) {
          return taskRuntime.Task.from(passwordHashAsyncValue(password, options));
        }
        static verify(password, encodedHash) {
          return passwordHashVerify(password, encodedHash);
        }
        static verify_async(password, encodedHash) {
          return taskRuntime.Task.from(
            passwordHashVerifyAsyncValue(password, encodedHash)
          );
        }
        static needs_rehash(encodedHash, options = null) {
          return passwordHashNeedsRehash(encodedHash, options);
        }
        static derive_key(password, options = null) {
          return passwordHashDeriveKey(password, options);
        }
        static derive_key_async(password, options = null) {
          return taskRuntime.Task.from(
            passwordHashDeriveKeyAsyncValue(password, options)
          );
        }
      };
      var Cipher = class {
        static generate_key(algorithm = "aes-256-gcm") {
          return cipherGenerateKey(algorithm);
        }
        static encrypt(plaintext, key, options = null) {
          return cipherEncrypt(plaintext, key, options);
        }
        static decrypt(envelope, key, options = null) {
          return cipherDecrypt(envelope, key, options);
        }
        static encrypt_async(plaintext, key, options = null) {
          return cipherEncryptAsync(plaintext, key, options);
        }
        static decrypt_async(envelope, key, options = null) {
          return cipherDecryptAsync(envelope, key, options);
        }
      };
      var KeyAgreement = class {
        constructor(secureKeyAgreement) {
          if (!(secureKeyAgreement instanceof SecureKeyAgreement)) {
            throw new Error("KeyAgreement objects are created by std/secure");
          }
          this.__secureKeyAgreement = secureKeyAgreement;
        }
        static generate(algorithm = "x25519") {
          return keyAgreementGenerate(algorithm);
        }
        static generate_async(algorithm = "x25519") {
          return taskRuntime.Task.from(
            keyAgreementGenerateAsyncValue(algorithm)
          );
        }
        static import_private(key, options = null) {
          return keyAgreementImportPrivate(key, options);
        }
        static import_private_async(key, options = null) {
          return taskRuntime.Task.from(
            keyAgreementImportPrivateAsyncValue(key, options)
          );
        }
        static import_public(key, options = null) {
          return keyAgreementImportPublic(key, options);
        }
        static import_public_async(key, options = null) {
          return taskRuntime.Task.from(
            keyAgreementImportPublicAsyncValue(key, options)
          );
        }
        public_key() {
          return keyAgreementPublicKey(this);
        }
        derive(publicKey) {
          return keyAgreementDerive(this, publicKey);
        }
        derive_async(publicKey) {
          return taskRuntime.Task.from(
            keyAgreementDeriveAsyncValue(this, publicKey)
          );
        }
        export_private(options = null) {
          return keyAgreementExportPrivate(this, options);
        }
      };
      var SigningKey = class {
        constructor(secureSigningKey) {
          if (!(secureSigningKey instanceof SecureSigningKey)) {
            throw new Error("SigningKey objects are created by std/secure");
          }
          this.__secureSigningKey = secureSigningKey;
        }
        static generate(algorithm = "ed25519") {
          return signingGenerate(algorithm);
        }
        static generate_async(algorithm = "ed25519") {
          return taskRuntime.Task.from(signingGenerateAsyncValue(algorithm));
        }
        static import_private(key, options = null) {
          return signingImportPrivate(key, options);
        }
        static import_private_async(key, options = null) {
          return taskRuntime.Task.from(
            signingImportPrivateAsyncValue(key, options)
          );
        }
        static import_public(key, options = null) {
          return signingImportPublic(key, options);
        }
        static import_public_async(key, options = null) {
          return taskRuntime.Task.from(
            signingImportPublicAsyncValue(key, options)
          );
        }
        public_key() {
          return signingPublicKey(this);
        }
        sign(message) {
          return signingSign(this, message);
        }
        sign_async(message) {
          return taskRuntime.Task.from(signingSignAsyncValue(this, message));
        }
        export_private(options = null) {
          return signingExportPrivate(this, options);
        }
      };
      var Certificate = class {
        constructor(secureCertificate) {
          if (!(secureCertificate instanceof SecureCertificate)) {
            throw new Error("Certificate objects are created by std/secure");
          }
          this.__secureCertificate = secureCertificate;
        }
        static parse(input) {
          return certificateParse(input);
        }
        static parse_chain(input) {
          return certificateParseChain(input);
        }
        static verify_chain(chain, options = null) {
          return certificateVerifyChain(chain, options);
        }
        subject() {
          return certificateState(this, "Certificate.subject").subject;
        }
        issuer() {
          return certificateState(this, "Certificate.issuer").issuer;
        }
        serial_number() {
          return certificateState(this, "Certificate.serial_number").serial;
        }
        not_before() {
          return new Time(certificateState(this, "Certificate.not_before").notBefore);
        }
        not_after() {
          return new Time(certificateState(this, "Certificate.not_after").notAfter);
        }
        fingerprint(algorithm = "sha256") {
          return certificateFingerprint(this, algorithm);
        }
        to_der() {
          return new BinaryString(
            Uint8Array.from(certificateState(this, "Certificate.to_der").der)
          );
        }
        to_pem() {
          return certificateDerToPem(
            certificateState(this, "Certificate.to_pem").der
          );
        }
        public_key() {
          return certificatePublicKey(this);
        }
      };
      var PrivateKey = class {
      };
      var PublicKey = class {
        constructor(securePublicKey) {
          if (!(securePublicKey instanceof SecurePublicKey)) {
            throw new Error("PublicKey objects are created by std/secure");
          }
          this.__securePublicKey = securePublicKey;
        }
        verify(message, signature) {
          return publicKeyVerify(this, message, signature);
        }
        verify_async(message, signature) {
          return taskRuntime.Task.from(
            publicKeyVerifyAsyncValue(this, message, signature)
          );
        }
        export(options = null) {
          return publicKeyExport(this, options);
        }
      };
      var SealedBox = class {
      };
      var TlsIdentity = class {
        constructor(secureTlsIdentity) {
          if (!(secureTlsIdentity instanceof SecureTlsIdentity)) {
            throw new Error("TlsIdentity objects are created by std/secure");
          }
          this.__secureTlsIdentity = secureTlsIdentity;
        }
        static from_pem(certificatePem, privateKeyPem, password = null) {
          return tlsIdentityFromPem(certificatePem, privateKeyPem, password);
        }
        static from_pkcs12(bytes, password = null) {
          return tlsIdentityFromPkcs12(bytes, password);
        }
        certificate() {
          return tlsIdentityCertificate(this);
        }
        private_key() {
          return tlsIdentityPrivateKey(this);
        }
      };
      module.exports = {
        Secure,
        SecureRandom,
        PasswordHash,
        KeyDerivation,
        Cipher,
        KeyAgreement,
        SigningKey,
        Certificate,
        PrivateKey,
        PublicKey,
        SealedBox,
        TlsIdentity,
        __zuzu_set_runtime_policy: setRuntimePolicy
      };
    }
  });

  // modules/std/data/json.js
  var require_json = __commonJS({
    "modules/std/data/json.js"(exports2, module2) {
      "use strict";
      var { Pair, PairList, ZuzuBag } = require_collections();
      var { BinaryString: BinaryString2 } = require_runtime_helpers();
      var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
      var utf8Encoder = new TextEncoder();
      function _isPlainObject(value) {
        return value != null && typeof value === "object" && !Array.isArray(value) && !(value instanceof PairList) && !(value instanceof ZuzuBag) && Object.prototype.toString.call(value) !== "[object Set]";
      }
      function _isSet(value) {
        return Object.prototype.toString.call(value) === "[object Set]";
      }
      function _optionsObject(value) {
        if (value instanceof PairList) {
          const out = {};
          for (const [key, inner] of value.list) {
            out[String(key)] = inner;
          }
          return out;
        }
        if (_isPlainObject(value)) {
          return value;
        }
        return {};
      }
      function _decorateDict(value) {
        if (!_isPlainObject(value)) {
          return value;
        }
        const sortedKeys = () => Object.keys(value).sort();
        for (const [name2, fn2] of [
          ["length", function _length() {
            return Object.keys(this).length;
          }],
          ["count", function _count() {
            return Object.keys(this).length;
          }],
          ["empty", function _empty() {
            return Object.keys(this).length === 0 ? 1 : 0;
          }],
          ["keys", function _keys() {
            return new Set(sortedKeys());
          }],
          ["values", function _values() {
            return new ZuzuBag(sortedKeys().map((key) => this[key]));
          }],
          [
            "enumerate",
            function _enumerate() {
              return new ZuzuBag(
                sortedKeys().map(
                  (key) => new Pair({ pair: [key, this[key]] })
                )
              );
            }
          ],
          ["has", function _has(key) {
            return Object.prototype.hasOwnProperty.call(this, String(key)) ? 1 : 0;
          }],
          ["contains", function _contains(key) {
            return this.has(key);
          }],
          ["exists", function _exists(key) {
            return this.has(key);
          }],
          ["defined", function _defined(key) {
            return this.has(key) && this[String(key)] != null ? 1 : 0;
          }],
          ["get", function _get(key, fallback = null) {
            return this.has(key) ? this[String(key)] : fallback;
          }],
          ["add", function _add(key, inner) {
            this[String(key)] = inner;
            return this;
          }],
          ["set", function _set(key, inner) {
            return this.add(key, inner);
          }],
          [
            "kv",
            function _kv() {
              const out = [];
              for (const key of sortedKeys()) {
                out.push(key, this[key]);
              }
              return out;
            }
          ],
          ["sorted_keys", function _sorted_keys() {
            return sortedKeys();
          }],
          [
            "to_Array",
            function _to_array() {
              return sortedKeys().map(
                (key) => new Pair({ pair: [key, this[key]] })
              );
            }
          ],
          ["to_Iterator", function _to_iterator() {
            return sortedKeys()[Symbol.iterator]();
          }],
          [
            "for_each_key",
            function _for_each_key(fn3) {
              for (const key of sortedKeys()) {
                fn3(key);
              }
              return this;
            }
          ],
          [
            "for_each_value",
            function _for_each_value(fn3) {
              for (const key of sortedKeys()) {
                fn3(this[key]);
              }
              return this;
            }
          ],
          [
            "for_each_pair",
            function _for_each_pair(fn3) {
              for (const key of sortedKeys()) {
                fn3(new Pair({ pair: [key, this[key]] }));
              }
              return this;
            }
          ],
          [
            "remove",
            function _remove(key) {
              if (typeof key === "function") {
                for (const entryKey of Object.keys(this)) {
                  if (key(new Pair({ pair: [entryKey, this[entryKey]] }))) {
                    delete this[entryKey];
                  }
                }
                return this;
              }
              delete this[String(key)];
              return this;
            }
          ],
          [
            "clear",
            function _clear() {
              for (const key of Object.keys(this)) {
                delete this[key];
              }
              return this;
            }
          ]
        ]) {
          if (!Object.prototype.hasOwnProperty.call(value, name2)) {
            Object.defineProperty(value, name2, {
              value: fn2,
              enumerable: false,
              configurable: true,
              writable: true
            });
          }
        }
        for (const key of Object.keys(value)) {
          value[key] = _decorateValue(value[key]);
        }
        return value;
      }
      function _decoratePairList(value) {
        if (!(value instanceof PairList)) {
          return value;
        }
        for (const [name2, getter] of [
          ["keys", function _keys() {
            return value.list.map((pair) => pair[0]);
          }],
          ["values", function _values() {
            return value.list.map((pair) => pair[1]);
          }]
        ]) {
          if (!Object.prototype.hasOwnProperty.call(value, name2)) {
            Object.defineProperty(value, name2, {
              get: getter,
              enumerable: false,
              configurable: true
            });
          }
        }
        return value;
      }
      function _decorateArray(value) {
        if (!Array.isArray(value)) {
          return value;
        }
        for (let i = 0; i < value.length; i++) {
          value[i] = _decorateValue(value[i]);
        }
        return value;
      }
      function _decorateValue(value) {
        if (Array.isArray(value)) {
          return _decorateArray(value);
        }
        if (value instanceof PairList) {
          return _decoratePairList(value);
        }
        if (_isPlainObject(value)) {
          return _decorateDict(value);
        }
        return value;
      }
      function _sortCollectionValues(values) {
        return values.slice().sort((left, right) => String(left).localeCompare(String(right)));
      }
      function _collapsePairListEntries(entries) {
        const order = [];
        const values = /* @__PURE__ */ new Map();
        for (const [rawKey, entryValue] of entries) {
          const key = String(rawKey);
          if (!values.has(key)) {
            order.push(key);
          }
          values.set(key, entryValue);
        }
        return order.map((key) => [key, values.get(key)]);
      }
      function _objectEntriesForEncode(value, options) {
        if (value instanceof PairList) {
          const entries2 = value.list.map((pair) => [String(pair[0]), pair[1]]);
          if (options.pairlists) {
            return options.canonical ? entries2.slice().sort((left, right) => left[0].localeCompare(right[0])) : entries2;
          }
          value = Object.fromEntries(_collapsePairListEntries(entries2));
        }
        const entries = Object.keys(value).map((key) => [key, value[key]]);
        if (options.canonical) {
          entries.sort((left, right) => left[0].localeCompare(right[0]));
        }
        return entries;
      }
      function _encodeJson(value, options, depth = 0) {
        if (value == null) {
          return "null";
        }
        if (typeof value === "string") {
          return JSON.stringify(value);
        }
        if (typeof value === "number") {
          return Number.isFinite(value) ? String(value) : "null";
        }
        if (typeof value === "boolean") {
          return value ? "true" : "false";
        }
        if (Array.isArray(value)) {
          const items = value.map((item) => {
            const encoded = _encodeJson(item, options, depth + 1);
            return encoded === void 0 ? "null" : encoded;
          });
          if (!options.pretty) {
            return `[${items.join(",")}]`;
          }
          if (items.length === 0) {
            return "[]";
          }
          const indent = "	".repeat(depth);
          const inner = "	".repeat(depth + 1);
          return `[
${inner}${items.join(`,
${inner}`)}
${indent}]`;
        }
        if (value instanceof ZuzuBag) {
          return _encodeJson(_sortCollectionValues(value.items), options, depth);
        }
        if (_isSet(value)) {
          return _encodeJson(_sortCollectionValues([...value]), options, depth);
        }
        if (value instanceof PairList || _isPlainObject(value)) {
          const entries = _objectEntriesForEncode(value, options).map((pair) => [pair[0], _encodeJson(pair[1], options, depth + 1)]).filter((pair) => pair[1] !== void 0);
          if (!options.pretty) {
            return `{${entries.map((pair) => `${JSON.stringify(pair[0])}:${pair[1]}`).join(",")}}`;
          }
          if (entries.length === 0) {
            return "{}";
          }
          const indent = "	".repeat(depth);
          const inner = "	".repeat(depth + 1);
          return `{
${inner}${entries.map((pair) => `${JSON.stringify(pair[0])}: ${pair[1]}`).join(`,
${inner}`)}
${indent}}`;
        }
        if (typeof value.toJSON === "function") {
          return _encodeJson(value.toJSON(), options, depth);
        }
        return void 0;
      }
      function _parseJson(text, pairlists) {
        let index = 0;
        let source = "";
        if (text && text.bytes instanceof Uint8Array) {
          source = utf8Decoder.decode(text.bytes);
        } else {
          source = String(text ?? "");
        }
        function error(message) {
          throw new Error(`JSON.parse error at position ${index}: ${message}`);
        }
        function skipWhitespace() {
          while (index < source.length && /\s/u.test(source[index])) {
            index++;
          }
        }
        function parseString() {
          let out = "";
          index++;
          while (index < source.length) {
            const ch = source[index++];
            if (ch === '"') {
              return out;
            }
            if (ch !== "\\") {
              out += ch;
              continue;
            }
            if (index >= source.length) {
              error("unterminated escape sequence");
            }
            const esc = source[index++];
            if (esc === '"' || esc === "\\" || esc === "/") {
              out += esc;
              continue;
            }
            if (esc === "b") {
              out += "\b";
              continue;
            }
            if (esc === "f") {
              out += "\f";
              continue;
            }
            if (esc === "n") {
              out += "\n";
              continue;
            }
            if (esc === "r") {
              out += "\r";
              continue;
            }
            if (esc === "t") {
              out += "	";
              continue;
            }
            if (esc === "u") {
              const hex = source.slice(index, index + 4);
              if (!/^[0-9A-Fa-f]{4}$/u.test(hex)) {
                error("invalid unicode escape");
              }
              out += String.fromCharCode(Number.parseInt(hex, 16));
              index += 4;
              continue;
            }
            error(`invalid escape ${esc}`);
          }
          error("unterminated string literal");
        }
        function parseNumber() {
          const match = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/u.exec(source.slice(index));
          if (!match) {
            error("invalid number");
          }
          index += match[0].length;
          return Number(match[0]);
        }
        function parseLiteral(literal, value2) {
          if (source.slice(index, index + literal.length) !== literal) {
            error(`expected ${literal}`);
          }
          index += literal.length;
          return value2;
        }
        function parseArray() {
          index++;
          skipWhitespace();
          const out = [];
          if (source[index] === "]") {
            index++;
            return out;
          }
          while (index < source.length) {
            out.push(parseValue());
            skipWhitespace();
            if (source[index] === "]") {
              index++;
              return out;
            }
            if (source[index] !== ",") {
              error("expected , or ]");
            }
            index++;
            skipWhitespace();
          }
          error("unterminated array");
        }
        function parseObject() {
          index++;
          skipWhitespace();
          const entries = [];
          if (source[index] === "}") {
            index++;
            return pairlists ? _decoratePairList(new PairList()) : _decorateDict({});
          }
          while (index < source.length) {
            if (source[index] !== '"') {
              error("expected object key string");
            }
            const key = parseString();
            skipWhitespace();
            if (source[index] !== ":") {
              error("expected :");
            }
            index++;
            skipWhitespace();
            entries.push([key, parseValue()]);
            skipWhitespace();
            if (source[index] === "}") {
              index++;
              if (pairlists) {
                return _decoratePairList(new PairList({ list: entries }));
              }
              const out = {};
              for (const [entryKey, entryValue] of entries) {
                Object.defineProperty(out, entryKey, {
                  value: entryValue,
                  enumerable: true,
                  configurable: true,
                  writable: true
                });
              }
              return _decorateDict(out);
            }
            if (source[index] !== ",") {
              error("expected , or }");
            }
            index++;
            skipWhitespace();
          }
          error("unterminated object");
        }
        function parseValue() {
          skipWhitespace();
          const ch = source[index];
          if (ch === '"') {
            return parseString();
          }
          if (ch === "[") {
            return parseArray();
          }
          if (ch === "{") {
            return parseObject();
          }
          if (ch === "t") {
            return parseLiteral("true", true);
          }
          if (ch === "f") {
            return parseLiteral("false", false);
          }
          if (ch === "n") {
            return parseLiteral("null", null);
          }
          return parseNumber();
        }
        const value = parseValue();
        skipWhitespace();
        if (index !== source.length) {
          error("unexpected trailing input");
        }
        return _decorateValue(value);
      }
      function _asPath(value, methodName) {
        if (value && typeof value.slurp === "function" && typeof value.spew === "function") {
          return value;
        }
        throw new Error(`TypeException: ${methodName} expects Path as first argument`);
      }
      var JSONCodec = class {
        constructor(options = {}, named = {}) {
          const merged = {
            ..._optionsObject(options),
            ..._optionsObject(named)
          };
          this.utf8 = Boolean(merged.utf8);
          this.pretty = Boolean(merged.pretty);
          this.canonical = Boolean(merged.canonical);
          this.pairlists = Boolean(merged.pairlists);
        }
        encode(value) {
          return _encodeJson(value, {
            canonical: this.canonical,
            pairlists: this.pairlists,
            pretty: this.pretty
          });
        }
        encode_binarystring(value) {
          return new BinaryString2(utf8Encoder.encode(this.encode(value)));
        }
        decode(text) {
          return _parseJson(text, this.pairlists);
        }
        decode_binarystring(raw) {
          if (!(raw instanceof BinaryString2)) {
            throw new Error("TypeException: JSON.decode_binarystring expects BinaryString");
          }
          return _parseJson(raw, this.pairlists);
        }
        load(pathObj) {
          const pathValue = _asPath(pathObj, "JSON.load");
          return this.decode_binarystring(pathValue.slurp());
        }
        dump(pathObj, value) {
          const pathValue = _asPath(pathObj, "JSON.dump");
          pathValue.spew(this.encode_binarystring(value));
          return pathObj;
        }
      };
      module2.exports = {
        JSON: JSONCodec
      };
    }
  });

  // node_modules/js-yaml/lib/common.js
  var require_common = __commonJS({
    "node_modules/js-yaml/lib/common.js"(exports2, module2) {
      "use strict";
      function isNothing(subject) {
        return typeof subject === "undefined" || subject === null;
      }
      function isObject(subject) {
        return typeof subject === "object" && subject !== null;
      }
      function toArray(sequence) {
        if (Array.isArray(sequence)) return sequence;
        else if (isNothing(sequence)) return [];
        return [sequence];
      }
      function extend(target, source) {
        var index, length, key, sourceKeys;
        if (source) {
          sourceKeys = Object.keys(source);
          for (index = 0, length = sourceKeys.length; index < length; index += 1) {
            key = sourceKeys[index];
            target[key] = source[key];
          }
        }
        return target;
      }
      function repeat(string, count) {
        var result = "", cycle;
        for (cycle = 0; cycle < count; cycle += 1) {
          result += string;
        }
        return result;
      }
      function isNegativeZero(number) {
        return number === 0 && Number.NEGATIVE_INFINITY === 1 / number;
      }
      module2.exports.isNothing = isNothing;
      module2.exports.isObject = isObject;
      module2.exports.toArray = toArray;
      module2.exports.repeat = repeat;
      module2.exports.isNegativeZero = isNegativeZero;
      module2.exports.extend = extend;
    }
  });

  // node_modules/js-yaml/lib/exception.js
  var require_exception = __commonJS({
    "node_modules/js-yaml/lib/exception.js"(exports2, module2) {
      "use strict";
      function formatError(exception, compact) {
        var where = "", message = exception.reason || "(unknown reason)";
        if (!exception.mark) return message;
        if (exception.mark.name) {
          where += 'in "' + exception.mark.name + '" ';
        }
        where += "(" + (exception.mark.line + 1) + ":" + (exception.mark.column + 1) + ")";
        if (!compact && exception.mark.snippet) {
          where += "\n\n" + exception.mark.snippet;
        }
        return message + " " + where;
      }
      function YAMLException(reason, mark) {
        Error.call(this);
        this.name = "YAMLException";
        this.reason = reason;
        this.mark = mark;
        this.message = formatError(this, false);
        if (Error.captureStackTrace) {
          Error.captureStackTrace(this, this.constructor);
        } else {
          this.stack = new Error().stack || "";
        }
      }
      YAMLException.prototype = Object.create(Error.prototype);
      YAMLException.prototype.constructor = YAMLException;
      YAMLException.prototype.toString = function toString(compact) {
        return this.name + ": " + formatError(this, compact);
      };
      module2.exports = YAMLException;
    }
  });

  // node_modules/js-yaml/lib/snippet.js
  var require_snippet = __commonJS({
    "node_modules/js-yaml/lib/snippet.js"(exports2, module2) {
      "use strict";
      var common = require_common();
      function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
        var head = "";
        var tail = "";
        var maxHalfLength = Math.floor(maxLineLength / 2) - 1;
        if (position - lineStart > maxHalfLength) {
          head = " ... ";
          lineStart = position - maxHalfLength + head.length;
        }
        if (lineEnd - position > maxHalfLength) {
          tail = " ...";
          lineEnd = position + maxHalfLength - tail.length;
        }
        return {
          str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail,
          pos: position - lineStart + head.length
          // relative position
        };
      }
      function padStart(string, max) {
        return common.repeat(" ", max - string.length) + string;
      }
      function makeSnippet(mark, options) {
        options = Object.create(options || null);
        if (!mark.buffer) return null;
        if (!options.maxLength) options.maxLength = 79;
        if (typeof options.indent !== "number") options.indent = 1;
        if (typeof options.linesBefore !== "number") options.linesBefore = 3;
        if (typeof options.linesAfter !== "number") options.linesAfter = 2;
        var re = /\r?\n|\r|\0/g;
        var lineStarts = [0];
        var lineEnds = [];
        var match;
        var foundLineNo = -1;
        while (match = re.exec(mark.buffer)) {
          lineEnds.push(match.index);
          lineStarts.push(match.index + match[0].length);
          if (mark.position <= match.index && foundLineNo < 0) {
            foundLineNo = lineStarts.length - 2;
          }
        }
        if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;
        var result = "", i, line;
        var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
        var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
        for (i = 1; i <= options.linesBefore; i++) {
          if (foundLineNo - i < 0) break;
          line = getLine(
            mark.buffer,
            lineStarts[foundLineNo - i],
            lineEnds[foundLineNo - i],
            mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),
            maxLineLength
          );
          result = common.repeat(" ", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + " | " + line.str + "\n" + result;
        }
        line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
        result += common.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n";
        result += common.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n";
        for (i = 1; i <= options.linesAfter; i++) {
          if (foundLineNo + i >= lineEnds.length) break;
          line = getLine(
            mark.buffer,
            lineStarts[foundLineNo + i],
            lineEnds[foundLineNo + i],
            mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),
            maxLineLength
          );
          result += common.repeat(" ", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + " | " + line.str + "\n";
        }
        return result.replace(/\n$/, "");
      }
      module2.exports = makeSnippet;
    }
  });

  // node_modules/js-yaml/lib/type.js
  var require_type = __commonJS({
    "node_modules/js-yaml/lib/type.js"(exports2, module2) {
      "use strict";
      var YAMLException = require_exception();
      var TYPE_CONSTRUCTOR_OPTIONS = [
        "kind",
        "multi",
        "resolve",
        "construct",
        "instanceOf",
        "predicate",
        "represent",
        "representName",
        "defaultStyle",
        "styleAliases"
      ];
      var YAML_NODE_KINDS = [
        "scalar",
        "sequence",
        "mapping"
      ];
      function compileStyleAliases(map) {
        var result = {};
        if (map !== null) {
          Object.keys(map).forEach(function(style) {
            map[style].forEach(function(alias) {
              result[String(alias)] = style;
            });
          });
        }
        return result;
      }
      function Type(tag, options) {
        options = options || {};
        Object.keys(options).forEach(function(name2) {
          if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name2) === -1) {
            throw new YAMLException('Unknown option "' + name2 + '" is met in definition of "' + tag + '" YAML type.');
          }
        });
        this.options = options;
        this.tag = tag;
        this.kind = options["kind"] || null;
        this.resolve = options["resolve"] || function() {
          return true;
        };
        this.construct = options["construct"] || function(data) {
          return data;
        };
        this.instanceOf = options["instanceOf"] || null;
        this.predicate = options["predicate"] || null;
        this.represent = options["represent"] || null;
        this.representName = options["representName"] || null;
        this.defaultStyle = options["defaultStyle"] || null;
        this.multi = options["multi"] || false;
        this.styleAliases = compileStyleAliases(options["styleAliases"] || null);
        if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
          throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
        }
      }
      module2.exports = Type;
    }
  });

  // node_modules/js-yaml/lib/schema.js
  var require_schema = __commonJS({
    "node_modules/js-yaml/lib/schema.js"(exports2, module2) {
      "use strict";
      var YAMLException = require_exception();
      var Type = require_type();
      function compileList(schema, name2) {
        var result = [];
        schema[name2].forEach(function(currentType) {
          var newIndex = result.length;
          result.forEach(function(previousType, previousIndex) {
            if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) {
              newIndex = previousIndex;
            }
          });
          result[newIndex] = currentType;
        });
        return result;
      }
      function compileMap() {
        var result = {
          scalar: {},
          sequence: {},
          mapping: {},
          fallback: {},
          multi: {
            scalar: [],
            sequence: [],
            mapping: [],
            fallback: []
          }
        }, index, length;
        function collectType(type) {
          if (type.multi) {
            result.multi[type.kind].push(type);
            result.multi["fallback"].push(type);
          } else {
            result[type.kind][type.tag] = result["fallback"][type.tag] = type;
          }
        }
        for (index = 0, length = arguments.length; index < length; index += 1) {
          arguments[index].forEach(collectType);
        }
        return result;
      }
      function Schema(definition) {
        return this.extend(definition);
      }
      Schema.prototype.extend = function extend(definition) {
        var implicit = [];
        var explicit = [];
        if (definition instanceof Type) {
          explicit.push(definition);
        } else if (Array.isArray(definition)) {
          explicit = explicit.concat(definition);
        } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
          if (definition.implicit) implicit = implicit.concat(definition.implicit);
          if (definition.explicit) explicit = explicit.concat(definition.explicit);
        } else {
          throw new YAMLException("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");
        }
        implicit.forEach(function(type) {
          if (!(type instanceof Type)) {
            throw new YAMLException("Specified list of YAML types (or a single Type object) contains a non-Type object.");
          }
          if (type.loadKind && type.loadKind !== "scalar") {
            throw new YAMLException("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");
          }
          if (type.multi) {
            throw new YAMLException("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.");
          }
        });
        explicit.forEach(function(type) {
          if (!(type instanceof Type)) {
            throw new YAMLException("Specified list of YAML types (or a single Type object) contains a non-Type object.");
          }
        });
        var result = Object.create(Schema.prototype);
        result.implicit = (this.implicit || []).concat(implicit);
        result.explicit = (this.explicit || []).concat(explicit);
        result.compiledImplicit = compileList(result, "implicit");
        result.compiledExplicit = compileList(result, "explicit");
        result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);
        return result;
      };
      module2.exports = Schema;
    }
  });

  // node_modules/js-yaml/lib/type/str.js
  var require_str = __commonJS({
    "node_modules/js-yaml/lib/type/str.js"(exports2, module2) {
      "use strict";
      var Type = require_type();
      module2.exports = new Type("tag:yaml.org,2002:str", {
        kind: "scalar",
        construct: function(data) {
          return data !== null ? data : "";
        }
      });
    }
  });

  // node_modules/js-yaml/lib/type/seq.js
  var require_seq = __commonJS({
    "node_modules/js-yaml/lib/type/seq.js"(exports2, module2) {
      "use strict";
      var Type = require_type();
      module2.exports = new Type("tag:yaml.org,2002:seq", {
        kind: "sequence",
        construct: function(data) {
          return data !== null ? data : [];
        }
      });
    }
  });

  // node_modules/js-yaml/lib/type/map.js
  var require_map = __commonJS({
    "node_modules/js-yaml/lib/type/map.js"(exports2, module2) {
      "use strict";
      var Type = require_type();
      module2.exports = new Type("tag:yaml.org,2002:map", {
        kind: "mapping",
        construct: function(data) {
          return data !== null ? data : {};
        }
      });
    }
  });

  // node_modules/js-yaml/lib/schema/failsafe.js
  var require_failsafe = __commonJS({
    "node_modules/js-yaml/lib/schema/failsafe.js"(exports2, module2) {
      "use strict";
      var Schema = require_schema();
      module2.exports = new Schema({
        explicit: [
          require_str(),
          require_seq(),
          require_map()
        ]
      });
    }
  });

  // node_modules/js-yaml/lib/type/null.js
  var require_null = __commonJS({
    "node_modules/js-yaml/lib/type/null.js"(exports2, module2) {
      "use strict";
      var Type = require_type();
      function resolveYamlNull(data) {
        if (data === null) return true;
        var max = data.length;
        return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL");
      }
      function constructYamlNull() {
        return null;
      }
      function isNull(object) {
        return object === null;
      }
      module2.exports = new Type("tag:yaml.org,2002:null", {
        kind: "scalar",
        resolve: resolveYamlNull,
        construct: constructYamlNull,
        predicate: isNull,
        represent: {
          canonical: function() {
            return "~";
          },
          lowercase: function() {
            return "null";
          },
          uppercase: function() {
            return "NULL";
          },
          camelcase: function() {
            return "Null";
          },
          empty: function() {
            return "";
          }
        },
        defaultStyle: "lowercase"
      });
    }
  });

  // node_modules/js-yaml/lib/type/bool.js
  var require_bool = __commonJS({
    "node_modules/js-yaml/lib/type/bool.js"(exports2, module2) {
      "use strict";
      var Type = require_type();
      function resolveYamlBoolean(data) {
        if (data === null) return false;
        var max = data.length;
        return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE");
      }
      function constructYamlBoolean(data) {
        return data === "true" || data === "True" || data === "TRUE";
      }
      function isBoolean(object) {
        return Object.prototype.toString.call(object) === "[object Boolean]";
      }
      module2.exports = new Type("tag:yaml.org,2002:bool", {
        kind: "scalar",
        resolve: resolveYamlBoolean,
        construct: constructYamlBoolean,
        predicate: isBoolean,
        represent: {
          lowercase: function(object) {
            return object ? "true" : "false";
          },
          uppercase: function(object) {
            return object ? "TRUE" : "FALSE";
          },
          camelcase: function(object) {
            return object ? "True" : "False";
          }
        },
        defaultStyle: "lowercase"
      });
    }
  });

  // node_modules/js-yaml/lib/type/int.js
  var require_int = __commonJS({
    "node_modules/js-yaml/lib/type/int.js"(exports2, module2) {
      "use strict";
      var common = require_common();
      var Type = require_type();
      function isHexCode(c) {
        return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102;
      }
      function isOctCode(c) {
        return 48 <= c && c <= 55;
      }
      function isDecCode(c) {
        return 48 <= c && c <= 57;
      }
      function resolveYamlInteger(data) {
        if (data === null) return false;
        var max = data.length, index = 0, hasDigits = false, ch;
        if (!max) return false;
        ch = data[index];
        if (ch === "-" || ch === "+") {
          ch = data[++index];
        }
        if (ch === "0") {
          if (index + 1 === max) return true;
          ch = data[++index];
          if (ch === "b") {
            index++;
            for (; index < max; index++) {
              ch = data[index];
              if (ch === "_") continue;
              if (ch !== "0" && ch !== "1") return false;
              hasDigits = true;
            }
            return hasDigits && ch !== "_";
          }
          if (ch === "x") {
            index++;
            for (; index < max; index++) {
              ch = data[index];
              if (ch === "_") continue;
              if (!isHexCode(data.charCodeAt(index))) return false;
              hasDigits = true;
            }
            return hasDigits && ch !== "_";
          }
          if (ch === "o") {
            index++;
            for (; index < max; index++) {
              ch = data[index];
              if (ch === "_") continue;
              if (!isOctCode(data.charCodeAt(index))) return false;
              hasDigits = true;
            }
            return hasDigits && ch !== "_";
          }
        }
        if (ch === "_") return false;
        for (; index < max; index++) {
          ch = data[index];
          if (ch === "_") continue;
          if (!isDecCode(data.charCodeAt(index))) {
            return false;
          }
          hasDigits = true;
        }
        if (!hasDigits || ch === "_") return false;
        return true;
      }
      function constructYamlInteger(data) {
        var value = data, sign = 1, ch;
        if (value.indexOf("_") !== -1) {
          value = value.replace(/_/g, "");
        }
        ch = value[0];
        if (ch === "-" || ch === "+") {
          if (ch === "-") sign = -1;
          value = value.slice(1);
          ch = value[0];
        }
        if (value === "0") return 0;
        if (ch === "0") {
          if (value[1] === "b") return sign * parseInt(value.slice(2), 2);
          if (value[1] === "x") return sign * parseInt(value.slice(2), 16);
          if (value[1] === "o") return sign * parseInt(value.slice(2), 8);
        }
        return sign * parseInt(value, 10);
      }
      function isInteger(object) {
        return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 === 0 && !common.isNegativeZero(object));
      }
      module2.exports = new Type("tag:yaml.org,2002:int", {
        kind: "scalar",
        resolve: resolveYamlInteger,
        construct: constructYamlInteger,
        predicate: isInteger,
        represent: {
          binary: function(obj) {
            return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);
          },
          octal: function(obj) {
            return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1);
          },
          decimal: function(obj) {
            return obj.toString(10);
          },
          /* eslint-disable max-len */
          hexadecimal: function(obj) {
            return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);
          }
        },
        defaultStyle: "decimal",
        styleAliases: {
          binary: [2, "bin"],
          octal: [8, "oct"],
          decimal: [10, "dec"],
          hexadecimal: [16, "hex"]
        }
      });
    }
  });

  // node_modules/js-yaml/lib/type/float.js
  var require_float = __commonJS({
    "node_modules/js-yaml/lib/type/float.js"(exports2, module2) {
      "use strict";
      var common = require_common();
      var Type = require_type();
      var YAML_FLOAT_PATTERN = new RegExp(
        // 2.5e4, 2.5 and integers
        "^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"
      );
      function resolveYamlFloat(data) {
        if (data === null) return false;
        if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_`
        // Probably should update regexp & check speed
        data[data.length - 1] === "_") {
          return false;
        }
        return true;
      }
      function constructYamlFloat(data) {
        var value, sign;
        value = data.replace(/_/g, "").toLowerCase();
        sign = value[0] === "-" ? -1 : 1;
        if ("+-".indexOf(value[0]) >= 0) {
          value = value.slice(1);
        }
        if (value === ".inf") {
          return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
        } else if (value === ".nan") {
          return NaN;
        }
        return sign * parseFloat(value, 10);
      }
      var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
      function representYamlFloat(object, style) {
        var res;
        if (isNaN(object)) {
          switch (style) {
            case "lowercase":
              return ".nan";
            case "uppercase":
              return ".NAN";
            case "camelcase":
              return ".NaN";
          }
        } else if (Number.POSITIVE_INFINITY === object) {
          switch (style) {
            case "lowercase":
              return ".inf";
            case "uppercase":
              return ".INF";
            case "camelcase":
              return ".Inf";
          }
        } else if (Number.NEGATIVE_INFINITY === object) {
          switch (style) {
            case "lowercase":
              return "-.inf";
            case "uppercase":
              return "-.INF";
            case "camelcase":
              return "-.Inf";
          }
        } else if (common.isNegativeZero(object)) {
          return "-0.0";
        }
        res = object.toString(10);
        return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
      }
      function isFloat(object) {
        return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common.isNegativeZero(object));
      }
      module2.exports = new Type("tag:yaml.org,2002:float", {
        kind: "scalar",
        resolve: resolveYamlFloat,
        construct: constructYamlFloat,
        predicate: isFloat,
        represent: representYamlFloat,
        defaultStyle: "lowercase"
      });
    }
  });

  // node_modules/js-yaml/lib/schema/json.js
  var require_json2 = __commonJS({
    "node_modules/js-yaml/lib/schema/json.js"(exports2, module2) {
      "use strict";
      module2.exports = require_failsafe().extend({
        implicit: [
          require_null(),
          require_bool(),
          require_int(),
          require_float()
        ]
      });
    }
  });

  // node_modules/js-yaml/lib/schema/core.js
  var require_core = __commonJS({
    "node_modules/js-yaml/lib/schema/core.js"(exports2, module2) {
      "use strict";
      module2.exports = require_json2();
    }
  });

  // node_modules/js-yaml/lib/type/timestamp.js
  var require_timestamp = __commonJS({
    "node_modules/js-yaml/lib/type/timestamp.js"(exports2, module2) {
      "use strict";
      var Type = require_type();
      var YAML_DATE_REGEXP = new RegExp(
        "^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"
      );
      var YAML_TIMESTAMP_REGEXP = new RegExp(
        "^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$"
      );
      function resolveYamlTimestamp(data) {
        if (data === null) return false;
        if (YAML_DATE_REGEXP.exec(data) !== null) return true;
        if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
        return false;
      }
      function constructYamlTimestamp(data) {
        var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date;
        match = YAML_DATE_REGEXP.exec(data);
        if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
        if (match === null) throw new Error("Date resolve error");
        year = +match[1];
        month = +match[2] - 1;
        day = +match[3];
        if (!match[4]) {
          return new Date(Date.UTC(year, month, day));
        }
        hour = +match[4];
        minute = +match[5];
        second = +match[6];
        if (match[7]) {
          fraction = match[7].slice(0, 3);
          while (fraction.length < 3) {
            fraction += "0";
          }
          fraction = +fraction;
        }
        if (match[9]) {
          tz_hour = +match[10];
          tz_minute = +(match[11] || 0);
          delta = (tz_hour * 60 + tz_minute) * 6e4;
          if (match[9] === "-") delta = -delta;
        }
        date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
        if (delta) date.setTime(date.getTime() - delta);
        return date;
      }
      function representYamlTimestamp(object) {
        return object.toISOString();
      }
      module2.exports = new Type("tag:yaml.org,2002:timestamp", {
        kind: "scalar",
        resolve: resolveYamlTimestamp,
        construct: constructYamlTimestamp,
        instanceOf: Date,
        represent: representYamlTimestamp
      });
    }
  });

  // node_modules/js-yaml/lib/type/merge.js
  var require_merge = __commonJS({
    "node_modules/js-yaml/lib/type/merge.js"(exports2, module2) {
      "use strict";
      var Type = require_type();
      function resolveYamlMerge(data) {
        return data === "<<" || data === null;
      }
      module2.exports = new Type("tag:yaml.org,2002:merge", {
        kind: "scalar",
        resolve: resolveYamlMerge
      });
    }
  });

  // node_modules/js-yaml/lib/type/binary.js
  var require_binary = __commonJS({
    "node_modules/js-yaml/lib/type/binary.js"(exports2, module2) {
      "use strict";
      var Type = require_type();
      var BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
      function resolveYamlBinary(data) {
        if (data === null) return false;
        var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
        for (idx = 0; idx < max; idx++) {
          code = map.indexOf(data.charAt(idx));
          if (code > 64) continue;
          if (code < 0) return false;
          bitlen += 6;
        }
        return bitlen % 8 === 0;
      }
      function constructYamlBinary(data) {
        var idx, tailbits, input = data.replace(/[\r\n=]/g, ""), max = input.length, map = BASE64_MAP, bits = 0, result = [];
        for (idx = 0; idx < max; idx++) {
          if (idx % 4 === 0 && idx) {
            result.push(bits >> 16 & 255);
            result.push(bits >> 8 & 255);
            result.push(bits & 255);
          }
          bits = bits << 6 | map.indexOf(input.charAt(idx));
        }
        tailbits = max % 4 * 6;
        if (tailbits === 0) {
          result.push(bits >> 16 & 255);
          result.push(bits >> 8 & 255);
          result.push(bits & 255);
        } else if (tailbits === 18) {
          result.push(bits >> 10 & 255);
          result.push(bits >> 2 & 255);
        } else if (tailbits === 12) {
          result.push(bits >> 4 & 255);
        }
        return new Uint8Array(result);
      }
      function representYamlBinary(object) {
        var result = "", bits = 0, idx, tail, max = object.length, map = BASE64_MAP;
        for (idx = 0; idx < max; idx++) {
          if (idx % 3 === 0 && idx) {
            result += map[bits >> 18 & 63];
            result += map[bits >> 12 & 63];
            result += map[bits >> 6 & 63];
            result += map[bits & 63];
          }
          bits = (bits << 8) + object[idx];
        }
        tail = max % 3;
        if (tail === 0) {
          result += map[bits >> 18 & 63];
          result += map[bits >> 12 & 63];
          result += map[bits >> 6 & 63];
          result += map[bits & 63];
        } else if (tail === 2) {
          result += map[bits >> 10 & 63];
          result += map[bits >> 4 & 63];
          result += map[bits << 2 & 63];
          result += map[64];
        } else if (tail === 1) {
          result += map[bits >> 2 & 63];
          result += map[bits << 4 & 63];
          result += map[64];
          result += map[64];
        }
        return result;
      }
      function isBinary(obj) {
        return Object.prototype.toString.call(obj) === "[object Uint8Array]";
      }
      module2.exports = new Type("tag:yaml.org,2002:binary", {
        kind: "scalar",
        resolve: resolveYamlBinary,
        construct: constructYamlBinary,
        predicate: isBinary,
        represent: representYamlBinary
      });
    }
  });

  // node_modules/js-yaml/lib/type/omap.js
  var require_omap = __commonJS({
    "node_modules/js-yaml/lib/type/omap.js"(exports2, module2) {
      "use strict";
      var Type = require_type();
      var _hasOwnProperty = Object.prototype.hasOwnProperty;
      var _toString = Object.prototype.toString;
      function resolveYamlOmap(data) {
        if (data === null) return true;
        var objectKeys = [], index, length, pair, pairKey, pairHasKey, object = data;
        for (index = 0, length = object.length; index < length; index += 1) {
          pair = object[index];
          pairHasKey = false;
          if (_toString.call(pair) !== "[object Object]") return false;
          for (pairKey in pair) {
            if (_hasOwnProperty.call(pair, pairKey)) {
              if (!pairHasKey) pairHasKey = true;
              else return false;
            }
          }
          if (!pairHasKey) return false;
          if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
          else return false;
        }
        return true;
      }
      function constructYamlOmap(data) {
        return data !== null ? data : [];
      }
      module2.exports = new Type("tag:yaml.org,2002:omap", {
        kind: "sequence",
        resolve: resolveYamlOmap,
        construct: constructYamlOmap
      });
    }
  });

  // node_modules/js-yaml/lib/type/pairs.js
  var require_pairs = __commonJS({
    "node_modules/js-yaml/lib/type/pairs.js"(exports2, module2) {
      "use strict";
      var Type = require_type();
      var _toString = Object.prototype.toString;
      function resolveYamlPairs(data) {
        if (data === null) return true;
        var index, length, pair, keys, result, object = data;
        result = new Array(object.length);
        for (index = 0, length = object.length; index < length; index += 1) {
          pair = object[index];
          if (_toString.call(pair) !== "[object Object]") return false;
          keys = Object.keys(pair);
          if (keys.length !== 1) return false;
          result[index] = [keys[0], pair[keys[0]]];
        }
        return true;
      }
      function constructYamlPairs(data) {
        if (data === null) return [];
        var index, length, pair, keys, result, object = data;
        result = new Array(object.length);
        for (index = 0, length = object.length; index < length; index += 1) {
          pair = object[index];
          keys = Object.keys(pair);
          result[index] = [keys[0], pair[keys[0]]];
        }
        return result;
      }
      module2.exports = new Type("tag:yaml.org,2002:pairs", {
        kind: "sequence",
        resolve: resolveYamlPairs,
        construct: constructYamlPairs
      });
    }
  });

  // node_modules/js-yaml/lib/type/set.js
  var require_set = __commonJS({
    "node_modules/js-yaml/lib/type/set.js"(exports2, module2) {
      "use strict";
      var Type = require_type();
      var _hasOwnProperty = Object.prototype.hasOwnProperty;
      function resolveYamlSet(data) {
        if (data === null) return true;
        var key, object = data;
        for (key in object) {
          if (_hasOwnProperty.call(object, key)) {
            if (object[key] !== null) return false;
          }
        }
        return true;
      }
      function constructYamlSet(data) {
        return data !== null ? data : {};
      }
      module2.exports = new Type("tag:yaml.org,2002:set", {
        kind: "mapping",
        resolve: resolveYamlSet,
        construct: constructYamlSet
      });
    }
  });

  // node_modules/js-yaml/lib/schema/default.js
  var require_default = __commonJS({
    "node_modules/js-yaml/lib/schema/default.js"(exports2, module2) {
      "use strict";
      module2.exports = require_core().extend({
        implicit: [
          require_timestamp(),
          require_merge()
        ],
        explicit: [
          require_binary(),
          require_omap(),
          require_pairs(),
          require_set()
        ]
      });
    }
  });

  // node_modules/js-yaml/lib/loader.js
  var require_loader = __commonJS({
    "node_modules/js-yaml/lib/loader.js"(exports2, module2) {
      "use strict";
      var common = require_common();
      var YAMLException = require_exception();
      var makeSnippet = require_snippet();
      var DEFAULT_SCHEMA = require_default();
      var _hasOwnProperty = Object.prototype.hasOwnProperty;
      var CONTEXT_FLOW_IN = 1;
      var CONTEXT_FLOW_OUT = 2;
      var CONTEXT_BLOCK_IN = 3;
      var CONTEXT_BLOCK_OUT = 4;
      var CHOMPING_CLIP = 1;
      var CHOMPING_STRIP = 2;
      var CHOMPING_KEEP = 3;
      var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
      var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
      var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
      var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
      var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
      function _class(obj) {
        return Object.prototype.toString.call(obj);
      }
      function is_EOL(c) {
        return c === 10 || c === 13;
      }
      function is_WHITE_SPACE(c) {
        return c === 9 || c === 32;
      }
      function is_WS_OR_EOL(c) {
        return c === 9 || c === 32 || c === 10 || c === 13;
      }
      function is_FLOW_INDICATOR(c) {
        return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;
      }
      function fromHexCode(c) {
        var lc;
        if (48 <= c && c <= 57) {
          return c - 48;
        }
        lc = c | 32;
        if (97 <= lc && lc <= 102) {
          return lc - 97 + 10;
        }
        return -1;
      }
      function escapedHexLen(c) {
        if (c === 120) {
          return 2;
        }
        if (c === 117) {
          return 4;
        }
        if (c === 85) {
          return 8;
        }
        return 0;
      }
      function fromDecimalCode(c) {
        if (48 <= c && c <= 57) {
          return c - 48;
        }
        return -1;
      }
      function simpleEscapeSequence(c) {
        return c === 48 ? "\0" : c === 97 ? "\x07" : c === 98 ? "\b" : c === 116 ? "	" : c === 9 ? "	" : c === 110 ? "\n" : c === 118 ? "\v" : c === 102 ? "\f" : c === 114 ? "\r" : c === 101 ? "\x1B" : c === 32 ? " " : c === 34 ? '"' : c === 47 ? "/" : c === 92 ? "\\" : c === 78 ? "\x85" : c === 95 ? "\xA0" : c === 76 ? "\u2028" : c === 80 ? "\u2029" : "";
      }
      function charFromCodepoint(c) {
        if (c <= 65535) {
          return String.fromCharCode(c);
        }
        return String.fromCharCode(
          (c - 65536 >> 10) + 55296,
          (c - 65536 & 1023) + 56320
        );
      }
      function setProperty(object, key, value) {
        if (key === "__proto__") {
          Object.defineProperty(object, key, {
            configurable: true,
            enumerable: true,
            writable: true,
            value
          });
        } else {
          object[key] = value;
        }
      }
      var simpleEscapeCheck = new Array(256);
      var simpleEscapeMap = new Array(256);
      for (i = 0; i < 256; i++) {
        simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
        simpleEscapeMap[i] = simpleEscapeSequence(i);
      }
      var i;
      function State(input, options) {
        this.input = input;
        this.filename = options["filename"] || null;
        this.schema = options["schema"] || DEFAULT_SCHEMA;
        this.onWarning = options["onWarning"] || null;
        this.legacy = options["legacy"] || false;
        this.json = options["json"] || false;
        this.listener = options["listener"] || null;
        this.implicitTypes = this.schema.compiledImplicit;
        this.typeMap = this.schema.compiledTypeMap;
        this.length = input.length;
        this.position = 0;
        this.line = 0;
        this.lineStart = 0;
        this.lineIndent = 0;
        this.firstTabInLine = -1;
        this.documents = [];
      }
      function generateError(state, message) {
        var mark = {
          name: state.filename,
          buffer: state.input.slice(0, -1),
          // omit trailing \0
          position: state.position,
          line: state.line,
          column: state.position - state.lineStart
        };
        mark.snippet = makeSnippet(mark);
        return new YAMLException(message, mark);
      }
      function throwError(state, message) {
        throw generateError(state, message);
      }
      function throwWarning(state, message) {
        if (state.onWarning) {
          state.onWarning.call(null, generateError(state, message));
        }
      }
      var directiveHandlers = {
        YAML: function handleYamlDirective(state, name2, args) {
          var match, major, minor;
          if (state.version !== null) {
            throwError(state, "duplication of %YAML directive");
          }
          if (args.length !== 1) {
            throwError(state, "YAML directive accepts exactly one argument");
          }
          match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
          if (match === null) {
            throwError(state, "ill-formed argument of the YAML directive");
          }
          major = parseInt(match[1], 10);
          minor = parseInt(match[2], 10);
          if (major !== 1) {
            throwError(state, "unacceptable YAML version of the document");
          }
          state.version = args[0];
          state.checkLineBreaks = minor < 2;
          if (minor !== 1 && minor !== 2) {
            throwWarning(state, "unsupported YAML version of the document");
          }
        },
        TAG: function handleTagDirective(state, name2, args) {
          var handle, prefix;
          if (args.length !== 2) {
            throwError(state, "TAG directive accepts exactly two arguments");
          }
          handle = args[0];
          prefix = args[1];
          if (!PATTERN_TAG_HANDLE.test(handle)) {
            throwError(state, "ill-formed tag handle (first argument) of the TAG directive");
          }
          if (_hasOwnProperty.call(state.tagMap, handle)) {
            throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
          }
          if (!PATTERN_TAG_URI.test(prefix)) {
            throwError(state, "ill-formed tag prefix (second argument) of the TAG directive");
          }
          try {
            prefix = decodeURIComponent(prefix);
          } catch (err) {
            throwError(state, "tag prefix is malformed: " + prefix);
          }
          state.tagMap[handle] = prefix;
        }
      };
      function captureSegment(state, start, end, checkJson) {
        var _position, _length, _character, _result;
        if (start < end) {
          _result = state.input.slice(start, end);
          if (checkJson) {
            for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
              _character = _result.charCodeAt(_position);
              if (!(_character === 9 || 32 <= _character && _character <= 1114111)) {
                throwError(state, "expected valid JSON character");
              }
            }
          } else if (PATTERN_NON_PRINTABLE.test(_result)) {
            throwError(state, "the stream contains non-printable characters");
          }
          state.result += _result;
        }
      }
      function mergeMappings(state, destination, source, overridableKeys) {
        var sourceKeys, key, index, quantity;
        if (!common.isObject(source)) {
          throwError(state, "cannot merge mappings; the provided source object is unacceptable");
        }
        sourceKeys = Object.keys(source);
        for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
          key = sourceKeys[index];
          if (!_hasOwnProperty.call(destination, key)) {
            setProperty(destination, key, source[key]);
            overridableKeys[key] = true;
          }
        }
      }
      function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) {
        var index, quantity;
        if (Array.isArray(keyNode)) {
          keyNode = Array.prototype.slice.call(keyNode);
          for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
            if (Array.isArray(keyNode[index])) {
              throwError(state, "nested arrays are not supported inside keys");
            }
            if (typeof keyNode === "object" && _class(keyNode[index]) === "[object Object]") {
              keyNode[index] = "[object Object]";
            }
          }
        }
        if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") {
          keyNode = "[object Object]";
        }
        keyNode = String(keyNode);
        if (_result === null) {
          _result = {};
        }
        if (keyTag === "tag:yaml.org,2002:merge") {
          if (Array.isArray(valueNode)) {
            for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
              mergeMappings(state, _result, valueNode[index], overridableKeys);
            }
          } else {
            mergeMappings(state, _result, valueNode, overridableKeys);
          }
        } else {
          if (!state.json && !_hasOwnProperty.call(overridableKeys, keyNode) && _hasOwnProperty.call(_result, keyNode)) {
            state.line = startLine || state.line;
            state.lineStart = startLineStart || state.lineStart;
            state.position = startPos || state.position;
            throwError(state, "duplicated mapping key");
          }
          setProperty(_result, keyNode, valueNode);
          delete overridableKeys[keyNode];
        }
        return _result;
      }
      function readLineBreak(state) {
        var ch;
        ch = state.input.charCodeAt(state.position);
        if (ch === 10) {
          state.position++;
        } else if (ch === 13) {
          state.position++;
          if (state.input.charCodeAt(state.position) === 10) {
            state.position++;
          }
        } else {
          throwError(state, "a line break is expected");
        }
        state.line += 1;
        state.lineStart = state.position;
        state.firstTabInLine = -1;
      }
      function skipSeparationSpace(state, allowComments, checkIndent) {
        var lineBreaks = 0, ch = state.input.charCodeAt(state.position);
        while (ch !== 0) {
          while (is_WHITE_SPACE(ch)) {
            if (ch === 9 && state.firstTabInLine === -1) {
              state.firstTabInLine = state.position;
            }
            ch = state.input.charCodeAt(++state.position);
          }
          if (allowComments && ch === 35) {
            do {
              ch = state.input.charCodeAt(++state.position);
            } while (ch !== 10 && ch !== 13 && ch !== 0);
          }
          if (is_EOL(ch)) {
            readLineBreak(state);
            ch = state.input.charCodeAt(state.position);
            lineBreaks++;
            state.lineIndent = 0;
            while (ch === 32) {
              state.lineIndent++;
              ch = state.input.charCodeAt(++state.position);
            }
          } else {
            break;
          }
        }
        if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
          throwWarning(state, "deficient indentation");
        }
        return lineBreaks;
      }
      function testDocumentSeparator(state) {
        var _position = state.position, ch;
        ch = state.input.charCodeAt(_position);
        if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) {
          _position += 3;
          ch = state.input.charCodeAt(_position);
          if (ch === 0 || is_WS_OR_EOL(ch)) {
            return true;
          }
        }
        return false;
      }
      function writeFoldedLines(state, count) {
        if (count === 1) {
          state.result += " ";
        } else if (count > 1) {
          state.result += common.repeat("\n", count - 1);
        }
      }
      function readPlainScalar(state, nodeIndent, withinFlowCollection) {
        var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch;
        ch = state.input.charCodeAt(state.position);
        if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) {
          return false;
        }
        if (ch === 63 || ch === 45) {
          following = state.input.charCodeAt(state.position + 1);
          if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
            return false;
          }
        }
        state.kind = "scalar";
        state.result = "";
        captureStart = captureEnd = state.position;
        hasPendingContent = false;
        while (ch !== 0) {
          if (ch === 58) {
            following = state.input.charCodeAt(state.position + 1);
            if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
              break;
            }
          } else if (ch === 35) {
            preceding = state.input.charCodeAt(state.position - 1);
            if (is_WS_OR_EOL(preceding)) {
              break;
            }
          } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && is_FLOW_INDICATOR(ch)) {
            break;
          } else if (is_EOL(ch)) {
            _line = state.line;
            _lineStart = state.lineStart;
            _lineIndent = state.lineIndent;
            skipSeparationSpace(state, false, -1);
            if (state.lineIndent >= nodeIndent) {
              hasPendingContent = true;
              ch = state.input.charCodeAt(state.position);
              continue;
            } else {
              state.position = captureEnd;
              state.line = _line;
              state.lineStart = _lineStart;
              state.lineIndent = _lineIndent;
              break;
            }
          }
          if (hasPendingContent) {
            captureSegment(state, captureStart, captureEnd, false);
            writeFoldedLines(state, state.line - _line);
            captureStart = captureEnd = state.position;
            hasPendingContent = false;
          }
          if (!is_WHITE_SPACE(ch)) {
            captureEnd = state.position + 1;
          }
          ch = state.input.charCodeAt(++state.position);
        }
        captureSegment(state, captureStart, captureEnd, false);
        if (state.result) {
          return true;
        }
        state.kind = _kind;
        state.result = _result;
        return false;
      }
      function readSingleQuotedScalar(state, nodeIndent) {
        var ch, captureStart, captureEnd;
        ch = state.input.charCodeAt(state.position);
        if (ch !== 39) {
          return false;
        }
        state.kind = "scalar";
        state.result = "";
        state.position++;
        captureStart = captureEnd = state.position;
        while ((ch = state.input.charCodeAt(state.position)) !== 0) {
          if (ch === 39) {
            captureSegment(state, captureStart, state.position, true);
            ch = state.input.charCodeAt(++state.position);
            if (ch === 39) {
              captureStart = state.position;
              state.position++;
              captureEnd = state.position;
            } else {
              return true;
            }
          } else if (is_EOL(ch)) {
            captureSegment(state, captureStart, captureEnd, true);
            writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
            captureStart = captureEnd = state.position;
          } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
            throwError(state, "unexpected end of the document within a single quoted scalar");
          } else {
            state.position++;
            captureEnd = state.position;
          }
        }
        throwError(state, "unexpected end of the stream within a single quoted scalar");
      }
      function readDoubleQuotedScalar(state, nodeIndent) {
        var captureStart, captureEnd, hexLength, hexResult, tmp, ch;
        ch = state.input.charCodeAt(state.position);
        if (ch !== 34) {
          return false;
        }
        state.kind = "scalar";
        state.result = "";
        state.position++;
        captureStart = captureEnd = state.position;
        while ((ch = state.input.charCodeAt(state.position)) !== 0) {
          if (ch === 34) {
            captureSegment(state, captureStart, state.position, true);
            state.position++;
            return true;
          } else if (ch === 92) {
            captureSegment(state, captureStart, state.position, true);
            ch = state.input.charCodeAt(++state.position);
            if (is_EOL(ch)) {
              skipSeparationSpace(state, false, nodeIndent);
            } else if (ch < 256 && simpleEscapeCheck[ch]) {
              state.result += simpleEscapeMap[ch];
              state.position++;
            } else if ((tmp = escapedHexLen(ch)) > 0) {
              hexLength = tmp;
              hexResult = 0;
              for (; hexLength > 0; hexLength--) {
                ch = state.input.charCodeAt(++state.position);
                if ((tmp = fromHexCode(ch)) >= 0) {
                  hexResult = (hexResult << 4) + tmp;
                } else {
                  throwError(state, "expected hexadecimal character");
                }
              }
              state.result += charFromCodepoint(hexResult);
              state.position++;
            } else {
              throwError(state, "unknown escape sequence");
            }
            captureStart = captureEnd = state.position;
          } else if (is_EOL(ch)) {
            captureSegment(state, captureStart, captureEnd, true);
            writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
            captureStart = captureEnd = state.position;
          } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
            throwError(state, "unexpected end of the document within a double quoted scalar");
          } else {
            state.position++;
            captureEnd = state.position;
          }
        }
        throwError(state, "unexpected end of the stream within a double quoted scalar");
      }
      function readFlowCollection(state, nodeIndent) {
        var readNext = true, _line, _lineStart, _pos, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = /* @__PURE__ */ Object.create(null), keyNode, keyTag, valueNode, ch;
        ch = state.input.charCodeAt(state.position);
        if (ch === 91) {
          terminator = 93;
          isMapping = false;
          _result = [];
        } else if (ch === 123) {
          terminator = 125;
          isMapping = true;
          _result = {};
        } else {
          return false;
        }
        if (state.anchor !== null) {
          state.anchorMap[state.anchor] = _result;
        }
        ch = state.input.charCodeAt(++state.position);
        while (ch !== 0) {
          skipSeparationSpace(state, true, nodeIndent);
          ch = state.input.charCodeAt(state.position);
          if (ch === terminator) {
            state.position++;
            state.tag = _tag;
            state.anchor = _anchor;
            state.kind = isMapping ? "mapping" : "sequence";
            state.result = _result;
            return true;
          } else if (!readNext) {
            throwError(state, "missed comma between flow collection entries");
          } else if (ch === 44) {
            throwError(state, "expected the node content, but found ','");
          }
          keyTag = keyNode = valueNode = null;
          isPair = isExplicitPair = false;
          if (ch === 63) {
            following = state.input.charCodeAt(state.position + 1);
            if (is_WS_OR_EOL(following)) {
              isPair = isExplicitPair = true;
              state.position++;
              skipSeparationSpace(state, true, nodeIndent);
            }
          }
          _line = state.line;
          _lineStart = state.lineStart;
          _pos = state.position;
          composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
          keyTag = state.tag;
          keyNode = state.result;
          skipSeparationSpace(state, true, nodeIndent);
          ch = state.input.charCodeAt(state.position);
          if ((isExplicitPair || state.line === _line) && ch === 58) {
            isPair = true;
            ch = state.input.charCodeAt(++state.position);
            skipSeparationSpace(state, true, nodeIndent);
            composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
            valueNode = state.result;
          }
          if (isMapping) {
            storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);
          } else if (isPair) {
            _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));
          } else {
            _result.push(keyNode);
          }
          skipSeparationSpace(state, true, nodeIndent);
          ch = state.input.charCodeAt(state.position);
          if (ch === 44) {
            readNext = true;
            ch = state.input.charCodeAt(++state.position);
          } else {
            readNext = false;
          }
        }
        throwError(state, "unexpected end of the stream within a flow collection");
      }
      function readBlockScalar(state, nodeIndent) {
        var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch;
        ch = state.input.charCodeAt(state.position);
        if (ch === 124) {
          folding = false;
        } else if (ch === 62) {
          folding = true;
        } else {
          return false;
        }
        state.kind = "scalar";
        state.result = "";
        while (ch !== 0) {
          ch = state.input.charCodeAt(++state.position);
          if (ch === 43 || ch === 45) {
            if (CHOMPING_CLIP === chomping) {
              chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP;
            } else {
              throwError(state, "repeat of a chomping mode identifier");
            }
          } else if ((tmp = fromDecimalCode(ch)) >= 0) {
            if (tmp === 0) {
              throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one");
            } else if (!detectedIndent) {
              textIndent = nodeIndent + tmp - 1;
              detectedIndent = true;
            } else {
              throwError(state, "repeat of an indentation width identifier");
            }
          } else {
            break;
          }
        }
        if (is_WHITE_SPACE(ch)) {
          do {
            ch = state.input.charCodeAt(++state.position);
          } while (is_WHITE_SPACE(ch));
          if (ch === 35) {
            do {
              ch = state.input.charCodeAt(++state.position);
            } while (!is_EOL(ch) && ch !== 0);
          }
        }
        while (ch !== 0) {
          readLineBreak(state);
          state.lineIndent = 0;
          ch = state.input.charCodeAt(state.position);
          while ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) {
            state.lineIndent++;
            ch = state.input.charCodeAt(++state.position);
          }
          if (!detectedIndent && state.lineIndent > textIndent) {
            textIndent = state.lineIndent;
          }
          if (is_EOL(ch)) {
            emptyLines++;
            continue;
          }
          if (state.lineIndent < textIndent) {
            if (chomping === CHOMPING_KEEP) {
              state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
            } else if (chomping === CHOMPING_CLIP) {
              if (didReadContent) {
                state.result += "\n";
              }
            }
            break;
          }
          if (folding) {
            if (is_WHITE_SPACE(ch)) {
              atMoreIndented = true;
              state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
            } else if (atMoreIndented) {
              atMoreIndented = false;
              state.result += common.repeat("\n", emptyLines + 1);
            } else if (emptyLines === 0) {
              if (didReadContent) {
                state.result += " ";
              }
            } else {
              state.result += common.repeat("\n", emptyLines);
            }
          } else {
            state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
          }
          didReadContent = true;
          detectedIndent = true;
          emptyLines = 0;
          captureStart = state.position;
          while (!is_EOL(ch) && ch !== 0) {
            ch = state.input.charCodeAt(++state.position);
          }
          captureSegment(state, captureStart, state.position, false);
        }
        return true;
      }
      function readBlockSequence(state, nodeIndent) {
        var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch;
        if (state.firstTabInLine !== -1) return false;
        if (state.anchor !== null) {
          state.anchorMap[state.anchor] = _result;
        }
        ch = state.input.charCodeAt(state.position);
        while (ch !== 0) {
          if (state.firstTabInLine !== -1) {
            state.position = state.firstTabInLine;
            throwError(state, "tab characters must not be used in indentation");
          }
          if (ch !== 45) {
            break;
          }
          following = state.input.charCodeAt(state.position + 1);
          if (!is_WS_OR_EOL(following)) {
            break;
          }
          detected = true;
          state.position++;
          if (skipSeparationSpace(state, true, -1)) {
            if (state.lineIndent <= nodeIndent) {
              _result.push(null);
              ch = state.input.charCodeAt(state.position);
              continue;
            }
          }
          _line = state.line;
          composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
          _result.push(state.result);
          skipSeparationSpace(state, true, -1);
          ch = state.input.charCodeAt(state.position);
          if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
            throwError(state, "bad indentation of a sequence entry");
          } else if (state.lineIndent < nodeIndent) {
            break;
          }
        }
        if (detected) {
          state.tag = _tag;
          state.anchor = _anchor;
          state.kind = "sequence";
          state.result = _result;
          return true;
        }
        return false;
      }
      function readBlockMapping(state, nodeIndent, flowIndent) {
        var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = /* @__PURE__ */ Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch;
        if (state.firstTabInLine !== -1) return false;
        if (state.anchor !== null) {
          state.anchorMap[state.anchor] = _result;
        }
        ch = state.input.charCodeAt(state.position);
        while (ch !== 0) {
          if (!atExplicitKey && state.firstTabInLine !== -1) {
            state.position = state.firstTabInLine;
            throwError(state, "tab characters must not be used in indentation");
          }
          following = state.input.charCodeAt(state.position + 1);
          _line = state.line;
          if ((ch === 63 || ch === 58) && is_WS_OR_EOL(following)) {
            if (ch === 63) {
              if (atExplicitKey) {
                storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
                keyTag = keyNode = valueNode = null;
              }
              detected = true;
              atExplicitKey = true;
              allowCompact = true;
            } else if (atExplicitKey) {
              atExplicitKey = false;
              allowCompact = true;
            } else {
              throwError(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");
            }
            state.position += 1;
            ch = following;
          } else {
            _keyLine = state.line;
            _keyLineStart = state.lineStart;
            _keyPos = state.position;
            if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
              break;
            }
            if (state.line === _line) {
              ch = state.input.charCodeAt(state.position);
              while (is_WHITE_SPACE(ch)) {
                ch = state.input.charCodeAt(++state.position);
              }
              if (ch === 58) {
                ch = state.input.charCodeAt(++state.position);
                if (!is_WS_OR_EOL(ch)) {
                  throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
                }
                if (atExplicitKey) {
                  storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
                  keyTag = keyNode = valueNode = null;
                }
                detected = true;
                atExplicitKey = false;
                allowCompact = false;
                keyTag = state.tag;
                keyNode = state.result;
              } else if (detected) {
                throwError(state, "can not read an implicit mapping pair; a colon is missed");
              } else {
                state.tag = _tag;
                state.anchor = _anchor;
                return true;
              }
            } else if (detected) {
              throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key");
            } else {
              state.tag = _tag;
              state.anchor = _anchor;
              return true;
            }
          }
          if (state.line === _line || state.lineIndent > nodeIndent) {
            if (atExplicitKey) {
              _keyLine = state.line;
              _keyLineStart = state.lineStart;
              _keyPos = state.position;
            }
            if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
              if (atExplicitKey) {
                keyNode = state.result;
              } else {
                valueNode = state.result;
              }
            }
            if (!atExplicitKey) {
              storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);
              keyTag = keyNode = valueNode = null;
            }
            skipSeparationSpace(state, true, -1);
            ch = state.input.charCodeAt(state.position);
          }
          if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
            throwError(state, "bad indentation of a mapping entry");
          } else if (state.lineIndent < nodeIndent) {
            break;
          }
        }
        if (atExplicitKey) {
          storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
        }
        if (detected) {
          state.tag = _tag;
          state.anchor = _anchor;
          state.kind = "mapping";
          state.result = _result;
        }
        return detected;
      }
      function readTagProperty(state) {
        var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch;
        ch = state.input.charCodeAt(state.position);
        if (ch !== 33) return false;
        if (state.tag !== null) {
          throwError(state, "duplication of a tag property");
        }
        ch = state.input.charCodeAt(++state.position);
        if (ch === 60) {
          isVerbatim = true;
          ch = state.input.charCodeAt(++state.position);
        } else if (ch === 33) {
          isNamed = true;
          tagHandle = "!!";
          ch = state.input.charCodeAt(++state.position);
        } else {
          tagHandle = "!";
        }
        _position = state.position;
        if (isVerbatim) {
          do {
            ch = state.input.charCodeAt(++state.position);
          } while (ch !== 0 && ch !== 62);
          if (state.position < state.length) {
            tagName = state.input.slice(_position, state.position);
            ch = state.input.charCodeAt(++state.position);
          } else {
            throwError(state, "unexpected end of the stream within a verbatim tag");
          }
        } else {
          while (ch !== 0 && !is_WS_OR_EOL(ch)) {
            if (ch === 33) {
              if (!isNamed) {
                tagHandle = state.input.slice(_position - 1, state.position + 1);
                if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
                  throwError(state, "named tag handle cannot contain such characters");
                }
                isNamed = true;
                _position = state.position + 1;
              } else {
                throwError(state, "tag suffix cannot contain exclamation marks");
              }
            }
            ch = state.input.charCodeAt(++state.position);
          }
          tagName = state.input.slice(_position, state.position);
          if (PATTERN_FLOW_INDICATORS.test(tagName)) {
            throwError(state, "tag suffix cannot contain flow indicator characters");
          }
        }
        if (tagName && !PATTERN_TAG_URI.test(tagName)) {
          throwError(state, "tag name cannot contain such characters: " + tagName);
        }
        try {
          tagName = decodeURIComponent(tagName);
        } catch (err) {
          throwError(state, "tag name is malformed: " + tagName);
        }
        if (isVerbatim) {
          state.tag = tagName;
        } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {
          state.tag = state.tagMap[tagHandle] + tagName;
        } else if (tagHandle === "!") {
          state.tag = "!" + tagName;
        } else if (tagHandle === "!!") {
          state.tag = "tag:yaml.org,2002:" + tagName;
        } else {
          throwError(state, 'undeclared tag handle "' + tagHandle + '"');
        }
        return true;
      }
      function readAnchorProperty(state) {
        var _position, ch;
        ch = state.input.charCodeAt(state.position);
        if (ch !== 38) return false;
        if (state.anchor !== null) {
          throwError(state, "duplication of an anchor property");
        }
        ch = state.input.charCodeAt(++state.position);
        _position = state.position;
        while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
          ch = state.input.charCodeAt(++state.position);
        }
        if (state.position === _position) {
          throwError(state, "name of an anchor node must contain at least one character");
        }
        state.anchor = state.input.slice(_position, state.position);
        return true;
      }
      function readAlias(state) {
        var _position, alias, ch;
        ch = state.input.charCodeAt(state.position);
        if (ch !== 42) return false;
        ch = state.input.charCodeAt(++state.position);
        _position = state.position;
        while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
          ch = state.input.charCodeAt(++state.position);
        }
        if (state.position === _position) {
          throwError(state, "name of an alias node must contain at least one character");
        }
        alias = state.input.slice(_position, state.position);
        if (!_hasOwnProperty.call(state.anchorMap, alias)) {
          throwError(state, 'unidentified alias "' + alias + '"');
        }
        state.result = state.anchorMap[alias];
        skipSeparationSpace(state, true, -1);
        return true;
      }
      function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
        var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, typeIndex, typeQuantity, typeList, type, flowIndent, blockIndent;
        if (state.listener !== null) {
          state.listener("open", state);
        }
        state.tag = null;
        state.anchor = null;
        state.kind = null;
        state.result = null;
        allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
        if (allowToSeek) {
          if (skipSeparationSpace(state, true, -1)) {
            atNewLine = true;
            if (state.lineIndent > parentIndent) {
              indentStatus = 1;
            } else if (state.lineIndent === parentIndent) {
              indentStatus = 0;
            } else if (state.lineIndent < parentIndent) {
              indentStatus = -1;
            }
          }
        }
        if (indentStatus === 1) {
          while (readTagProperty(state) || readAnchorProperty(state)) {
            if (skipSeparationSpace(state, true, -1)) {
              atNewLine = true;
              allowBlockCollections = allowBlockStyles;
              if (state.lineIndent > parentIndent) {
                indentStatus = 1;
              } else if (state.lineIndent === parentIndent) {
                indentStatus = 0;
              } else if (state.lineIndent < parentIndent) {
                indentStatus = -1;
              }
            } else {
              allowBlockCollections = false;
            }
          }
        }
        if (allowBlockCollections) {
          allowBlockCollections = atNewLine || allowCompact;
        }
        if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
          if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
            flowIndent = parentIndent;
          } else {
            flowIndent = parentIndent + 1;
          }
          blockIndent = state.position - state.lineStart;
          if (indentStatus === 1) {
            if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) {
              hasContent = true;
            } else {
              if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) {
                hasContent = true;
              } else if (readAlias(state)) {
                hasContent = true;
                if (state.tag !== null || state.anchor !== null) {
                  throwError(state, "alias node should not have any properties");
                }
              } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
                hasContent = true;
                if (state.tag === null) {
                  state.tag = "?";
                }
              }
              if (state.anchor !== null) {
                state.anchorMap[state.anchor] = state.result;
              }
            }
          } else if (indentStatus === 0) {
            hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
          }
        }
        if (state.tag === null) {
          if (state.anchor !== null) {
            state.anchorMap[state.anchor] = state.result;
          }
        } else if (state.tag === "?") {
          if (state.result !== null && state.kind !== "scalar") {
            throwError(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');
          }
          for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
            type = state.implicitTypes[typeIndex];
            if (type.resolve(state.result)) {
              state.result = type.construct(state.result);
              state.tag = type.tag;
              if (state.anchor !== null) {
                state.anchorMap[state.anchor] = state.result;
              }
              break;
            }
          }
        } else if (state.tag !== "!") {
          if (_hasOwnProperty.call(state.typeMap[state.kind || "fallback"], state.tag)) {
            type = state.typeMap[state.kind || "fallback"][state.tag];
          } else {
            type = null;
            typeList = state.typeMap.multi[state.kind || "fallback"];
            for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {
              if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
                type = typeList[typeIndex];
                break;
              }
            }
          }
          if (!type) {
            throwError(state, "unknown tag !<" + state.tag + ">");
          }
          if (state.result !== null && type.kind !== state.kind) {
            throwError(state, "unacceptable node kind for !<" + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
          }
          if (!type.resolve(state.result, state.tag)) {
            throwError(state, "cannot resolve a node with !<" + state.tag + "> explicit tag");
          } else {
            state.result = type.construct(state.result, state.tag);
            if (state.anchor !== null) {
              state.anchorMap[state.anchor] = state.result;
            }
          }
        }
        if (state.listener !== null) {
          state.listener("close", state);
        }
        return state.tag !== null || state.anchor !== null || hasContent;
      }
      function readDocument(state) {
        var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch;
        state.version = null;
        state.checkLineBreaks = state.legacy;
        state.tagMap = /* @__PURE__ */ Object.create(null);
        state.anchorMap = /* @__PURE__ */ Object.create(null);
        while ((ch = state.input.charCodeAt(state.position)) !== 0) {
          skipSeparationSpace(state, true, -1);
          ch = state.input.charCodeAt(state.position);
          if (state.lineIndent > 0 || ch !== 37) {
            break;
          }
          hasDirectives = true;
          ch = state.input.charCodeAt(++state.position);
          _position = state.position;
          while (ch !== 0 && !is_WS_OR_EOL(ch)) {
            ch = state.input.charCodeAt(++state.position);
          }
          directiveName = state.input.slice(_position, state.position);
          directiveArgs = [];
          if (directiveName.length < 1) {
            throwError(state, "directive name must not be less than one character in length");
          }
          while (ch !== 0) {
            while (is_WHITE_SPACE(ch)) {
              ch = state.input.charCodeAt(++state.position);
            }
            if (ch === 35) {
              do {
                ch = state.input.charCodeAt(++state.position);
              } while (ch !== 0 && !is_EOL(ch));
              break;
            }
            if (is_EOL(ch)) break;
            _position = state.position;
            while (ch !== 0 && !is_WS_OR_EOL(ch)) {
              ch = state.input.charCodeAt(++state.position);
            }
            directiveArgs.push(state.input.slice(_position, state.position));
          }
          if (ch !== 0) readLineBreak(state);
          if (_hasOwnProperty.call(directiveHandlers, directiveName)) {
            directiveHandlers[directiveName](state, directiveName, directiveArgs);
          } else {
            throwWarning(state, 'unknown document directive "' + directiveName + '"');
          }
        }
        skipSeparationSpace(state, true, -1);
        if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) {
          state.position += 3;
          skipSeparationSpace(state, true, -1);
        } else if (hasDirectives) {
          throwError(state, "directives end mark is expected");
        }
        composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
        skipSeparationSpace(state, true, -1);
        if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
          throwWarning(state, "non-ASCII line breaks are interpreted as content");
        }
        state.documents.push(state.result);
        if (state.position === state.lineStart && testDocumentSeparator(state)) {
          if (state.input.charCodeAt(state.position) === 46) {
            state.position += 3;
            skipSeparationSpace(state, true, -1);
          }
          return;
        }
        if (state.position < state.length - 1) {
          throwError(state, "end of the stream or a document separator is expected");
        } else {
          return;
        }
      }
      function loadDocuments(input, options) {
        input = String(input);
        options = options || {};
        if (input.length !== 0) {
          if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) {
            input += "\n";
          }
          if (input.charCodeAt(0) === 65279) {
            input = input.slice(1);
          }
        }
        var state = new State(input, options);
        var nullpos = input.indexOf("\0");
        if (nullpos !== -1) {
          state.position = nullpos;
          throwError(state, "null byte is not allowed in input");
        }
        state.input += "\0";
        while (state.input.charCodeAt(state.position) === 32) {
          state.lineIndent += 1;
          state.position += 1;
        }
        while (state.position < state.length - 1) {
          readDocument(state);
        }
        return state.documents;
      }
      function loadAll(input, iterator, options) {
        if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") {
          options = iterator;
          iterator = null;
        }
        var documents = loadDocuments(input, options);
        if (typeof iterator !== "function") {
          return documents;
        }
        for (var index = 0, length = documents.length; index < length; index += 1) {
          iterator(documents[index]);
        }
      }
      function load(input, options) {
        var documents = loadDocuments(input, options);
        if (documents.length === 0) {
          return void 0;
        } else if (documents.length === 1) {
          return documents[0];
        }
        throw new YAMLException("expected a single document in the stream, but found more");
      }
      module2.exports.loadAll = loadAll;
      module2.exports.load = load;
    }
  });

  // node_modules/js-yaml/lib/dumper.js
  var require_dumper = __commonJS({
    "node_modules/js-yaml/lib/dumper.js"(exports2, module2) {
      "use strict";
      var common = require_common();
      var YAMLException = require_exception();
      var DEFAULT_SCHEMA = require_default();
      var _toString = Object.prototype.toString;
      var _hasOwnProperty = Object.prototype.hasOwnProperty;
      var CHAR_BOM = 65279;
      var CHAR_TAB = 9;
      var CHAR_LINE_FEED = 10;
      var CHAR_CARRIAGE_RETURN = 13;
      var CHAR_SPACE = 32;
      var CHAR_EXCLAMATION = 33;
      var CHAR_DOUBLE_QUOTE = 34;
      var CHAR_SHARP = 35;
      var CHAR_PERCENT = 37;
      var CHAR_AMPERSAND = 38;
      var CHAR_SINGLE_QUOTE = 39;
      var CHAR_ASTERISK = 42;
      var CHAR_COMMA = 44;
      var CHAR_MINUS = 45;
      var CHAR_COLON = 58;
      var CHAR_EQUALS = 61;
      var CHAR_GREATER_THAN = 62;
      var CHAR_QUESTION = 63;
      var CHAR_COMMERCIAL_AT = 64;
      var CHAR_LEFT_SQUARE_BRACKET = 91;
      var CHAR_RIGHT_SQUARE_BRACKET = 93;
      var CHAR_GRAVE_ACCENT = 96;
      var CHAR_LEFT_CURLY_BRACKET = 123;
      var CHAR_VERTICAL_LINE = 124;
      var CHAR_RIGHT_CURLY_BRACKET = 125;
      var ESCAPE_SEQUENCES = {};
      ESCAPE_SEQUENCES[0] = "\\0";
      ESCAPE_SEQUENCES[7] = "\\a";
      ESCAPE_SEQUENCES[8] = "\\b";
      ESCAPE_SEQUENCES[9] = "\\t";
      ESCAPE_SEQUENCES[10] = "\\n";
      ESCAPE_SEQUENCES[11] = "\\v";
      ESCAPE_SEQUENCES[12] = "\\f";
      ESCAPE_SEQUENCES[13] = "\\r";
      ESCAPE_SEQUENCES[27] = "\\e";
      ESCAPE_SEQUENCES[34] = '\\"';
      ESCAPE_SEQUENCES[92] = "\\\\";
      ESCAPE_SEQUENCES[133] = "\\N";
      ESCAPE_SEQUENCES[160] = "\\_";
      ESCAPE_SEQUENCES[8232] = "\\L";
      ESCAPE_SEQUENCES[8233] = "\\P";
      var DEPRECATED_BOOLEANS_SYNTAX = [
        "y",
        "Y",
        "yes",
        "Yes",
        "YES",
        "on",
        "On",
        "ON",
        "n",
        "N",
        "no",
        "No",
        "NO",
        "off",
        "Off",
        "OFF"
      ];
      var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
      function compileStyleMap(schema, map) {
        var result, keys, index, length, tag, style, type;
        if (map === null) return {};
        result = {};
        keys = Object.keys(map);
        for (index = 0, length = keys.length; index < length; index += 1) {
          tag = keys[index];
          style = String(map[tag]);
          if (tag.slice(0, 2) === "!!") {
            tag = "tag:yaml.org,2002:" + tag.slice(2);
          }
          type = schema.compiledTypeMap["fallback"][tag];
          if (type && _hasOwnProperty.call(type.styleAliases, style)) {
            style = type.styleAliases[style];
          }
          result[tag] = style;
        }
        return result;
      }
      function encodeHex(character) {
        var string, handle, length;
        string = character.toString(16).toUpperCase();
        if (character <= 255) {
          handle = "x";
          length = 2;
        } else if (character <= 65535) {
          handle = "u";
          length = 4;
        } else if (character <= 4294967295) {
          handle = "U";
          length = 8;
        } else {
          throw new YAMLException("code point within a string may not be greater than 0xFFFFFFFF");
        }
        return "\\" + handle + common.repeat("0", length - string.length) + string;
      }
      var QUOTING_TYPE_SINGLE = 1;
      var QUOTING_TYPE_DOUBLE = 2;
      function State(options) {
        this.schema = options["schema"] || DEFAULT_SCHEMA;
        this.indent = Math.max(1, options["indent"] || 2);
        this.noArrayIndent = options["noArrayIndent"] || false;
        this.skipInvalid = options["skipInvalid"] || false;
        this.flowLevel = common.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"];
        this.styleMap = compileStyleMap(this.schema, options["styles"] || null);
        this.sortKeys = options["sortKeys"] || false;
        this.lineWidth = options["lineWidth"] || 80;
        this.noRefs = options["noRefs"] || false;
        this.noCompatMode = options["noCompatMode"] || false;
        this.condenseFlow = options["condenseFlow"] || false;
        this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
        this.forceQuotes = options["forceQuotes"] || false;
        this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null;
        this.implicitTypes = this.schema.compiledImplicit;
        this.explicitTypes = this.schema.compiledExplicit;
        this.tag = null;
        this.result = "";
        this.duplicates = [];
        this.usedDuplicates = null;
      }
      function indentString(string, spaces) {
        var ind = common.repeat(" ", spaces), position = 0, next = -1, result = "", line, length = string.length;
        while (position < length) {
          next = string.indexOf("\n", position);
          if (next === -1) {
            line = string.slice(position);
            position = length;
          } else {
            line = string.slice(position, next + 1);
            position = next + 1;
          }
          if (line.length && line !== "\n") result += ind;
          result += line;
        }
        return result;
      }
      function generateNextLine(state, level) {
        return "\n" + common.repeat(" ", state.indent * level);
      }
      function testImplicitResolving(state, str) {
        var index, length, type;
        for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
          type = state.implicitTypes[index];
          if (type.resolve(str)) {
            return true;
          }
        }
        return false;
      }
      function isWhitespace(c) {
        return c === CHAR_SPACE || c === CHAR_TAB;
      }
      function isPrintable(c) {
        return 32 <= c && c <= 126 || 161 <= c && c <= 55295 && c !== 8232 && c !== 8233 || 57344 <= c && c <= 65533 && c !== CHAR_BOM || 65536 <= c && c <= 1114111;
      }
      function isNsCharOrWhitespace(c) {
        return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
      }
      function isPlainSafe(c, prev, inblock) {
        var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
        var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
        return (
          // ns-plain-safe
          (inblock ? (
            // c = flow-in
            cIsNsCharOrWhitespace
          ) : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar
        );
      }
      function isPlainSafeFirst(c) {
        return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
      }
      function isPlainSafeLast(c) {
        return !isWhitespace(c) && c !== CHAR_COLON;
      }
      function codePointAt(string, pos) {
        var first = string.charCodeAt(pos), second;
        if (first >= 55296 && first <= 56319 && pos + 1 < string.length) {
          second = string.charCodeAt(pos + 1);
          if (second >= 56320 && second <= 57343) {
            return (first - 55296) * 1024 + second - 56320 + 65536;
          }
        }
        return first;
      }
      function needIndentIndicator(string) {
        var leadingSpaceRe = /^\n* /;
        return leadingSpaceRe.test(string);
      }
      var STYLE_PLAIN = 1;
      var STYLE_SINGLE = 2;
      var STYLE_LITERAL = 3;
      var STYLE_FOLDED = 4;
      var STYLE_DOUBLE = 5;
      function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) {
        var i;
        var char = 0;
        var prevChar = null;
        var hasLineBreak = false;
        var hasFoldableLine = false;
        var shouldTrackWidth = lineWidth !== -1;
        var previousLineBreak = -1;
        var plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
        if (singleLineOnly || forceQuotes) {
          for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
            char = codePointAt(string, i);
            if (!isPrintable(char)) {
              return STYLE_DOUBLE;
            }
            plain = plain && isPlainSafe(char, prevChar, inblock);
            prevChar = char;
          }
        } else {
          for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
            char = codePointAt(string, i);
            if (char === CHAR_LINE_FEED) {
              hasLineBreak = true;
              if (shouldTrackWidth) {
                hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented.
                i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ";
                previousLineBreak = i;
              }
            } else if (!isPrintable(char)) {
              return STYLE_DOUBLE;
            }
            plain = plain && isPlainSafe(char, prevChar, inblock);
            prevChar = char;
          }
          hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");
        }
        if (!hasLineBreak && !hasFoldableLine) {
          if (plain && !forceQuotes && !testAmbiguousType(string)) {
            return STYLE_PLAIN;
          }
          return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
        }
        if (indentPerLevel > 9 && needIndentIndicator(string)) {
          return STYLE_DOUBLE;
        }
        if (!forceQuotes) {
          return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
        }
        return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
      }
      function writeScalar(state, string, level, iskey, inblock) {
        state.dump = (function() {
          if (string.length === 0) {
            return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
          }
          if (!state.noCompatMode) {
            if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
              return state.quotingType === QUOTING_TYPE_DOUBLE ? '"' + string + '"' : "'" + string + "'";
            }
          }
          var indent = state.indent * Math.max(1, level);
          var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
          var singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel;
          function testAmbiguity(string2) {
            return testImplicitResolving(state, string2);
          }
          switch (chooseScalarStyle(
            string,
            singleLineOnly,
            state.indent,
            lineWidth,
            testAmbiguity,
            state.quotingType,
            state.forceQuotes && !iskey,
            inblock
          )) {
            case STYLE_PLAIN:
              return string;
            case STYLE_SINGLE:
              return "'" + string.replace(/'/g, "''") + "'";
            case STYLE_LITERAL:
              return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));
            case STYLE_FOLDED:
              return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
            case STYLE_DOUBLE:
              return '"' + escapeString(string, lineWidth) + '"';
            default:
              throw new YAMLException("impossible error: invalid scalar style");
          }
        })();
      }
      function blockHeader(string, indentPerLevel) {
        var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : "";
        var clip = string[string.length - 1] === "\n";
        var keep = clip && (string[string.length - 2] === "\n" || string === "\n");
        var chomp = keep ? "+" : clip ? "" : "-";
        return indentIndicator + chomp + "\n";
      }
      function dropEndingNewline(string) {
        return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
      }
      function foldString(string, width) {
        var lineRe = /(\n+)([^\n]*)/g;
        var result = (function() {
          var nextLF = string.indexOf("\n");
          nextLF = nextLF !== -1 ? nextLF : string.length;
          lineRe.lastIndex = nextLF;
          return foldLine(string.slice(0, nextLF), width);
        })();
        var prevMoreIndented = string[0] === "\n" || string[0] === " ";
        var moreIndented;
        var match;
        while (match = lineRe.exec(string)) {
          var prefix = match[1], line = match[2];
          moreIndented = line[0] === " ";
          result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
          prevMoreIndented = moreIndented;
        }
        return result;
      }
      function foldLine(line, width) {
        if (line === "" || line[0] === " ") return line;
        var breakRe = / [^ ]/g;
        var match;
        var start = 0, end, curr = 0, next = 0;
        var result = "";
        while (match = breakRe.exec(line)) {
          next = match.index;
          if (next - start > width) {
            end = curr > start ? curr : next;
            result += "\n" + line.slice(start, end);
            start = end + 1;
          }
          curr = next;
        }
        result += "\n";
        if (line.length - start > width && curr > start) {
          result += line.slice(start, curr) + "\n" + line.slice(curr + 1);
        } else {
          result += line.slice(start);
        }
        return result.slice(1);
      }
      function escapeString(string) {
        var result = "";
        var char = 0;
        var escapeSeq;
        for (var i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
          char = codePointAt(string, i);
          escapeSeq = ESCAPE_SEQUENCES[char];
          if (!escapeSeq && isPrintable(char)) {
            result += string[i];
            if (char >= 65536) result += string[i + 1];
          } else {
            result += escapeSeq || encodeHex(char);
          }
        }
        return result;
      }
      function writeFlowSequence(state, level, object) {
        var _result = "", _tag = state.tag, index, length, value;
        for (index = 0, length = object.length; index < length; index += 1) {
          value = object[index];
          if (state.replacer) {
            value = state.replacer.call(object, String(index), value);
          }
          if (writeNode(state, level, value, false, false) || typeof value === "undefined" && writeNode(state, level, null, false, false)) {
            if (_result !== "") _result += "," + (!state.condenseFlow ? " " : "");
            _result += state.dump;
          }
        }
        state.tag = _tag;
        state.dump = "[" + _result + "]";
      }
      function writeBlockSequence(state, level, object, compact) {
        var _result = "", _tag = state.tag, index, length, value;
        for (index = 0, length = object.length; index < length; index += 1) {
          value = object[index];
          if (state.replacer) {
            value = state.replacer.call(object, String(index), value);
          }
          if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true)) {
            if (!compact || _result !== "") {
              _result += generateNextLine(state, level);
            }
            if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
              _result += "-";
            } else {
              _result += "- ";
            }
            _result += state.dump;
          }
        }
        state.tag = _tag;
        state.dump = _result || "[]";
      }
      function writeFlowMapping(state, level, object) {
        var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, pairBuffer;
        for (index = 0, length = objectKeyList.length; index < length; index += 1) {
          pairBuffer = "";
          if (_result !== "") pairBuffer += ", ";
          if (state.condenseFlow) pairBuffer += '"';
          objectKey = objectKeyList[index];
          objectValue = object[objectKey];
          if (state.replacer) {
            objectValue = state.replacer.call(object, objectKey, objectValue);
          }
          if (!writeNode(state, level, objectKey, false, false)) {
            continue;
          }
          if (state.dump.length > 1024) pairBuffer += "? ";
          pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " ");
          if (!writeNode(state, level, objectValue, false, false)) {
            continue;
          }
          pairBuffer += state.dump;
          _result += pairBuffer;
        }
        state.tag = _tag;
        state.dump = "{" + _result + "}";
      }
      function writeBlockMapping(state, level, object, compact) {
        var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, explicitPair, pairBuffer;
        if (state.sortKeys === true) {
          objectKeyList.sort();
        } else if (typeof state.sortKeys === "function") {
          objectKeyList.sort(state.sortKeys);
        } else if (state.sortKeys) {
          throw new YAMLException("sortKeys must be a boolean or a function");
        }
        for (index = 0, length = objectKeyList.length; index < length; index += 1) {
          pairBuffer = "";
          if (!compact || _result !== "") {
            pairBuffer += generateNextLine(state, level);
          }
          objectKey = objectKeyList[index];
          objectValue = object[objectKey];
          if (state.replacer) {
            objectValue = state.replacer.call(object, objectKey, objectValue);
          }
          if (!writeNode(state, level + 1, objectKey, true, true, true)) {
            continue;
          }
          explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024;
          if (explicitPair) {
            if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
              pairBuffer += "?";
            } else {
              pairBuffer += "? ";
            }
          }
          pairBuffer += state.dump;
          if (explicitPair) {
            pairBuffer += generateNextLine(state, level);
          }
          if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
            continue;
          }
          if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
            pairBuffer += ":";
          } else {
            pairBuffer += ": ";
          }
          pairBuffer += state.dump;
          _result += pairBuffer;
        }
        state.tag = _tag;
        state.dump = _result || "{}";
      }
      function detectType(state, object, explicit) {
        var _result, typeList, index, length, type, style;
        typeList = explicit ? state.explicitTypes : state.implicitTypes;
        for (index = 0, length = typeList.length; index < length; index += 1) {
          type = typeList[index];
          if ((type.instanceOf || type.predicate) && (!type.instanceOf || typeof object === "object" && object instanceof type.instanceOf) && (!type.predicate || type.predicate(object))) {
            if (explicit) {
              if (type.multi && type.representName) {
                state.tag = type.representName(object);
              } else {
                state.tag = type.tag;
              }
            } else {
              state.tag = "?";
            }
            if (type.represent) {
              style = state.styleMap[type.tag] || type.defaultStyle;
              if (_toString.call(type.represent) === "[object Function]") {
                _result = type.represent(object, style);
              } else if (_hasOwnProperty.call(type.represent, style)) {
                _result = type.represent[style](object, style);
              } else {
                throw new YAMLException("!<" + type.tag + '> tag resolver accepts not "' + style + '" style');
              }
              state.dump = _result;
            }
            return true;
          }
        }
        return false;
      }
      function writeNode(state, level, object, block, compact, iskey, isblockseq) {
        state.tag = null;
        state.dump = object;
        if (!detectType(state, object, false)) {
          detectType(state, object, true);
        }
        var type = _toString.call(state.dump);
        var inblock = block;
        var tagStr;
        if (block) {
          block = state.flowLevel < 0 || state.flowLevel > level;
        }
        var objectOrArray = type === "[object Object]" || type === "[object Array]", duplicateIndex, duplicate;
        if (objectOrArray) {
          duplicateIndex = state.duplicates.indexOf(object);
          duplicate = duplicateIndex !== -1;
        }
        if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) {
          compact = false;
        }
        if (duplicate && state.usedDuplicates[duplicateIndex]) {
          state.dump = "*ref_" + duplicateIndex;
        } else {
          if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
            state.usedDuplicates[duplicateIndex] = true;
          }
          if (type === "[object Object]") {
            if (block && Object.keys(state.dump).length !== 0) {
              writeBlockMapping(state, level, state.dump, compact);
              if (duplicate) {
                state.dump = "&ref_" + duplicateIndex + state.dump;
              }
            } else {
              writeFlowMapping(state, level, state.dump);
              if (duplicate) {
                state.dump = "&ref_" + duplicateIndex + " " + state.dump;
              }
            }
          } else if (type === "[object Array]") {
            if (block && state.dump.length !== 0) {
              if (state.noArrayIndent && !isblockseq && level > 0) {
                writeBlockSequence(state, level - 1, state.dump, compact);
              } else {
                writeBlockSequence(state, level, state.dump, compact);
              }
              if (duplicate) {
                state.dump = "&ref_" + duplicateIndex + state.dump;
              }
            } else {
              writeFlowSequence(state, level, state.dump);
              if (duplicate) {
                state.dump = "&ref_" + duplicateIndex + " " + state.dump;
              }
            }
          } else if (type === "[object String]") {
            if (state.tag !== "?") {
              writeScalar(state, state.dump, level, iskey, inblock);
            }
          } else if (type === "[object Undefined]") {
            return false;
          } else {
            if (state.skipInvalid) return false;
            throw new YAMLException("unacceptable kind of an object to dump " + type);
          }
          if (state.tag !== null && state.tag !== "?") {
            tagStr = encodeURI(
              state.tag[0] === "!" ? state.tag.slice(1) : state.tag
            ).replace(/!/g, "%21");
            if (state.tag[0] === "!") {
              tagStr = "!" + tagStr;
            } else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") {
              tagStr = "!!" + tagStr.slice(18);
            } else {
              tagStr = "!<" + tagStr + ">";
            }
            state.dump = tagStr + " " + state.dump;
          }
        }
        return true;
      }
      function getDuplicateReferences(object, state) {
        var objects = [], duplicatesIndexes = [], index, length;
        inspectNode(object, objects, duplicatesIndexes);
        for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
          state.duplicates.push(objects[duplicatesIndexes[index]]);
        }
        state.usedDuplicates = new Array(length);
      }
      function inspectNode(object, objects, duplicatesIndexes) {
        var objectKeyList, index, length;
        if (object !== null && typeof object === "object") {
          index = objects.indexOf(object);
          if (index !== -1) {
            if (duplicatesIndexes.indexOf(index) === -1) {
              duplicatesIndexes.push(index);
            }
          } else {
            objects.push(object);
            if (Array.isArray(object)) {
              for (index = 0, length = object.length; index < length; index += 1) {
                inspectNode(object[index], objects, duplicatesIndexes);
              }
            } else {
              objectKeyList = Object.keys(object);
              for (index = 0, length = objectKeyList.length; index < length; index += 1) {
                inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
              }
            }
          }
        }
      }
      function dump(input, options) {
        options = options || {};
        var state = new State(options);
        if (!state.noRefs) getDuplicateReferences(input, state);
        var value = input;
        if (state.replacer) {
          value = state.replacer.call({ "": value }, "", value);
        }
        if (writeNode(state, 0, value, true, true)) return state.dump + "\n";
        return "";
      }
      module2.exports.dump = dump;
    }
  });

  // node_modules/js-yaml/index.js
  var require_js_yaml = __commonJS({
    "node_modules/js-yaml/index.js"(exports2, module2) {
      "use strict";
      var loader = require_loader();
      var dumper = require_dumper();
      function renamed(from, to) {
        return function() {
          throw new Error("Function yaml." + from + " is removed in js-yaml 4. Use yaml." + to + " instead, which is now safe by default.");
        };
      }
      module2.exports.Type = require_type();
      module2.exports.Schema = require_schema();
      module2.exports.FAILSAFE_SCHEMA = require_failsafe();
      module2.exports.JSON_SCHEMA = require_json2();
      module2.exports.CORE_SCHEMA = require_core();
      module2.exports.DEFAULT_SCHEMA = require_default();
      module2.exports.load = loader.load;
      module2.exports.loadAll = loader.loadAll;
      module2.exports.dump = dumper.dump;
      module2.exports.YAMLException = require_exception();
      module2.exports.types = {
        binary: require_binary(),
        float: require_float(),
        map: require_map(),
        null: require_null(),
        pairs: require_pairs(),
        set: require_set(),
        timestamp: require_timestamp(),
        bool: require_bool(),
        int: require_int(),
        merge: require_merge(),
        omap: require_omap(),
        seq: require_seq(),
        str: require_str()
      };
      module2.exports.safeLoad = renamed("safeLoad", "load");
      module2.exports.safeLoadAll = renamed("safeLoadAll", "loadAll");
      module2.exports.safeDump = renamed("safeDump", "dump");
    }
  });

  // modules/std/data/yaml.js
  var require_yaml = __commonJS({
    "modules/std/data/yaml.js"(exports2, module2) {
      "use strict";
      var yaml = require_js_yaml();
      var { Pair, PairList, ZuzuBag } = require_collections();
      var { BinaryString: BinaryString2 } = require_runtime_helpers();
      var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
      var utf8Encoder = new TextEncoder();
      function isPlainObject2(value) {
        return value != null && typeof value === "object" && !Array.isArray(value) && !(value instanceof PairList) && !(value instanceof ZuzuBag) && Object.prototype.toString.call(value) !== "[object Set]";
      }
      function isPath(value) {
        return value && value.constructor && value.constructor.name === "Path" && typeof value.slurp === "function" && typeof value.spew === "function";
      }
      function normalizeValue(value) {
        if (value instanceof PairList) {
          const out = {};
          for (const [key, inner] of value.list) {
            if (!Object.prototype.hasOwnProperty.call(out, String(key))) {
              out[String(key)] = normalizeValue(inner);
            }
          }
          return out;
        }
        if (value && Array.isArray(value.items) && typeof value.to_Array === "function") {
          return normalizeValue(
            value.to_Array().slice().sort((left, right) => String(left).localeCompare(String(right)))
          );
        }
        if (value && value.constructor && value.constructor.name === "Set" && typeof value.to_Array === "function") {
          return normalizeValue(
            value.to_Array().slice().sort((left, right) => String(left).localeCompare(String(right)))
          );
        }
        if (value && value.constructor && value.constructor.name === "ZuzuBag" && typeof value.to_Array === "function") {
          return normalizeValue(
            value.to_Array().slice().sort((left, right) => String(left).localeCompare(String(right)))
          );
        }
        if (value && value.constructor && ["Set", "ZuzuBag", "PairList"].includes(value.constructor.name) && typeof value.to_Array === "function") {
          return normalizeValue(value.to_Array());
        }
        if (Array.isArray(value)) {
          return value.map((item) => normalizeValue(item));
        }
        if (value && value.constructor && value.constructor.name === "Object") {
          const out = {};
          for (const key of Object.keys(value).sort()) {
            out[key] = normalizeValue(value[key]);
          }
          return out;
        }
        return value;
      }
      function decorateValue(value) {
        if (Array.isArray(value)) {
          for (let i = 0; i < value.length; i++) {
            value[i] = decorateValue(value[i]);
          }
          return value;
        }
        if (!isPlainObject2(value)) {
          return value;
        }
        const sortedKeys = () => Object.keys(value).sort();
        for (const [name2, fn2] of [
          ["length", function _length() {
            return Object.keys(this).length;
          }],
          ["count", function _count() {
            return Object.keys(this).length;
          }],
          ["empty", function _empty() {
            return Object.keys(this).length === 0 ? 1 : 0;
          }],
          ["keys", function _keys() {
            return new Set(sortedKeys());
          }],
          ["values", function _values() {
            return new ZuzuBag(sortedKeys().map((key) => this[key]));
          }],
          [
            "enumerate",
            function _enumerate() {
              return new ZuzuBag(
                sortedKeys().map(
                  (key) => new Pair({ pair: [key, this[key]] })
                )
              );
            }
          ],
          ["has", function _has(key) {
            return Object.prototype.hasOwnProperty.call(this, String(key)) ? 1 : 0;
          }],
          ["contains", function _contains(key) {
            return this.has(key);
          }],
          ["exists", function _exists(key) {
            return this.has(key);
          }],
          ["defined", function _defined(key) {
            return this.has(key) && this[String(key)] != null ? 1 : 0;
          }],
          ["get", function _get(key, fallback = null) {
            return this.has(key) ? this[String(key)] : fallback;
          }],
          ["add", function _add(key, inner) {
            this[String(key)] = inner;
            return this;
          }],
          ["set", function _set(key, inner) {
            return this.add(key, inner);
          }],
          [
            "kv",
            function _kv() {
              const out = [];
              for (const key of sortedKeys()) {
                out.push(key, this[key]);
              }
              return out;
            }
          ],
          ["sorted_keys", function _sorted_keys() {
            return sortedKeys();
          }],
          [
            "to_Array",
            function _to_array() {
              return sortedKeys().map(
                (key) => new Pair({ pair: [key, this[key]] })
              );
            }
          ],
          ["to_Iterator", function _to_iterator() {
            return sortedKeys()[Symbol.iterator]();
          }],
          [
            "for_each_key",
            function _for_each_key(fn3) {
              for (const key of sortedKeys()) {
                fn3(key);
              }
              return this;
            }
          ],
          [
            "for_each_value",
            function _for_each_value(fn3) {
              for (const key of sortedKeys()) {
                fn3(this[key]);
              }
              return this;
            }
          ],
          [
            "for_each_pair",
            function _for_each_pair(fn3) {
              for (const key of sortedKeys()) {
                fn3(new Pair({ pair: [key, this[key]] }));
              }
              return this;
            }
          ],
          [
            "remove",
            function _remove(key) {
              delete this[String(key)];
              return this;
            }
          ],
          [
            "clear",
            function _clear() {
              for (const key of Object.keys(this)) {
                delete this[key];
              }
              return this;
            }
          ]
        ]) {
          if (!Object.prototype.hasOwnProperty.call(value, name2)) {
            Object.defineProperty(value, name2, {
              value: fn2,
              enumerable: false,
              configurable: true,
              writable: true
            });
          }
        }
        for (const key of Object.keys(value)) {
          value[key] = decorateValue(value[key]);
        }
        return value;
      }
      var YAML = class {
        constructor(options = {}) {
          const merged = options instanceof PairList ? Object.fromEntries(options.list.map(([key, value]) => [String(key), value])) : options;
          this.pretty = !!merged.pretty;
          this.canonical = !!merged.canonical;
        }
        encode(value) {
          const text = yaml.dump(normalizeValue(value), {
            lineWidth: -1,
            noArrayIndent: true,
            noRefs: true,
            sortKeys: true
          });
          return this.pretty ? text : text.replace(/\n$/u, "");
        }
        encode_binarystring(value) {
          return new BinaryString2(utf8Encoder.encode(this.encode(value)));
        }
        decode(text) {
          const value = yaml.load(String(text));
          return value === void 0 ? null : decorateValue(value);
        }
        decode_binarystring(raw) {
          if (!(raw instanceof BinaryString2)) {
            throw new Error("TypeException: YAML.decode_binarystring expects BinaryString");
          }
          return this.decode(utf8Decoder.decode(raw.bytes));
        }
        dump(pathValue, value) {
          if (!isPath(pathValue)) {
            throw new Error("TypeException: YAML.dump expects Path as first argument");
          }
          pathValue.spew(this.encode_binarystring(value));
          return pathValue;
        }
        load(pathValue) {
          if (!isPath(pathValue)) {
            throw new Error("TypeException: YAML.load expects Path as first argument");
          }
          return this.decode_binarystring(pathValue.slurp());
        }
      };
      module2.exports = {
        YAML
      };
    }
  });

  // modules/std/data/csv.js
  var require_csv = __commonJS({
    "modules/std/data/csv.js"(exports2, module2) {
      "use strict";
      var { PairList } = require_collections();
      var { BinaryString: BinaryString2 } = require_runtime_helpers();
      var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
      var utf8Encoder = new TextEncoder();
      var runtimePolicy2 = {
        deny_fs: false,
        deny_db: false,
        host_name: "node"
      };
      var nodeFs;
      var nodeFsLoaded = false;
      var PathClass;
      var PathClassLoaded = false;
      var DatabaseHandleClass;
      var DatabaseHandleClassLoaded = false;
      function _safeRequire(moduleName) {
        if (typeof __require !== "function") {
          return null;
        }
        try {
          return __require(moduleName);
        } catch (_err) {
          return null;
        }
      }
      function _nodeFs() {
        if (nodeFsLoaded) {
          return nodeFs;
        }
        nodeFsLoaded = true;
        nodeFs = _safeRequire("node:fs");
        return nodeFs;
      }
      function _PathClass() {
        if (PathClassLoaded) {
          return PathClass;
        }
        PathClassLoaded = true;
        const loaded = _safeRequire("../io.js");
        PathClass = loaded && loaded.Path ? loaded.Path : null;
        return PathClass;
      }
      function _DatabaseHandleClass() {
        if (DatabaseHandleClassLoaded) {
          return DatabaseHandleClass;
        }
        DatabaseHandleClassLoaded = true;
        const loaded = _safeRequire("../db.js");
        DatabaseHandleClass = loaded && loaded.DatabaseHandle ? loaded.DatabaseHandle : null;
        return DatabaseHandleClass;
      }
      function assertCapability(capability, message) {
        if (runtimePolicy2[`deny_${capability}`]) {
          throw new Error(message);
        }
      }
      function bool(value) {
        return value ? 1 : 0;
      }
      function isPlainObject2(value) {
        return value != null && typeof value === "object" && !Array.isArray(value) && !(value instanceof PairList);
      }
      function isPath(value) {
        if (value == null || typeof value !== "object") {
          return false;
        }
        const Path = _PathClass();
        return Path ? value instanceof Path : false;
      }
      function isDbHandle(value) {
        if (value == null || typeof value !== "object") {
          return false;
        }
        const DatabaseHandle = _DatabaseHandleClass();
        return DatabaseHandle ? value instanceof DatabaseHandle : false;
      }
      function optionsObject(value) {
        if (value instanceof PairList) {
          return Object.fromEntries(
            value.list.map(([key, inner]) => [String(key), inner])
          );
        }
        if (isPlainObject2(value)) {
          return { ...value };
        }
        return {};
      }
      function arrayValue(value) {
        if (Array.isArray(value)) {
          return value.slice();
        }
        return [];
      }
      function objectValue(value) {
        return isPlainObject2(value) ? { ...value } : {};
      }
      function normalizeConfig(...parts) {
        const out = {};
        for (const part of parts) {
          Object.assign(out, optionsObject(part));
        }
        return out;
      }
      function runtimeConfig(...parts) {
        const config = normalizeConfig(...parts);
        for (const key of ["columns", "required_columns", "sniff_candidates"]) {
          if (key in config) {
            config[key] = arrayValue(config[key]);
          }
        }
        for (const key of [
          "defaults",
          "rename_headers",
          "column_map",
          "column_types",
          "types",
          "parsers",
          "formatters"
        ]) {
          if (key in config) {
            config[key] = objectValue(config[key]);
          }
        }
        return config;
      }
      function columnNamesFromConfig(config) {
        if (Array.isArray(config.columns)) {
          return config.columns.map((name2) => String(name2 ?? ""));
        }
        return null;
      }
      function defaultColumnsForRow(row) {
        const out = [];
        for (let i = 0; i < row.length; i++) {
          out.push(`column${i + 1}`);
        }
        return out;
      }
      function normalizeFieldValue(value, config) {
        if (value === "" && config.blank_is_undef) {
          return null;
        }
        if (value === "" && config.empty_is_undef) {
          return null;
        }
        return value;
      }
      function headerName(raw, config) {
        let value = String(raw ?? "");
        if (config.trim_headers) {
          value = value.trim();
        }
        if (config.lowercase_headers) {
          value = value.toLowerCase();
        }
        if (config.rename_headers && Object.prototype.hasOwnProperty.call(config.rename_headers, value)) {
          value = String(config.rename_headers[value]);
        }
        return value;
      }
      function normalizeHeaders(headers, config) {
        if (!Array.isArray(headers)) {
          return [];
        }
        const seen = /* @__PURE__ */ new Map();
        const out = [];
        const policy = String(config.duplicate_headers || "overwrite").toLowerCase();
        for (const raw of headers) {
          let name2 = headerName(raw, config);
          if (seen.has(name2)) {
            if (policy === "error") {
              throw new Error(`Duplicate CSV header '${name2}'`);
            }
            if (policy === "suffix") {
              const next = seen.get(name2) + 1;
              seen.set(name2, next);
              name2 = `${name2}_${next}`;
            } else {
              seen.set(name2, seen.get(name2) + 1);
            }
          } else {
            seen.set(name2, 1);
          }
          out.push(name2);
        }
        return out;
      }
      function requireColumns(headers, config) {
        const required = arrayValue(config.required_columns);
        if (required.length === 0) {
          return;
        }
        const have = new Set(headers || []);
        for (const name2 of required) {
          if (!have.has(name2)) {
            throw new Error(`Required CSV column '${name2}' missing`);
          }
        }
      }
      function typeForColumn(config, headers, index) {
        const types = config.types;
        if (Array.isArray(types)) {
          return types[index];
        }
        if (isPlainObject2(types) && Array.isArray(headers)) {
          return types[headers[index]];
        }
        return void 0;
      }
      function coerceScalar(value, type) {
        if (type == null) {
          return value;
        }
        const name2 = String(type).toLowerCase();
        if (name2 === "null") {
          return null;
        }
        if (value == null) {
          return name2 === "string" ? "" : null;
        }
        if (name2 === "integer" || name2 === "int") {
          return parseInt(String(value), 10) || 0;
        }
        if (["number", "float", "real"].includes(name2)) {
          return Number(value) || 0;
        }
        if (name2 === "boolean" || name2 === "bool") {
          const text = String(value).toLowerCase();
          if (/^(1|true|yes|on)$/u.test(text)) {
            return 1;
          }
          if (/^(0|false|no|off)?$/u.test(text)) {
            return 0;
          }
          return bool(value);
        }
        return String(value);
      }
      function applyRowRules(row, headers, config, state = {}) {
        const working = row.slice();
        if (Array.isArray(headers)) {
          const expected = headers.length;
          const actual = working.length;
          const ragged = String(config.ragged || "allow").toLowerCase();
          if (actual < expected) {
            if (ragged === "fill") {
              while (working.length < expected) {
                working.push(config.fill_value ?? null);
              }
            } else if (ragged === "error") {
              throw new Error(`CSV row has too few fields at line ${state.line_number ?? "?"}`);
            }
          } else if (actual > expected) {
            if (ragged === "truncate") {
              working.length = expected;
            } else if (ragged === "error") {
              throw new Error(`CSV row has too many fields at line ${state.line_number ?? "?"}`);
            }
          }
        }
        for (let i = 0; i < working.length; i++) {
          working[i] = coerceScalar(
            normalizeFieldValue(working[i], config),
            typeForColumn(config, headers, i)
          );
        }
        if (Array.isArray(headers)) {
          const out = {};
          for (let i = 0; i < headers.length; i++) {
            out[headers[i]] = working[i];
          }
          for (const [key, value] of Object.entries(objectValue(config.defaults))) {
            if (out[key] == null || out[key] === "") {
              out[key] = value;
            }
          }
          if (String(config.unknown_columns || "keep").toLowerCase() === "ignore") {
            const allowed = new Set(headers);
            for (const key of Object.keys(out)) {
              if (!allowed.has(key)) {
                delete out[key];
              }
            }
          }
          return out;
        }
        return working;
      }
      var UnterminatedQuoteError = class extends Error {
      };
      function parseRecord(record, config) {
        const sep = String(config.sep_char ?? ",");
        const quote = String(config.quote_char ?? '"');
        const escape = String(config.escape_char ?? quote);
        const allowWhitespace = !!config.allow_whitespace;
        const row = [];
        let field = "";
        let inQuotes = false;
        let afterQuote = false;
        for (let i = 0; i < record.length; i++) {
          const ch = record[i];
          if (inQuotes) {
            if (ch === quote) {
              if (escape === quote && record[i + 1] === quote) {
                field += quote;
                i++;
              } else {
                inQuotes = false;
                afterQuote = true;
              }
              continue;
            }
            if (escape !== quote && ch === escape && i + 1 < record.length) {
              field += record[i + 1];
              i++;
              continue;
            }
            field += ch;
            continue;
          }
          if (afterQuote) {
            if (ch === sep) {
              row.push(normalizeFieldValue(field, config));
              field = "";
              afterQuote = false;
              continue;
            }
            if (ch === "\n") {
              row.push(normalizeFieldValue(field, config));
              return row;
            }
            if (ch === "\r") {
              continue;
            }
            if (allowWhitespace && /\s/u.test(ch)) {
              continue;
            }
            throw new Error(`unexpected trailing text after closing quote near column ${row.length + 1}`);
          }
          if (ch === sep) {
            row.push(normalizeFieldValue(field, config));
            field = "";
            continue;
          }
          if (ch === quote && field === "") {
            inQuotes = true;
            continue;
          }
          if (ch === "\n") {
            row.push(normalizeFieldValue(field, config));
            return row;
          }
          if (ch === "\r") {
            continue;
          }
          field += ch;
        }
        if (inQuotes) {
          throw new UnterminatedQuoteError("unterminated quoted field");
        }
        row.push(normalizeFieldValue(field, config));
        return row;
      }
      function csvErrorDetail(error, state = {}) {
        const parts = [];
        if (state.line_number != null) {
          parts.push(`line ${state.line_number}`);
        }
        if (state.column_number != null) {
          parts.push(`column ${state.column_number}`);
        }
        if (state.raw_line != null) {
          parts.push(`row ${state.raw_line}`);
        }
        return {
          message: parts.length > 0 ? `${error.message} (${parts.join(", ")})` : error.message,
          line_number: state.line_number ?? null,
          column_number: state.column_number ?? null,
          raw_line: state.raw_line ?? null
        };
      }
      function sourceLinesFromText(text) {
        const source = String(text ?? "");
        let index = 0;
        return function nextLine() {
          if (index >= source.length) {
            return null;
          }
          let end = source.indexOf("\n", index);
          if (end === -1) {
            end = source.length;
          } else {
            end += 1;
          }
          const line = source.slice(index, end);
          index = end;
          return line;
        };
      }
      var FileLineSource = class {
        constructor(target) {
          const fs = _nodeFs();
          if (!fs) {
            throw new Error("CSV file access requires filesystem support");
          }
          this.fd = fs.openSync(target.to_String(), "r");
          this.buffer = "";
          this.eof = false;
        }
        nextLine() {
          const fs = _nodeFs();
          while (true) {
            const idx = this.buffer.indexOf("\n");
            if (idx >= 0) {
              const line = this.buffer.slice(0, idx + 1);
              this.buffer = this.buffer.slice(idx + 1);
              return line;
            }
            if (this.eof) {
              if (this.buffer === "") {
                return null;
              }
              const tail = this.buffer;
              this.buffer = "";
              return tail;
            }
            const chunk = Buffer.allocUnsafe(8192);
            const bytesRead = fs.readSync(this.fd, chunk, 0, chunk.length, null);
            if (bytesRead === 0) {
              this.eof = true;
            } else {
              this.buffer += chunk.toString("utf8", 0, bytesRead);
            }
          }
        }
        close() {
          if (this.fd != null) {
            const fs = _nodeFs();
            fs.closeSync(this.fd);
            this.fd = null;
          }
        }
      };
      var CSVReader = class {
        constructor(target, options = {}) {
          if (!isPath(target)) {
            throw new Error("TypeException: CSV.open expects Path as first argument");
          }
          this.config = runtimeConfig(options);
          this.source = new FileLineSource(target);
          this.headersList = columnNamesFromConfig(this.config);
          this.mode = this.headersList ? "dict" : "array";
          this.lineNumberValue = 0;
          this.rowNumberValue = 0;
          this.errorsList = [];
          this.recordBuffer = "";
          this.recordStartLine = null;
          this.skipRemaining = Number(this.config.skip_lines || 0);
          this.closed = false;
          if (!this.headersList && this.config.headers) {
            const headerRow = this._readNextArray(true);
            this.headersList = normalizeHeaders(headerRow || [], this.config);
            requireColumns(this.headersList, this.config);
            this.mode = "dict";
          } else if (this.headersList) {
            requireColumns(this.headersList, this.config);
          }
        }
        _state() {
          return {
            line_number: this.recordStartLine ?? this.lineNumberValue,
            row_number: this.rowNumberValue,
            raw_line: this.recordBuffer
          };
        }
        _nextPhysicalLine() {
          const line = this.source.nextLine();
          if (line != null) {
            this.lineNumberValue++;
          }
          return line;
        }
        _readNextArray(internal = false) {
          while (true) {
            const line = this._nextPhysicalLine();
            if (line == null) {
              if (this.recordBuffer === "") {
                return null;
              }
              try {
                const finalRow = parseRecord(this.recordBuffer, this.config);
                this.recordBuffer = "";
                return finalRow;
              } catch (error) {
                if (error instanceof UnterminatedQuoteError) {
                  const detail = csvErrorDetail(error, this._state());
                  this.errorsList.push(detail);
                  if (internal || String(this.config.on_error || "die").toLowerCase() !== "collect") {
                    throw new Error(detail.message);
                  }
                  this.recordBuffer = "";
                  return null;
                }
                throw error;
              }
            }
            if (this.recordBuffer === "") {
              if (this.skipRemaining > 0) {
                this.skipRemaining--;
                continue;
              }
              if (this.config.comment_char && line.startsWith(String(this.config.comment_char))) {
                continue;
              }
              if (this.config.skip_empty_rows && /^\s*$/u.test(line)) {
                continue;
              }
              this.recordStartLine = this.lineNumberValue;
            }
            this.recordBuffer += line;
            try {
              const row = parseRecord(this.recordBuffer, this.config);
              this.recordBuffer = "";
              return row;
            } catch (error) {
              if (error instanceof UnterminatedQuoteError) {
                continue;
              }
              const detail = csvErrorDetail(error, this._state());
              this.errorsList.push(detail);
              this.recordBuffer = "";
              if (internal || String(this.config.on_error || "die").toLowerCase() !== "collect") {
                throw new Error(detail.message);
              }
            }
          }
        }
        next_array() {
          while (true) {
            const row = this._readNextArray(false);
            if (row == null) {
              return null;
            }
            const result = applyRowRules(
              row,
              this.headersList,
              this.config,
              {
                line_number: this.recordStartLine,
                row_number: this.rowNumberValue + 1,
                raw_line: this.recordBuffer
              }
            );
            this.rowNumberValue++;
            if (Array.isArray(result)) {
              return result;
            }
            return (this.headersList || []).map((name2) => result[name2]);
          }
        }
        next_dict() {
          if (!Array.isArray(this.headersList) || this.headersList.length === 0) {
            throw new Error("CSVReader.next_dict requires headers or columns");
          }
          const row = this._readNextArray(false);
          if (row == null) {
            return null;
          }
          this.rowNumberValue++;
          const result = applyRowRules(
            row,
            this.headersList,
            this.config,
            {
              line_number: this.recordStartLine,
              row_number: this.rowNumberValue,
              raw_line: this.recordBuffer
            }
          );
          return Array.isArray(result) ? Object.fromEntries(this.headersList.map((name2, index) => [name2, result[index]])) : result;
        }
        next() {
          return this.mode === "dict" ? this.next_dict() : this.next_array();
        }
        all_array() {
          const out = [];
          let row;
          while ((row = this.next_array()) !== null) {
            out.push(row);
          }
          return out;
        }
        all_dict() {
          const out = [];
          let row;
          while ((row = this.next_dict()) !== null) {
            out.push(row);
          }
          return out;
        }
        headers() {
          return this.headersList ? this.headersList.slice() : null;
        }
        columns() {
          return this.headers();
        }
        set_columns(columns) {
          this.headersList = arrayValue(columns).map((name2) => String(name2));
          this.mode = "dict";
          return this.headers();
        }
        row_number() {
          return this.rowNumberValue;
        }
        skip_lines(count) {
          let skipped = 0;
          while (skipped < Number(count || 0)) {
            if (this._nextPhysicalLine() == null) {
              break;
            }
            skipped++;
          }
          return skipped;
        }
        errors() {
          return this.errorsList.slice();
        }
        close() {
          if (!this.closed) {
            this.closed = true;
            this.source.close();
          }
          return 1;
        }
        *[Symbol.iterator]() {
          let row;
          while ((row = this.next()) !== null) {
            yield row;
          }
        }
        to_Iterator() {
          return this[Symbol.iterator]();
        }
      };
      function outputColumnsFromRows(rows, config) {
        const configured = columnNamesFromConfig(config);
        if (configured && configured.length > 0) {
          return configured;
        }
        for (const row of rows) {
          if (Array.isArray(row)) {
            return config.headers ? defaultColumnsForRow(row) : null;
          }
          if (isPlainObject2(row)) {
            const keys = Object.keys(row);
            if (config.sort_columns) {
              keys.sort((left, right) => left.localeCompare(right));
            }
            return keys;
          }
        }
        return null;
      }
      function formatOutputRow(row, columns) {
        if (Array.isArray(row)) {
          return row.slice();
        }
        if (isPlainObject2(row)) {
          return (columns || Object.keys(row)).map((name2) => row[name2]);
        }
        return [row];
      }
      function encodeCell(value, config) {
        if (value == null) {
          return "";
        }
        const sep = String(config.sep_char ?? ",");
        const quote = String(config.quote_char ?? '"');
        const escape = String(config.escape_char ?? quote);
        let text = String(value);
        const needsQuote = config.always_quote || text.includes(sep) || text.includes("\n") || text.includes("\r") || text.includes(quote) || config.quote_space && /^\s|\s$/u.test(text) || config.quote_empty && text === "";
        if (!needsQuote) {
          return text;
        }
        if (escape === quote) {
          text = text.replaceAll(quote, quote + quote);
        } else {
          text = text.replaceAll(escape, escape + escape);
          text = text.replaceAll(quote, escape + quote);
        }
        return `${quote}${text}${quote}`;
      }
      function quotedIdentifier(name2) {
        return `"${String(name2).replaceAll('"', '""')}"`;
      }
      var CSVWriter = class {
        constructor(target, options = {}) {
          if (!isPath(target)) {
            throw new Error("TypeException: CSV.open_writer expects Path as first argument");
          }
          const fs = _nodeFs();
          if (!fs) {
            throw new Error("CSV file access requires filesystem support");
          }
          this.config = runtimeConfig(options);
          this.columnsList = columnNamesFromConfig(this.config);
          this.rowNumberValue = 0;
          this.wroteHeader = !!this.config.append;
          const flag = this.config.append ? "a" : "w";
          this.fd = fs.openSync(target.to_String(), flag);
          this.closed = false;
        }
        _writeText(text) {
          const fs = _nodeFs();
          fs.writeSync(this.fd, text, null, "utf8");
        }
        columns() {
          return this.columnsList ? this.columnsList.slice() : null;
        }
        write_header(columns = null) {
          if (columns != null) {
            this.columnsList = arrayValue(columns).map((name2) => String(name2));
          }
          if (!Array.isArray(this.columnsList)) {
            this.columnsList = [];
          }
          this._writeText(
            this.columnsList.map((value) => encodeCell(value, this.config)).join(String(this.config.sep_char ?? ",")) + String(this.config.eol ?? "\n")
          );
          this.wroteHeader = true;
          return this.columns();
        }
        write_row(row) {
          if (this.closed) {
            throw new Error("CSVWriter is closed");
          }
          if (!this.columnsList) {
            if (Array.isArray(row) && this.config.headers) {
              this.columnsList = defaultColumnsForRow(row);
            } else if (isPlainObject2(row)) {
              this.columnsList = Object.keys(row);
              if (this.config.sort_columns) {
                this.columnsList.sort((left, right) => left.localeCompare(right));
              }
            }
          }
          if (this.config.headers && !this.wroteHeader && this.columnsList) {
            this.write_header(this.columnsList);
          }
          const fields = formatOutputRow(row, this.columnsList);
          this._writeText(
            fields.map((value) => encodeCell(value, this.config)).join(String(this.config.sep_char ?? ",")) + String(this.config.eol ?? "\n")
          );
          this.rowNumberValue++;
          return fields;
        }
        print_row(row) {
          return this.write_row(row);
        }
        row_number() {
          return this.rowNumberValue;
        }
        close() {
          if (!this.closed) {
            this.closed = true;
            const fs = _nodeFs();
            fs.closeSync(this.fd);
          }
          return 1;
        }
      };
      function sniffCounts(text, char) {
        return String(text ?? "").split(/\r?\n/u).filter((line) => line !== "").slice(0, 5).reduce((count, line) => count + (line.split(char).length - 1), 0);
      }
      function sniffText(source, config = {}) {
        const candidates = arrayValue(config.sniff_candidates);
        const chars = candidates.length > 0 ? candidates : [",", "	", ";", "|"];
        let best = chars[0];
        let bestScore = -1;
        for (const char of chars) {
          const score = sniffCounts(source, char);
          if (score > bestScore) {
            bestScore = score;
            best = char;
          }
        }
        const first = String(source ?? "").split(/\r?\n/u).find((line) => /\S/u.test(line)) || "";
        let headers = 0;
        if (first !== "") {
          const parts = first.split(best);
          headers = parts.length > 0 && parts.every((part) => !/^-?(?:\d+(?:\.\d+)?)$/u.test(part)) ? 1 : 0;
        }
        return {
          sep_char: best,
          headers,
          quote_char: '"'
        };
      }
      var CSV = class _CSV {
        constructor(options = {}) {
          this.config = runtimeConfig(options);
        }
        sniff(source) {
          if (isPath(source)) {
            assertCapability("fs", "CSV.sniff is denied by runtime policy");
            return this.sniff_binarystring(source.slurp());
          }
          return sniffText(source, this.config);
        }
        sniff_binarystring(source) {
          if (!(source instanceof BinaryString2)) {
            throw new Error("TypeException: CSV.sniff_binarystring expects BinaryString");
          }
          return sniffText(utf8Decoder.decode(source.bytes), this.config);
        }
        transpose(rows) {
          const matrix = Array.isArray(rows) ? rows : [];
          let max = 0;
          for (const row of matrix) {
            max = Math.max(max, Array.isArray(row) ? row.length : 1);
          }
          const out = [];
          for (let i = 0; i < max; i++) {
            const next = [];
            for (const row of matrix) {
              next.push(Array.isArray(row) ? row[i] : i === 0 ? row : null);
            }
            out.push(next);
          }
          return out;
        }
        decode(text) {
          const report = this.decode_report(text);
          if (report.errors.length > 0 && String(this.config.on_error || "die").toLowerCase() !== "collect") {
            throw new Error(report.errors[0].message);
          }
          return report.rows;
        }
        decode_binarystring(raw) {
          if (!(raw instanceof BinaryString2)) {
            throw new Error("TypeException: CSV.decode_binarystring expects BinaryString");
          }
          return this.decode(utf8Decoder.decode(raw.bytes));
        }
        decode_report(text) {
          const config = runtimeConfig(this.config, { on_error: "collect" });
          const rows = [];
          const errors = [];
          const nextLine = sourceLinesFromText(text);
          let headers = columnNamesFromConfig(config);
          let lineNumber = 0;
          let rowNumber = 0;
          let buffer = "";
          let recordStartLine = null;
          let skipRemaining = Number(config.skip_lines || 0);
          while (true) {
            const line = nextLine();
            if (line == null) {
              break;
            }
            lineNumber++;
            if (buffer === "") {
              if (skipRemaining > 0) {
                skipRemaining--;
                continue;
              }
              if (config.comment_char && line.startsWith(String(config.comment_char))) {
                continue;
              }
              if (config.skip_empty_rows && /^\s*$/u.test(line)) {
                continue;
              }
              recordStartLine = lineNumber;
            }
            buffer += line;
            let row;
            try {
              row = parseRecord(buffer, config);
            } catch (error) {
              if (error instanceof UnterminatedQuoteError) {
                continue;
              }
              errors.push(
                csvErrorDetail(
                  error,
                  {
                    line_number: recordStartLine,
                    row_number: rowNumber + 1,
                    raw_line: buffer
                  }
                )
              );
              buffer = "";
              break;
            }
            buffer = "";
            if (!headers && config.headers) {
              headers = normalizeHeaders(row, config);
              requireColumns(headers, config);
              continue;
            }
            try {
              rowNumber++;
              rows.push(
                applyRowRules(
                  row,
                  headers,
                  config,
                  {
                    line_number: recordStartLine,
                    row_number: rowNumber,
                    raw_line: line
                  }
                )
              );
            } catch (error) {
              errors.push(
                csvErrorDetail(
                  error,
                  {
                    line_number: recordStartLine,
                    row_number: rowNumber,
                    raw_line: line
                  }
                )
              );
              buffer = "";
            }
          }
          if (buffer !== "") {
            try {
              const row = parseRecord(buffer, config);
              if (!headers && config.headers) {
                headers = normalizeHeaders(row, config);
                requireColumns(headers, config);
              } else {
                rowNumber++;
                rows.push(
                  applyRowRules(
                    row,
                    headers,
                    config,
                    {
                      line_number: recordStartLine,
                      row_number: rowNumber,
                      raw_line: buffer
                    }
                  )
                );
              }
            } catch (error) {
              errors.push(
                csvErrorDetail(
                  error,
                  {
                    line_number: recordStartLine,
                    row_number: rowNumber + 1,
                    raw_line: buffer
                  }
                )
              );
            }
          }
          return { rows, errors };
        }
        decode_report_binarystring(raw) {
          if (!(raw instanceof BinaryString2)) {
            throw new Error(
              "TypeException: CSV.decode_report_binarystring expects BinaryString"
            );
          }
          return this.decode_report(utf8Decoder.decode(raw.bytes));
        }
        encode(rows) {
          const input = Array.isArray(rows) ? rows : [];
          const columns = outputColumnsFromRows(input, this.config);
          const lines = [];
          if (this.config.headers && columns) {
            lines.push(this.encode_row(columns).replace(/\n$/u, ""));
          }
          for (const row of input) {
            lines.push(
              formatOutputRow(row, columns).map((value) => encodeCell(value, this.config)).join(String(this.config.sep_char ?? ","))
            );
          }
          return lines.join(String(this.config.eol ?? "\n")) + (lines.length > 0 ? String(this.config.eol ?? "\n") : "");
        }
        encode_binarystring(rows) {
          return new BinaryString2(utf8Encoder.encode(this.encode(rows)));
        }
        encode_row(row) {
          const fields = formatOutputRow(row, null);
          return fields.map((value) => encodeCell(value, this.config)).join(String(this.config.sep_char ?? ",")) + String(this.config.eol ?? "\n");
        }
        encode_row_binarystring(row) {
          return new BinaryString2(utf8Encoder.encode(this.encode_row(row)));
        }
        load(pathValue) {
          if (!isPath(pathValue)) {
            throw new Error("TypeException: CSV.load expects Path as first argument");
          }
          assertCapability("fs", "CSV.load is denied by runtime policy");
          return this.decode_binarystring(pathValue.slurp());
        }
        load_report(pathValue) {
          if (!isPath(pathValue)) {
            throw new Error("TypeException: CSV.load_report expects Path as first argument");
          }
          assertCapability("fs", "CSV.load_report is denied by runtime policy");
          return this.decode_report_binarystring(pathValue.slurp());
        }
        dump(pathValue, rows) {
          if (!isPath(pathValue)) {
            throw new Error("TypeException: CSV.dump expects Path as first argument");
          }
          assertCapability("fs", "CSV.dump is denied by runtime policy");
          pathValue.spew(this.encode_binarystring(rows));
          return pathValue;
        }
        open(pathValue) {
          if (!isPath(pathValue)) {
            throw new Error("TypeException: CSV.open expects Path as first argument");
          }
          assertCapability("fs", "CSV.open is denied by runtime policy");
          return new CSVReader(pathValue, this.config);
        }
        open_writer(pathValue, options = {}) {
          if (!isPath(pathValue)) {
            throw new Error("TypeException: CSV.open_writer expects Path as first argument");
          }
          assertCapability("fs", "CSV.open_writer is denied by runtime policy");
          return new CSVWriter(pathValue, normalizeConfig(this.config, options));
        }
        dump_query(pathValue, dbh, sql, bind = [], options = {}) {
          if (!isPath(pathValue)) {
            throw new Error("TypeException: CSV.dump_query expects Path as first argument");
          }
          if (!isDbHandle(dbh)) {
            throw new Error("TypeException: CSV.dump_query expects DatabaseHandle");
          }
          assertCapability("fs", "CSV.dump_query is denied by runtime policy");
          assertCapability("db", "CSV.dump_query is denied by runtime policy");
          const stmt = dbh.prepare(String(sql));
          stmt.execute(...Array.isArray(bind) ? bind : []);
          const rows = stmt.all_dict();
          const config = normalizeConfig(this.config, { headers: true }, options);
          return new _CSV(config).dump(pathValue, rows);
        }
        dump_table(pathValue, dbh, table, options = {}) {
          return this.dump_query(
            pathValue,
            dbh,
            `select * from ${quotedIdentifier(table)}`,
            [],
            normalizeConfig({ headers: true }, options)
          );
        }
        load_table(pathValue, dbh, table, options = {}) {
          if (!isPath(pathValue)) {
            throw new Error("TypeException: CSV.load_table expects Path as first argument");
          }
          if (!isDbHandle(dbh)) {
            throw new Error("TypeException: CSV.load_table expects DatabaseHandle");
          }
          assertCapability("fs", "CSV.load_table is denied by runtime policy");
          assertCapability("db", "CSV.load_table is denied by runtime policy");
          const config = normalizeConfig(this.config, options);
          const reader = new _CSV(config).open(pathValue);
          let sourceColumns = reader.columns();
          let firstRow = sourceColumns ? reader.next_dict() : reader.next_array();
          if (firstRow == null) {
            reader.close();
            return 0;
          }
          if (!sourceColumns) {
            sourceColumns = Array.isArray(firstRow) ? defaultColumnsForRow(firstRow) : Object.keys(firstRow);
            reader.set_columns(sourceColumns);
            if (Array.isArray(firstRow)) {
              firstRow = Object.fromEntries(
                sourceColumns.map((name2, index) => [name2, firstRow[index]])
              );
            }
          }
          const targetColumns = sourceColumns.map(
            (name2) => config.column_map && Object.prototype.hasOwnProperty.call(config.column_map, name2) ? config.column_map[name2] : name2
          );
          if (config.create_table) {
            if (String(config.if_exists || "append").toLowerCase() === "replace") {
              dbh.prepare(`drop table if exists ${quotedIdentifier(table)}`).execute();
            }
            const defs = targetColumns.map((name2, index) => {
              let type = "TEXT";
              if (Array.isArray(config.column_types)) {
                type = String(config.column_types[index] || "TEXT");
              } else if (isPlainObject2(config.column_types)) {
                type = String(config.column_types[name2] || "TEXT");
              }
              return `${quotedIdentifier(name2)} ${type}`;
            });
            const ifNotExists = String(config.if_exists || "append").toLowerCase() === "append" ? " if not exists" : "";
            dbh.prepare(
              `create table${ifNotExists} ${quotedIdentifier(table)} (${defs.join(", ")})`
            ).execute();
          }
          const conflict = String(config.conflict || "").trim();
          const insertPrefix = conflict === "" || conflict.toLowerCase() === "default" ? "insert" : `insert or ${conflict.toUpperCase()}`;
          const placeholders = targetColumns.map(() => "?").join(", ");
          const stmt = dbh.prepare(
            `${insertPrefix} into ${quotedIdentifier(table)} (${targetColumns.map(quotedIdentifier).join(", ")}) values (${placeholders})`
          );
          const transactionEnabled = config.transaction !== false;
          const commitInterval = Number(config.commit_interval || 0);
          let count = 0;
          if (transactionEnabled) {
            dbh.begin();
          }
          try {
            const writeRow = (row2) => {
              const dict = Array.isArray(row2) ? Object.fromEntries(sourceColumns.map((name2, index) => [name2, row2[index]])) : row2;
              const values = sourceColumns.map((name2) => dict[name2]);
              stmt.execute(...values);
              count++;
              if (transactionEnabled && commitInterval > 0 && count % commitInterval === 0) {
                dbh.commit();
                dbh.begin();
              }
            };
            writeRow(firstRow);
            let row;
            while ((row = reader.next_dict()) !== null) {
              writeRow(row);
            }
            if (transactionEnabled) {
              dbh.commit();
            }
          } catch (error) {
            if (transactionEnabled) {
              dbh.rollback();
            }
            reader.close();
            throw error;
          }
          reader.close();
          return count;
        }
      };
      module2.exports = {
        CSV,
        CSVReader,
        CSVWriter,
        __zuzu_set_runtime_policy(policy = {}) {
          runtimePolicy2 = { ...runtimePolicy2, ...policy };
        }
      };
    }
  });

  // node_modules/@xmldom/xmldom/lib/conventions.js
  var require_conventions = __commonJS({
    "node_modules/@xmldom/xmldom/lib/conventions.js"(exports2) {
      "use strict";
      function find(list, predicate, ac) {
        if (ac === void 0) {
          ac = Array.prototype;
        }
        if (list && typeof ac.find === "function") {
          return ac.find.call(list, predicate);
        }
        for (var i = 0; i < list.length; i++) {
          if (hasOwn(list, i)) {
            var item = list[i];
            if (predicate.call(void 0, item, i, list)) {
              return item;
            }
          }
        }
      }
      function freeze(object, oc) {
        if (oc === void 0) {
          oc = Object;
        }
        if (oc && typeof oc.getOwnPropertyDescriptors === "function") {
          object = oc.create(null, oc.getOwnPropertyDescriptors(object));
        }
        return oc && typeof oc.freeze === "function" ? oc.freeze(object) : object;
      }
      function hasOwn(object, key) {
        return Object.prototype.hasOwnProperty.call(object, key);
      }
      function assign(target, source) {
        if (target === null || typeof target !== "object") {
          throw new TypeError("target is not an object");
        }
        for (var key in source) {
          if (hasOwn(source, key)) {
            target[key] = source[key];
          }
        }
        return target;
      }
      var HTML_BOOLEAN_ATTRIBUTES = freeze({
        allowfullscreen: true,
        async: true,
        autofocus: true,
        autoplay: true,
        checked: true,
        controls: true,
        default: true,
        defer: true,
        disabled: true,
        formnovalidate: true,
        hidden: true,
        ismap: true,
        itemscope: true,
        loop: true,
        multiple: true,
        muted: true,
        nomodule: true,
        novalidate: true,
        open: true,
        playsinline: true,
        readonly: true,
        required: true,
        reversed: true,
        selected: true
      });
      function isHTMLBooleanAttribute(name2) {
        return hasOwn(HTML_BOOLEAN_ATTRIBUTES, name2.toLowerCase());
      }
      var HTML_VOID_ELEMENTS = freeze({
        area: true,
        base: true,
        br: true,
        col: true,
        embed: true,
        hr: true,
        img: true,
        input: true,
        link: true,
        meta: true,
        param: true,
        source: true,
        track: true,
        wbr: true
      });
      function isHTMLVoidElement(tagName) {
        return hasOwn(HTML_VOID_ELEMENTS, tagName.toLowerCase());
      }
      var HTML_RAW_TEXT_ELEMENTS = freeze({
        script: false,
        style: false,
        textarea: true,
        title: true
      });
      function isHTMLRawTextElement(tagName) {
        var key = tagName.toLowerCase();
        return hasOwn(HTML_RAW_TEXT_ELEMENTS, key) && !HTML_RAW_TEXT_ELEMENTS[key];
      }
      function isHTMLEscapableRawTextElement(tagName) {
        var key = tagName.toLowerCase();
        return hasOwn(HTML_RAW_TEXT_ELEMENTS, key) && HTML_RAW_TEXT_ELEMENTS[key];
      }
      function isHTMLMimeType(mimeType) {
        return mimeType === MIME_TYPE.HTML;
      }
      function hasDefaultHTMLNamespace(mimeType) {
        return isHTMLMimeType(mimeType) || mimeType === MIME_TYPE.XML_XHTML_APPLICATION;
      }
      var MIME_TYPE = freeze({
        /**
         * `text/html`, the only mime type that triggers treating an XML document as HTML.
         *
         * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
         * @see https://en.wikipedia.org/wiki/HTML Wikipedia
         * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
         * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring
         *      WHATWG HTML Spec
         */
        HTML: "text/html",
        /**
         * `application/xml`, the standard mime type for XML documents.
         *
         * @see https://www.iana.org/assignments/media-types/application/xml IANA MimeType
         *      registration
         * @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303
         * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
         */
        XML_APPLICATION: "application/xml",
        /**
         * `text/xml`, an alias for `application/xml`.
         *
         * @see https://tools.ietf.org/html/rfc7303#section-9.2 RFC 7303
         * @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration
         * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
         */
        XML_TEXT: "text/xml",
        /**
         * `application/xhtml+xml`, indicates an XML document that has the default HTML namespace,
         * but is parsed as an XML document.
         *
         * @see https://www.iana.org/assignments/media-types/application/xhtml+xml IANA MimeType
         *      registration
         * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec
         * @see https://en.wikipedia.org/wiki/XHTML Wikipedia
         */
        XML_XHTML_APPLICATION: "application/xhtml+xml",
        /**
         * `image/svg+xml`,
         *
         * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration
         * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1
         * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia
         */
        XML_SVG_IMAGE: "image/svg+xml"
      });
      var _MIME_TYPES = Object.keys(MIME_TYPE).map(function(key) {
        return MIME_TYPE[key];
      });
      function isValidMimeType(mimeType) {
        return _MIME_TYPES.indexOf(mimeType) > -1;
      }
      var NAMESPACE = freeze({
        /**
         * The XHTML namespace.
         *
         * @see http://www.w3.org/1999/xhtml
         */
        HTML: "http://www.w3.org/1999/xhtml",
        /**
         * The SVG namespace.
         *
         * @see http://www.w3.org/2000/svg
         */
        SVG: "http://www.w3.org/2000/svg",
        /**
         * The `xml:` namespace.
         *
         * @see http://www.w3.org/XML/1998/namespace
         */
        XML: "http://www.w3.org/XML/1998/namespace",
        /**
         * The `xmlns:` namespace.
         *
         * @see https://www.w3.org/2000/xmlns/
         */
        XMLNS: "http://www.w3.org/2000/xmlns/"
      });
      exports2.assign = assign;
      exports2.find = find;
      exports2.freeze = freeze;
      exports2.HTML_BOOLEAN_ATTRIBUTES = HTML_BOOLEAN_ATTRIBUTES;
      exports2.HTML_RAW_TEXT_ELEMENTS = HTML_RAW_TEXT_ELEMENTS;
      exports2.HTML_VOID_ELEMENTS = HTML_VOID_ELEMENTS;
      exports2.hasDefaultHTMLNamespace = hasDefaultHTMLNamespace;
      exports2.hasOwn = hasOwn;
      exports2.isHTMLBooleanAttribute = isHTMLBooleanAttribute;
      exports2.isHTMLRawTextElement = isHTMLRawTextElement;
      exports2.isHTMLEscapableRawTextElement = isHTMLEscapableRawTextElement;
      exports2.isHTMLMimeType = isHTMLMimeType;
      exports2.isHTMLVoidElement = isHTMLVoidElement;
      exports2.isValidMimeType = isValidMimeType;
      exports2.MIME_TYPE = MIME_TYPE;
      exports2.NAMESPACE = NAMESPACE;
    }
  });

  // node_modules/@xmldom/xmldom/lib/errors.js
  var require_errors2 = __commonJS({
    "node_modules/@xmldom/xmldom/lib/errors.js"(exports2) {
      "use strict";
      var conventions = require_conventions();
      function extendError(constructor, writableName) {
        constructor.prototype = Object.create(Error.prototype, {
          constructor: { value: constructor },
          name: { value: constructor.name, enumerable: true, writable: writableName }
        });
      }
      var DOMExceptionName = conventions.freeze({
        /**
         * the default value as defined by the spec
         */
        Error: "Error",
        /**
         * @deprecated
         * Use RangeError instead.
         */
        IndexSizeError: "IndexSizeError",
        /**
         * @deprecated
         * Just to match the related static code, not part of the spec.
         */
        DomstringSizeError: "DomstringSizeError",
        HierarchyRequestError: "HierarchyRequestError",
        WrongDocumentError: "WrongDocumentError",
        InvalidCharacterError: "InvalidCharacterError",
        /**
         * @deprecated
         * Just to match the related static code, not part of the spec.
         */
        NoDataAllowedError: "NoDataAllowedError",
        NoModificationAllowedError: "NoModificationAllowedError",
        NotFoundError: "NotFoundError",
        NotSupportedError: "NotSupportedError",
        InUseAttributeError: "InUseAttributeError",
        InvalidStateError: "InvalidStateError",
        SyntaxError: "SyntaxError",
        InvalidModificationError: "InvalidModificationError",
        NamespaceError: "NamespaceError",
        /**
         * @deprecated
         * Use TypeError for invalid arguments,
         * "NotSupportedError" DOMException for unsupported operations,
         * and "NotAllowedError" DOMException for denied requests instead.
         */
        InvalidAccessError: "InvalidAccessError",
        /**
         * @deprecated
         * Just to match the related static code, not part of the spec.
         */
        ValidationError: "ValidationError",
        /**
         * @deprecated
         * Use TypeError instead.
         */
        TypeMismatchError: "TypeMismatchError",
        SecurityError: "SecurityError",
        NetworkError: "NetworkError",
        AbortError: "AbortError",
        /**
         * @deprecated
         * Just to match the related static code, not part of the spec.
         */
        URLMismatchError: "URLMismatchError",
        QuotaExceededError: "QuotaExceededError",
        TimeoutError: "TimeoutError",
        InvalidNodeTypeError: "InvalidNodeTypeError",
        DataCloneError: "DataCloneError",
        EncodingError: "EncodingError",
        NotReadableError: "NotReadableError",
        UnknownError: "UnknownError",
        ConstraintError: "ConstraintError",
        DataError: "DataError",
        TransactionInactiveError: "TransactionInactiveError",
        ReadOnlyError: "ReadOnlyError",
        VersionError: "VersionError",
        OperationError: "OperationError",
        NotAllowedError: "NotAllowedError",
        OptOutError: "OptOutError"
      });
      var DOMExceptionNames = Object.keys(DOMExceptionName);
      function isValidDomExceptionCode(value) {
        return typeof value === "number" && value >= 1 && value <= 25;
      }
      function endsWithError(value) {
        return typeof value === "string" && value.substring(value.length - DOMExceptionName.Error.length) === DOMExceptionName.Error;
      }
      function DOMException(messageOrCode, nameOrMessage) {
        if (isValidDomExceptionCode(messageOrCode)) {
          this.name = DOMExceptionNames[messageOrCode];
          this.message = nameOrMessage || "";
        } else {
          this.message = messageOrCode;
          this.name = endsWithError(nameOrMessage) ? nameOrMessage : DOMExceptionName.Error;
        }
        if (Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
      }
      extendError(DOMException, true);
      Object.defineProperties(DOMException.prototype, {
        code: {
          enumerable: true,
          get: function() {
            var code = DOMExceptionNames.indexOf(this.name);
            if (isValidDomExceptionCode(code)) return code;
            return 0;
          }
        }
      });
      var ExceptionCode = {
        INDEX_SIZE_ERR: 1,
        DOMSTRING_SIZE_ERR: 2,
        HIERARCHY_REQUEST_ERR: 3,
        WRONG_DOCUMENT_ERR: 4,
        INVALID_CHARACTER_ERR: 5,
        NO_DATA_ALLOWED_ERR: 6,
        NO_MODIFICATION_ALLOWED_ERR: 7,
        NOT_FOUND_ERR: 8,
        NOT_SUPPORTED_ERR: 9,
        INUSE_ATTRIBUTE_ERR: 10,
        INVALID_STATE_ERR: 11,
        SYNTAX_ERR: 12,
        INVALID_MODIFICATION_ERR: 13,
        NAMESPACE_ERR: 14,
        INVALID_ACCESS_ERR: 15,
        VALIDATION_ERR: 16,
        TYPE_MISMATCH_ERR: 17,
        SECURITY_ERR: 18,
        NETWORK_ERR: 19,
        ABORT_ERR: 20,
        URL_MISMATCH_ERR: 21,
        QUOTA_EXCEEDED_ERR: 22,
        TIMEOUT_ERR: 23,
        INVALID_NODE_TYPE_ERR: 24,
        DATA_CLONE_ERR: 25
      };
      var entries = Object.entries(ExceptionCode);
      for (i = 0; i < entries.length; i++) {
        key = entries[i][0];
        DOMException[key] = entries[i][1];
      }
      var key;
      var i;
      function ParseError(message, locator) {
        this.message = message;
        this.locator = locator;
        if (Error.captureStackTrace) Error.captureStackTrace(this, ParseError);
      }
      extendError(ParseError);
      exports2.DOMException = DOMException;
      exports2.DOMExceptionName = DOMExceptionName;
      exports2.ExceptionCode = ExceptionCode;
      exports2.ParseError = ParseError;
    }
  });

  // node_modules/@xmldom/xmldom/lib/grammar.js
  var require_grammar = __commonJS({
    "node_modules/@xmldom/xmldom/lib/grammar.js"(exports2) {
      "use strict";
      function detectUnicodeSupport(RegExpImpl) {
        try {
          if (typeof RegExpImpl !== "function") {
            RegExpImpl = RegExp;
          }
          var match = new RegExpImpl("\u{1D306}", "u").exec("\u{1D306}");
          return !!match && match[0].length === 2;
        } catch (error) {
        }
        return false;
      }
      var UNICODE_SUPPORT = detectUnicodeSupport();
      function chars(regexp) {
        if (regexp.source[0] !== "[") {
          throw new Error(regexp + " can not be used with chars");
        }
        return regexp.source.slice(1, regexp.source.lastIndexOf("]"));
      }
      function chars_without(regexp, search) {
        if (regexp.source[0] !== "[") {
          throw new Error("/" + regexp.source + "/ can not be used with chars_without");
        }
        if (!search || typeof search !== "string") {
          throw new Error(JSON.stringify(search) + " is not a valid search");
        }
        if (regexp.source.indexOf(search) === -1) {
          throw new Error('"' + search + '" is not is /' + regexp.source + "/");
        }
        if (search === "-" && regexp.source.indexOf(search) !== 1) {
          throw new Error('"' + search + '" is not at the first postion of /' + regexp.source + "/");
        }
        return new RegExp(regexp.source.replace(search, ""), UNICODE_SUPPORT ? "u" : "");
      }
      function reg(args) {
        var self = this;
        return new RegExp(
          Array.prototype.slice.call(arguments).map(function(part) {
            var isStr = typeof part === "string";
            if (isStr && self === void 0 && part === "|") {
              throw new Error("use regg instead of reg to wrap expressions with `|`!");
            }
            return isStr ? part : part.source;
          }).join(""),
          UNICODE_SUPPORT ? "mu" : "m"
        );
      }
      function regg(args) {
        if (arguments.length === 0) {
          throw new Error("no parameters provided");
        }
        return reg.apply(regg, ["(?:"].concat(Array.prototype.slice.call(arguments), [")"]));
      }
      var UNICODE_REPLACEMENT_CHARACTER = "\uFFFD";
      var Char = /[-\x09\x0A\x0D\x20-\x2C\x2E-\uD7FF\uE000-\uFFFD]/;
      if (UNICODE_SUPPORT) {
        Char = reg("[", chars(Char), "\\u{10000}-\\u{10FFFF}", "]");
      }
      var InvalidChar = new RegExp("[^" + chars(Char) + "]", UNICODE_SUPPORT ? "u" : "");
      var _SChar = /[\x20\x09\x0D\x0A]/;
      var SChar_s = chars(_SChar);
      var S = reg(_SChar, "+");
      var S_OPT = reg(_SChar, "*");
      var NameStartChar = /[:_a-zA-Z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;
      if (UNICODE_SUPPORT) {
        NameStartChar = reg("[", chars(NameStartChar), "\\u{10000}-\\u{10FFFF}", "]");
      }
      var NameStartChar_s = chars(NameStartChar);
      var NameChar = reg("[", NameStartChar_s, chars(/[-.0-9\xB7]/), chars(/[\u0300-\u036F\u203F-\u2040]/), "]");
      var Name = reg(NameStartChar, NameChar, "*");
      var Nmtoken = reg(NameChar, "+");
      var EntityRef = reg("&", Name, ";");
      var CharRef = regg(/&#[0-9]+;|&#x[0-9a-fA-F]+;/);
      var Reference = regg(EntityRef, "|", CharRef);
      var PEReference = reg("%", Name, ";");
      var EntityValue = regg(
        reg('"', regg(/[^%&"]/, "|", PEReference, "|", Reference), "*", '"'),
        "|",
        reg("'", regg(/[^%&']/, "|", PEReference, "|", Reference), "*", "'")
      );
      var AttValue = regg('"', regg(/[^<&"]/, "|", Reference), "*", '"', "|", "'", regg(/[^<&']/, "|", Reference), "*", "'");
      var NCNameStartChar = chars_without(NameStartChar, ":");
      var NCNameChar = chars_without(NameChar, ":");
      var NCName = reg(NCNameStartChar, NCNameChar, "*");
      var QName = reg(NCName, regg(":", NCName), "?");
      var QName_exact = reg("^", QName, "$");
      var QName_group = reg("(", QName, ")");
      var SystemLiteral = regg(/"[^"]*"|'[^']*'/);
      var PI = reg(/^<\?/, "(", Name, ")", regg(S, "(", Char, "*?)"), "?", /\?>/);
      var PubidChar = /[\x20\x0D\x0Aa-zA-Z0-9-'()+,./:=?;!*#@$_%]/;
      var PubidLiteral = regg('"', PubidChar, '*"', "|", "'", chars_without(PubidChar, "'"), "*'");
      var COMMENT_START = "<!--";
      var COMMENT_END = "-->";
      var Comment = reg(COMMENT_START, regg(chars_without(Char, "-"), "|", reg("-", chars_without(Char, "-"))), "*", COMMENT_END);
      var PCDATA = "#PCDATA";
      var Mixed = regg(
        reg(/\(/, S_OPT, PCDATA, regg(S_OPT, /\|/, S_OPT, QName), "*", S_OPT, /\)\*/),
        "|",
        reg(/\(/, S_OPT, PCDATA, S_OPT, /\)/)
      );
      var _children_quantity = /[?*+]?/;
      var children = reg(
        /\([^>]+\)/,
        _children_quantity
        /*regg(choice, '|', seq), _children_quantity*/
      );
      var contentspec = regg("EMPTY", "|", "ANY", "|", Mixed, "|", children);
      var ELEMENTDECL_START = "<!ELEMENT";
      var elementdecl = reg(ELEMENTDECL_START, S, regg(QName, "|", PEReference), S, regg(contentspec, "|", PEReference), S_OPT, ">");
      var NotationType = reg("NOTATION", S, /\(/, S_OPT, Name, regg(S_OPT, /\|/, S_OPT, Name), "*", S_OPT, /\)/);
      var Enumeration = reg(/\(/, S_OPT, Nmtoken, regg(S_OPT, /\|/, S_OPT, Nmtoken), "*", S_OPT, /\)/);
      var EnumeratedType = regg(NotationType, "|", Enumeration);
      var AttType = regg(/CDATA|ID|IDREF|IDREFS|ENTITY|ENTITIES|NMTOKEN|NMTOKENS/, "|", EnumeratedType);
      var DefaultDecl = regg(/#REQUIRED|#IMPLIED/, "|", regg(regg("#FIXED", S), "?", AttValue));
      var AttDef = regg(S, Name, S, AttType, S, DefaultDecl);
      var ATTLIST_DECL_START = "<!ATTLIST";
      var AttlistDecl = reg(ATTLIST_DECL_START, S, Name, AttDef, "*", S_OPT, ">");
      var ABOUT_LEGACY_COMPAT = "about:legacy-compat";
      var ABOUT_LEGACY_COMPAT_SystemLiteral = regg('"' + ABOUT_LEGACY_COMPAT + '"', "|", "'" + ABOUT_LEGACY_COMPAT + "'");
      var SYSTEM = "SYSTEM";
      var PUBLIC = "PUBLIC";
      var ExternalID = regg(regg(SYSTEM, S, SystemLiteral), "|", regg(PUBLIC, S, PubidLiteral, S, SystemLiteral));
      var ExternalID_match = reg(
        "^",
        regg(
          regg(SYSTEM, S, "(?<SystemLiteralOnly>", SystemLiteral, ")"),
          "|",
          regg(PUBLIC, S, "(?<PubidLiteral>", PubidLiteral, ")", S, "(?<SystemLiteral>", SystemLiteral, ")")
        )
      );
      var PubidLiteral_match = reg("^", PubidLiteral, "$");
      var SystemLiteral_match = reg("^", SystemLiteral, "$");
      var NDataDecl = regg(S, "NDATA", S, Name);
      var EntityDef = regg(EntityValue, "|", regg(ExternalID, NDataDecl, "?"));
      var ENTITY_DECL_START = "<!ENTITY";
      var GEDecl = reg(ENTITY_DECL_START, S, Name, S, EntityDef, S_OPT, ">");
      var PEDef = regg(EntityValue, "|", ExternalID);
      var PEDecl = reg(ENTITY_DECL_START, S, "%", S, Name, S, PEDef, S_OPT, ">");
      var EntityDecl = regg(GEDecl, "|", PEDecl);
      var PublicID = reg(PUBLIC, S, PubidLiteral);
      var NotationDecl = reg("<!NOTATION", S, Name, S, regg(ExternalID, "|", PublicID), S_OPT, ">");
      var Eq = reg(S_OPT, "=", S_OPT);
      var VersionNum = /1[.]\d+/;
      var VersionInfo = reg(S, "version", Eq, regg("'", VersionNum, "'", "|", '"', VersionNum, '"'));
      var EncName = /[A-Za-z][-A-Za-z0-9._]*/;
      var EncodingDecl = regg(S, "encoding", Eq, regg('"', EncName, '"', "|", "'", EncName, "'"));
      var SDDecl = regg(S, "standalone", Eq, regg("'", regg("yes", "|", "no"), "'", "|", '"', regg("yes", "|", "no"), '"'));
      var XMLDecl = reg(/^<\?xml/, VersionInfo, EncodingDecl, "?", SDDecl, "?", S_OPT, /\?>/);
      var DOCTYPE_DECL_START = "<!DOCTYPE";
      var CDATA_START = "<![CDATA[";
      var CDATA_END = "]]>";
      var CDStart = /<!\[CDATA\[/;
      var CDEnd = /\]\]>/;
      var CData = reg(Char, "*?", CDEnd);
      var CDSect = reg(CDStart, CData);
      exports2.chars = chars;
      exports2.chars_without = chars_without;
      exports2.detectUnicodeSupport = detectUnicodeSupport;
      exports2.reg = reg;
      exports2.regg = regg;
      exports2.ABOUT_LEGACY_COMPAT = ABOUT_LEGACY_COMPAT;
      exports2.ABOUT_LEGACY_COMPAT_SystemLiteral = ABOUT_LEGACY_COMPAT_SystemLiteral;
      exports2.AttlistDecl = AttlistDecl;
      exports2.CDATA_START = CDATA_START;
      exports2.CDATA_END = CDATA_END;
      exports2.CDSect = CDSect;
      exports2.Char = Char;
      exports2.Comment = Comment;
      exports2.COMMENT_START = COMMENT_START;
      exports2.COMMENT_END = COMMENT_END;
      exports2.DOCTYPE_DECL_START = DOCTYPE_DECL_START;
      exports2.elementdecl = elementdecl;
      exports2.EntityDecl = EntityDecl;
      exports2.EntityValue = EntityValue;
      exports2.ExternalID = ExternalID;
      exports2.ExternalID_match = ExternalID_match;
      exports2.Name = Name;
      exports2.NotationDecl = NotationDecl;
      exports2.Reference = Reference;
      exports2.PEReference = PEReference;
      exports2.PI = PI;
      exports2.PUBLIC = PUBLIC;
      exports2.PubidLiteral = PubidLiteral;
      exports2.PubidLiteral_match = PubidLiteral_match;
      exports2.QName = QName;
      exports2.QName_exact = QName_exact;
      exports2.QName_group = QName_group;
      exports2.S = S;
      exports2.SChar_s = SChar_s;
      exports2.S_OPT = S_OPT;
      exports2.SYSTEM = SYSTEM;
      exports2.SystemLiteral = SystemLiteral;
      exports2.SystemLiteral_match = SystemLiteral_match;
      exports2.InvalidChar = InvalidChar;
      exports2.UNICODE_REPLACEMENT_CHARACTER = UNICODE_REPLACEMENT_CHARACTER;
      exports2.UNICODE_SUPPORT = UNICODE_SUPPORT;
      exports2.XMLDecl = XMLDecl;
    }
  });

  // node_modules/@xmldom/xmldom/lib/dom.js
  var require_dom = __commonJS({
    "node_modules/@xmldom/xmldom/lib/dom.js"(exports2) {
      "use strict";
      var conventions = require_conventions();
      var find = conventions.find;
      var hasDefaultHTMLNamespace = conventions.hasDefaultHTMLNamespace;
      var hasOwn = conventions.hasOwn;
      var isHTMLMimeType = conventions.isHTMLMimeType;
      var isHTMLRawTextElement = conventions.isHTMLRawTextElement;
      var isHTMLVoidElement = conventions.isHTMLVoidElement;
      var MIME_TYPE = conventions.MIME_TYPE;
      var NAMESPACE = conventions.NAMESPACE;
      var PDC = /* @__PURE__ */ Symbol();
      var errors = require_errors2();
      var DOMException = errors.DOMException;
      var DOMExceptionName = errors.DOMExceptionName;
      var g = require_grammar();
      function checkSymbol(symbol) {
        if (symbol !== PDC) {
          throw new TypeError("Illegal constructor");
        }
      }
      function notEmptyString(input) {
        return input !== "";
      }
      function splitOnASCIIWhitespace(input) {
        return input ? input.split(/[\t\n\f\r ]+/).filter(notEmptyString) : [];
      }
      function orderedSetReducer(current, element) {
        if (!hasOwn(current, element)) {
          current[element] = true;
        }
        return current;
      }
      function toOrderedSet(input) {
        if (!input) return [];
        var list = splitOnASCIIWhitespace(input);
        return Object.keys(list.reduce(orderedSetReducer, {}));
      }
      function arrayIncludes(list) {
        return function(element) {
          return list && list.indexOf(element) !== -1;
        };
      }
      function validateQualifiedName(qualifiedName) {
        if (!g.QName_exact.test(qualifiedName)) {
          throw new DOMException(DOMException.INVALID_CHARACTER_ERR, 'invalid character in qualified name "' + qualifiedName + '"');
        }
      }
      function validateAndExtract(namespace, qualifiedName) {
        validateQualifiedName(qualifiedName);
        namespace = namespace || null;
        var prefix = null;
        var localName = qualifiedName;
        if (qualifiedName.indexOf(":") >= 0) {
          var splitResult = qualifiedName.split(":");
          prefix = splitResult[0];
          localName = splitResult[1];
        }
        if (prefix !== null && namespace === null) {
          throw new DOMException(DOMException.NAMESPACE_ERR, "prefix is non-null and namespace is null");
        }
        if (prefix === "xml" && namespace !== conventions.NAMESPACE.XML) {
          throw new DOMException(DOMException.NAMESPACE_ERR, 'prefix is "xml" and namespace is not the XML namespace');
        }
        if ((prefix === "xmlns" || qualifiedName === "xmlns") && namespace !== conventions.NAMESPACE.XMLNS) {
          throw new DOMException(
            DOMException.NAMESPACE_ERR,
            'either qualifiedName or prefix is "xmlns" and namespace is not the XMLNS namespace'
          );
        }
        if (namespace === conventions.NAMESPACE.XMLNS && prefix !== "xmlns" && qualifiedName !== "xmlns") {
          throw new DOMException(
            DOMException.NAMESPACE_ERR,
            'namespace is the XMLNS namespace and neither qualifiedName nor prefix is "xmlns"'
          );
        }
        return [namespace, prefix, localName];
      }
      function copy(src, dest) {
        for (var p in src) {
          if (hasOwn(src, p)) {
            dest[p] = src[p];
          }
        }
      }
      function _extends(Class, Super) {
        var pt = Class.prototype;
        if (!(pt instanceof Super)) {
          let t = function() {
          };
          t.prototype = Super.prototype;
          t = new t();
          copy(pt, t);
          Class.prototype = pt = t;
        }
        if (pt.constructor != Class) {
          if (typeof Class != "function") {
            console.error("unknown Class:" + Class);
          }
          pt.constructor = Class;
        }
      }
      var NodeType = {};
      var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
      var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
      var TEXT_NODE = NodeType.TEXT_NODE = 3;
      var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
      var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
      var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
      var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
      var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
      var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
      var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
      var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
      var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
      var DocumentPosition = conventions.freeze({
        DOCUMENT_POSITION_DISCONNECTED: 1,
        DOCUMENT_POSITION_PRECEDING: 2,
        DOCUMENT_POSITION_FOLLOWING: 4,
        DOCUMENT_POSITION_CONTAINS: 8,
        DOCUMENT_POSITION_CONTAINED_BY: 16,
        DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 32
      });
      function commonAncestor(a, b) {
        if (b.length < a.length) return commonAncestor(b, a);
        var c = null;
        for (var n in a) {
          if (a[n] !== b[n]) return c;
          c = a[n];
        }
        return c;
      }
      function docGUID(doc) {
        if (!doc.guid) doc.guid = Math.random();
        return doc.guid;
      }
      function NodeList() {
      }
      NodeList.prototype = {
        /**
         * The number of nodes in the list. The range of valid child node indices is 0 to length-1
         * inclusive.
         *
         * @type {number}
         */
        length: 0,
        /**
         * Returns the item at `index`. If index is greater than or equal to the number of nodes in
         * the list, this returns null.
         *
         * @param index
         * Unsigned long Index into the collection.
         * @returns {Node | null}
         * The node at position `index` in the NodeList,
         * or null if that is not a valid index.
         */
        item: function(index) {
          return index >= 0 && index < this.length ? this[index] : null;
        },
        /**
         * Returns a string representation of the NodeList.
         *
         * Accepts the same `options` object as `XMLSerializer.prototype.serializeToString`
         * (`requireWellFormed`, `splitCDATASections`, `nodeFilter`). Passing a function is treated as
         * a legacy `nodeFilter` for backward compatibility.
         *
         * @param {Object | function} [options]
         * @param {boolean} [options.requireWellFormed=false]
         * @param {boolean} [options.splitCDATASections=true]
         * @param {function} [options.nodeFilter]
         * @returns {string}
         */
        toString: function(options) {
          var opts;
          if (typeof options === "function") {
            opts = { requireWellFormed: false, splitCDATASections: true, nodeFilter: options };
          } else if (!!options) {
            opts = {
              requireWellFormed: !!options.requireWellFormed,
              splitCDATASections: options.splitCDATASections !== false,
              nodeFilter: options.nodeFilter || null
            };
          } else {
            opts = { requireWellFormed: false, splitCDATASections: true, nodeFilter: null };
          }
          for (var buf = [], i = 0; i < this.length; i++) {
            serializeToString(this[i], buf, null, opts);
          }
          return buf.join("");
        },
        /**
         * Filters the NodeList based on a predicate.
         *
         * @param {function(Node): boolean} predicate
         * - A predicate function to filter the NodeList.
         * @returns {Node[]}
         * An array of nodes that satisfy the predicate.
         * @private
         */
        filter: function(predicate) {
          return Array.prototype.filter.call(this, predicate);
        },
        /**
         * Returns the first index at which a given node can be found in the NodeList, or -1 if it is
         * not present.
         *
         * @param {Node} item
         * - The Node item to locate in the NodeList.
         * @returns {number}
         * The first index of the node in the NodeList; -1 if not found.
         * @private
         */
        indexOf: function(item) {
          return Array.prototype.indexOf.call(this, item);
        }
      };
      NodeList.prototype[Symbol.iterator] = function() {
        var me = this;
        var index = 0;
        return {
          next: function() {
            if (index < me.length) {
              return {
                value: me[index++],
                done: false
              };
            } else {
              return {
                done: true
              };
            }
          },
          return: function() {
            return {
              done: true
            };
          }
        };
      };
      function LiveNodeList(node, refresh) {
        this._node = node;
        this._refresh = refresh;
        _updateLiveList(this);
      }
      function _updateLiveList(list) {
        var inc = list._node._inc || list._node.ownerDocument._inc;
        if (list._inc !== inc) {
          var ls = list._refresh(list._node);
          __set__(list, "length", ls.length);
          if (!list.$$length || ls.length < list.$$length) {
            for (var i = ls.length; i in list; i++) {
              if (hasOwn(list, i)) {
                delete list[i];
              }
            }
          }
          copy(ls, list);
          list._inc = inc;
        }
      }
      LiveNodeList.prototype.item = function(i) {
        _updateLiveList(this);
        return this[i] || null;
      };
      _extends(LiveNodeList, NodeList);
      function NamedNodeMap() {
      }
      function _findNodeIndex(list, node) {
        var i = 0;
        while (i < list.length) {
          if (list[i] === node) {
            return i;
          }
          i++;
        }
      }
      function _addNamedNode(el, list, newAttr, oldAttr) {
        if (oldAttr) {
          list[_findNodeIndex(list, oldAttr)] = newAttr;
        } else {
          list[list.length] = newAttr;
          list.length++;
        }
        if (el) {
          newAttr.ownerElement = el;
          var doc = el.ownerDocument;
          if (doc) {
            oldAttr && _onRemoveAttribute(doc, el, oldAttr);
            _onAddAttribute(doc, el, newAttr);
          }
        }
      }
      function _removeNamedNode(el, list, attr) {
        var i = _findNodeIndex(list, attr);
        if (i >= 0) {
          var lastIndex = list.length - 1;
          while (i <= lastIndex) {
            list[i] = list[++i];
          }
          list.length = lastIndex;
          if (el) {
            var doc = el.ownerDocument;
            if (doc) {
              _onRemoveAttribute(doc, el, attr);
            }
            attr.ownerElement = null;
          }
        }
      }
      NamedNodeMap.prototype = {
        length: 0,
        item: NodeList.prototype.item,
        /**
         * Get an attribute by name. Note: Name is in lower case in case of HTML namespace and
         * document.
         *
         * @param {string} localName
         * The local name of the attribute.
         * @returns {Attr | null}
         * The attribute with the given local name, or null if no such attribute exists.
         * @see https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name
         */
        getNamedItem: function(localName) {
          if (this._ownerElement && this._ownerElement._isInHTMLDocumentAndNamespace()) {
            localName = localName.toLowerCase();
          }
          var i = 0;
          while (i < this.length) {
            var attr = this[i];
            if (attr.nodeName === localName) {
              return attr;
            }
            i++;
          }
          return null;
        },
        /**
         * Set an attribute.
         *
         * @param {Attr} attr
         * The attribute to set.
         * @returns {Attr | null}
         * The old attribute with the same local name and namespace URI as the new one, or null if no
         * such attribute exists.
         * @throws {DOMException}
         * With code:
         * - {@link INUSE_ATTRIBUTE_ERR} - If the attribute is already an attribute of another
         * element.
         * @see https://dom.spec.whatwg.org/#concept-element-attributes-set
         */
        setNamedItem: function(attr) {
          var el = attr.ownerElement;
          if (el && el !== this._ownerElement) {
            throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR);
          }
          var oldAttr = this.getNamedItemNS(attr.namespaceURI, attr.localName);
          if (oldAttr === attr) {
            return attr;
          }
          _addNamedNode(this._ownerElement, this, attr, oldAttr);
          return oldAttr;
        },
        /**
         * Set an attribute, replacing an existing attribute with the same local name and namespace
         * URI if one exists.
         *
         * @param {Attr} attr
         * The attribute to set.
         * @returns {Attr | null}
         * The old attribute with the same local name and namespace URI as the new one, or null if no
         * such attribute exists.
         * @throws {DOMException}
         * Throws a DOMException with the name "InUseAttributeError" if the attribute is already an
         * attribute of another element.
         * @see https://dom.spec.whatwg.org/#concept-element-attributes-set
         */
        setNamedItemNS: function(attr) {
          return this.setNamedItem(attr);
        },
        /**
         * Removes an attribute specified by the local name.
         *
         * @param {string} localName
         * The local name of the attribute to be removed.
         * @returns {Attr}
         * The attribute node that was removed.
         * @throws {DOMException}
         * With code:
         * - {@link DOMException.NOT_FOUND_ERR} if no attribute with the given name is found.
         * @see https://dom.spec.whatwg.org/#dom-namednodemap-removenameditem
         * @see https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-name
         */
        removeNamedItem: function(localName) {
          var attr = this.getNamedItem(localName);
          if (!attr) {
            throw new DOMException(DOMException.NOT_FOUND_ERR, localName);
          }
          _removeNamedNode(this._ownerElement, this, attr);
          return attr;
        },
        /**
         * Removes an attribute specified by the namespace and local name.
         *
         * @param {string | null} namespaceURI
         * The namespace URI of the attribute to be removed.
         * @param {string} localName
         * The local name of the attribute to be removed.
         * @returns {Attr}
         * The attribute node that was removed.
         * @throws {DOMException}
         * With code:
         * - {@link DOMException.NOT_FOUND_ERR} if no attribute with the given namespace URI and local
         * name is found.
         * @see https://dom.spec.whatwg.org/#dom-namednodemap-removenameditemns
         * @see https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-namespace
         */
        removeNamedItemNS: function(namespaceURI, localName) {
          var attr = this.getNamedItemNS(namespaceURI, localName);
          if (!attr) {
            throw new DOMException(DOMException.NOT_FOUND_ERR, namespaceURI ? namespaceURI + " : " + localName : localName);
          }
          _removeNamedNode(this._ownerElement, this, attr);
          return attr;
        },
        /**
         * Get an attribute by namespace and local name.
         *
         * @param {string | null} namespaceURI
         * The namespace URI of the attribute.
         * @param {string} localName
         * The local name of the attribute.
         * @returns {Attr | null}
         * The attribute with the given namespace URI and local name, or null if no such attribute
         * exists.
         * @see https://dom.spec.whatwg.org/#concept-element-attributes-get-by-namespace
         */
        getNamedItemNS: function(namespaceURI, localName) {
          if (!namespaceURI) {
            namespaceURI = null;
          }
          var i = 0;
          while (i < this.length) {
            var node = this[i];
            if (node.localName === localName && node.namespaceURI === namespaceURI) {
              return node;
            }
            i++;
          }
          return null;
        }
      };
      NamedNodeMap.prototype[Symbol.iterator] = function() {
        var me = this;
        var index = 0;
        return {
          next: function() {
            if (index < me.length) {
              return {
                value: me[index++],
                done: false
              };
            } else {
              return {
                done: true
              };
            }
          },
          return: function() {
            return {
              done: true
            };
          }
        };
      };
      function DOMImplementation() {
      }
      DOMImplementation.prototype = {
        /**
         * Test if the DOM implementation implements a specific feature and version, as specified in
         * {@link https://www.w3.org/TR/DOM-Level-3-Core/core.html#DOMFeatures DOM Features}.
         *
         * The DOMImplementation.hasFeature() method returns a Boolean flag indicating if a given
         * feature is supported. The different implementations fairly diverged in what kind of
         * features were reported. The latest version of the spec settled to force this method to
         * always return true, where the functionality was accurate and in use.
         *
         * @deprecated
         * It is deprecated and modern browsers return true in all cases.
         * @function DOMImplementation#hasFeature
         * @param {string} feature
         * The name of the feature to test.
         * @param {string} [version]
         * This is the version number of the feature to test.
         * @returns {boolean}
         * Always returns true.
         * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/hasFeature MDN
         * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core
         * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard
         * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-5CED94D7 DOM Level 3 Core
         */
        hasFeature: function(feature, version) {
          return true;
        },
        /**
         * Creates a DOM Document object of the specified type with its document element. Note that
         * based on the {@link DocumentType}
         * given to create the document, the implementation may instantiate specialized
         * {@link Document} objects that support additional features than the "Core", such as "HTML"
         * {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#DOM2HTML DOM Level 2 HTML}.
         * On the other hand, setting the {@link DocumentType} after the document was created makes
         * this very unlikely to happen. Alternatively, specialized {@link Document} creation methods,
         * such as createHTMLDocument
         * {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#DOM2HTML DOM Level 2 HTML},
         * can be used to obtain specific types of {@link Document} objects.
         *
         * __It behaves slightly different from the description in the living standard__:
         * - There is no interface/class `XMLDocument`, it returns a `Document`
         * instance (with it's `type` set to `'xml'`).
         * - `encoding`, `mode`, `origin`, `url` fields are currently not declared.
         *
         * @function DOMImplementation.createDocument
         * @param {string | null} namespaceURI
         * The
         * {@link https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-namespaceURI namespace URI}
         * of the document element to create or null.
         * @param {string | null} qualifiedName
         * The
         * {@link https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-qualifiedname qualified name}
         * of the document element to be created or null.
         * @param {DocumentType | null} [doctype=null]
         * The type of document to be created or null. When doctype is not null, its
         * {@link Node#ownerDocument} attribute is set to the document being created. Default is
         * `null`
         * @returns {Document}
         * A new {@link Document} object with its document element. If the NamespaceURI,
         * qualifiedName, and doctype are null, the returned {@link Document} is empty with no
         * document element.
         * @throws {DOMException}
         * With code:
         *
         * - `INVALID_CHARACTER_ERR`: Raised if the specified qualified name is not an XML name
         * according to {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#XML XML 1.0}.
         * - `NAMESPACE_ERR`: Raised if the qualifiedName is malformed, if the qualifiedName has a
         * prefix and the namespaceURI is null, or if the qualifiedName is null and the namespaceURI
         * is different from null, or if the qualifiedName has a prefix that is "xml" and the
         * namespaceURI is different from "{@link http://www.w3.org/XML/1998/namespace}"
         * {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#Namespaces XML Namespaces},
         * or if the DOM implementation does not support the "XML" feature but a non-null namespace
         * URI was provided, since namespaces were defined by XML.
         * - `WRONG_DOCUMENT_ERR`: Raised if doctype has already been used with a different document
         * or was created from a different implementation.
         * - `NOT_SUPPORTED_ERR`: May be raised if the implementation does not support the feature
         * "XML" and the language exposed through the Document does not support XML Namespaces (such
         * as {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#HTML40 HTML 4.01}).
         * @since DOM Level 2.
         * @see {@link #createHTMLDocument}
         * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN
         * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Living Standard
         * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Level-2-Core-DOM-createDocument DOM
         *      Level 3 Core
         * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM
         *      Level 2 Core (initial)
         */
        createDocument: function(namespaceURI, qualifiedName, doctype) {
          var contentType = MIME_TYPE.XML_APPLICATION;
          if (namespaceURI === NAMESPACE.HTML) {
            contentType = MIME_TYPE.XML_XHTML_APPLICATION;
          } else if (namespaceURI === NAMESPACE.SVG) {
            contentType = MIME_TYPE.XML_SVG_IMAGE;
          }
          var doc = new Document(PDC, { contentType });
          doc.implementation = this;
          doc.childNodes = new NodeList();
          doc.doctype = doctype || null;
          if (doctype) {
            doc.appendChild(doctype);
          }
          if (qualifiedName) {
            var root = doc.createElementNS(namespaceURI, qualifiedName);
            doc.appendChild(root);
          }
          return doc;
        },
        /**
         * Creates an empty DocumentType node. Entity declarations and notations are not made
         * available. Entity reference expansions and default attribute additions do not occur.
         *
         * **This behavior is slightly different from the one in the specs**:
         * - `encoding`, `mode`, `origin`, `url` fields are currently not declared.
         * - `publicId` and `systemId` contain the raw data including any possible quotes,
         *   so they can always be serialized back to the original value
         * - `internalSubset` contains the raw string between `[` and `]` if present,
         *   but is not parsed or validated in any form.
         *
         * @function DOMImplementation#createDocumentType
         * @param {string} qualifiedName
         * The {@link https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-qualifiedname qualified
         * name} of the document type to be created.
         * @param {string} [publicId]
         * The external subset public identifier. Stored verbatim including surrounding quotes.
         * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError`
         * if the value is non-empty and does not match the XML `PubidLiteral` production
         * (W3C DOM Parsing §3.2.1.3; XML 1.0 production [12]). Creation-time validation is not
         * enforced — deferred to a future breaking release.
         * @param {string} [systemId]
         * The external subset system identifier. Stored verbatim including surrounding quotes.
         * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError`
         * if the value is non-empty and does not match the XML `SystemLiteral` production
         * (W3C DOM Parsing §3.2.1.3; XML 1.0 production [11]). Creation-time validation is not
         * enforced — deferred to a future breaking release.
         * @param {string} [internalSubset]
         * The internal subset or an empty string if it is not present. Stored verbatim.
         * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError`
         * if the value contains `"]>"`. Creation-time validation is not enforced.
         * @returns {DocumentType}
         * A new {@link DocumentType} node with {@link Node#ownerDocument} set to null.
         * @throws {DOMException}
         * With code:
         *
         * - `INVALID_CHARACTER_ERR`: Raised if the specified qualified name is not an XML name
         * according to {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#XML XML 1.0}.
         * - `NAMESPACE_ERR`: Raised if the qualifiedName is malformed.
         * - `NOT_SUPPORTED_ERR`: May be raised if the implementation does not support the feature
         * "XML" and the language exposed through the Document does not support XML Namespaces (such
         * as {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#HTML40 HTML 4.01}).
         * @since DOM Level 2.
         * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType
         *      MDN
         * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype DOM Living
         *      Standard
         * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Level-3-Core-DOM-createDocType DOM
         *      Level 3 Core
         * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM
         *      Level 2 Core
         * @see https://github.com/xmldom/xmldom/blob/master/CHANGELOG.md#050
         * @see https://www.w3.org/TR/DOM-Level-2-Core/#core-ID-Core-DocType-internalSubset
         * @prettierignore
         */
        createDocumentType: function(qualifiedName, publicId, systemId, internalSubset) {
          validateQualifiedName(qualifiedName);
          var node = new DocumentType(PDC);
          node.name = qualifiedName;
          node.nodeName = qualifiedName;
          node.publicId = publicId || "";
          node.systemId = systemId || "";
          node.internalSubset = internalSubset || "";
          node.childNodes = new NodeList();
          return node;
        },
        /**
         * Returns an HTML document, that might already have a basic DOM structure.
         *
         * __It behaves slightly different from the description in the living standard__:
         * - If the first argument is `false` no initial nodes are added (steps 3-7 in the specs are
         * omitted)
         * - `encoding`, `mode`, `origin`, `url` fields are currently not declared.
         *
         * @param {string | false} [title]
         * A string containing the title to give the new HTML document.
         * @returns {Document}
         * The HTML document.
         * @since WHATWG Living Standard.
         * @see {@link #createDocument}
         * @see https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument
         * @see https://dom.spec.whatwg.org/#html-document
         */
        createHTMLDocument: function(title) {
          var doc = new Document(PDC, { contentType: MIME_TYPE.HTML });
          doc.implementation = this;
          doc.childNodes = new NodeList();
          if (title !== false) {
            doc.doctype = this.createDocumentType("html");
            doc.doctype.ownerDocument = doc;
            doc.appendChild(doc.doctype);
            var htmlNode = doc.createElement("html");
            doc.appendChild(htmlNode);
            var headNode = doc.createElement("head");
            htmlNode.appendChild(headNode);
            if (typeof title === "string") {
              var titleNode = doc.createElement("title");
              titleNode.appendChild(doc.createTextNode(title));
              headNode.appendChild(titleNode);
            }
            htmlNode.appendChild(doc.createElement("body"));
          }
          return doc;
        }
      };
      function Node(symbol) {
        checkSymbol(symbol);
      }
      Node.prototype = {
        /**
         * The first child of this node.
         *
         * @type {Node | null}
         */
        firstChild: null,
        /**
         * The last child of this node.
         *
         * @type {Node | null}
         */
        lastChild: null,
        /**
         * The previous sibling of this node.
         *
         * @type {Node | null}
         */
        previousSibling: null,
        /**
         * The next sibling of this node.
         *
         * @type {Node | null}
         */
        nextSibling: null,
        /**
         * The parent node of this node.
         *
         * @type {Node | null}
         */
        parentNode: null,
        /**
         * The parent element of this node.
         *
         * @type {Element | null}
         */
        get parentElement() {
          return this.parentNode && this.parentNode.nodeType === this.ELEMENT_NODE ? this.parentNode : null;
        },
        /**
         * The child nodes of this node.
         *
         * @type {NodeList}
         */
        childNodes: null,
        /**
         * The document object associated with this node.
         *
         * @type {Document | null}
         */
        ownerDocument: null,
        /**
         * The value of this node.
         *
         * @type {string | null}
         */
        nodeValue: null,
        /**
         * The namespace URI of this node.
         *
         * @type {string | null}
         */
        namespaceURI: null,
        /**
         * The prefix of the namespace for this node.
         *
         * @type {string | null}
         */
        prefix: null,
        /**
         * The local part of the qualified name of this node.
         *
         * @type {string | null}
         */
        localName: null,
        /**
         * The baseURI is currently always `about:blank`,
         * since that's what happens when you create a document from scratch.
         *
         * @type {'about:blank'}
         */
        baseURI: "about:blank",
        /**
         * Is true if this node is part of a document.
         *
         * @type {boolean}
         */
        get isConnected() {
          var rootNode = this.getRootNode();
          return rootNode && rootNode.nodeType === rootNode.DOCUMENT_NODE;
        },
        /**
         * Checks whether `other` is an inclusive descendant of this node.
         *
         * @param {Node | null | undefined} other
         * The node to check.
         * @returns {boolean}
         * True if `other` is an inclusive descendant of this node; false otherwise.
         * @see https://dom.spec.whatwg.org/#dom-node-contains
         */
        contains: function(other) {
          if (!other) return false;
          var parent = other;
          do {
            if (this === parent) return true;
            parent = parent.parentNode;
          } while (parent);
          return false;
        },
        /**
         * @typedef GetRootNodeOptions
         * @property {boolean} [composed=false]
         */
        /**
         * Searches for the root node of this node.
         *
         * **This behavior is slightly different from the in the specs**:
         * - ignores `options.composed`, since `ShadowRoot`s are unsupported, always returns root.
         *
         * @param {GetRootNodeOptions} [options]
         * @returns {Node}
         * Root node.
         * @see https://dom.spec.whatwg.org/#dom-node-getrootnode
         * @see https://dom.spec.whatwg.org/#concept-shadow-including-root
         */
        getRootNode: function(options) {
          var parent = this;
          do {
            if (!parent.parentNode) {
              return parent;
            }
            parent = parent.parentNode;
          } while (parent);
        },
        /**
         * Checks whether the given node is equal to this node.
         *
         * Two nodes are equal when they have the same type, defining characteristics (for the type),
         * and the same childNodes. The comparison is iterative to avoid stack overflows on
         * deeply-nested trees. Attribute nodes of each Element pair are also pushed onto the stack
         * and compared the same way.
         *
         * @param {Node} [otherNode]
         * @returns {boolean}
         * @see https://dom.spec.whatwg.org/#concept-node-equals
         * @see ../docs/walk-dom.md.
         */
        isEqualNode: function(otherNode) {
          if (!otherNode) return false;
          var stack = [{ node: this, other: otherNode }];
          while (stack.length > 0) {
            var pair = stack.pop();
            var node = pair.node;
            var other = pair.other;
            if (node.nodeType !== other.nodeType) return false;
            switch (node.nodeType) {
              case node.DOCUMENT_TYPE_NODE:
                if (node.name !== other.name) return false;
                if (node.publicId !== other.publicId) return false;
                if (node.systemId !== other.systemId) return false;
                break;
              case node.ELEMENT_NODE:
                if (node.namespaceURI !== other.namespaceURI) return false;
                if (node.prefix !== other.prefix) return false;
                if (node.localName !== other.localName) return false;
                if (node.attributes.length !== other.attributes.length) return false;
                for (var i = 0; i < node.attributes.length; i++) {
                  var attr = node.attributes.item(i);
                  var otherAttr = other.getAttributeNodeNS(attr.namespaceURI, attr.localName);
                  if (!otherAttr) return false;
                  stack.push({ node: attr, other: otherAttr });
                }
                break;
              case node.ATTRIBUTE_NODE:
                if (node.namespaceURI !== other.namespaceURI) return false;
                if (node.localName !== other.localName) return false;
                if (node.value !== other.value) return false;
                break;
              case node.PROCESSING_INSTRUCTION_NODE:
                if (node.target !== other.target || node.data !== other.data) return false;
                break;
              case node.TEXT_NODE:
              case node.CDATA_SECTION_NODE:
              case node.COMMENT_NODE:
                if (node.data !== other.data) return false;
                break;
            }
            if (node.childNodes.length !== other.childNodes.length) return false;
            for (var i = node.childNodes.length - 1; i >= 0; i--) {
              stack.push({ node: node.childNodes[i], other: other.childNodes[i] });
            }
          }
          return true;
        },
        /**
         * Checks whether or not the given node is this node.
         *
         * @param {Node} [otherNode]
         */
        isSameNode: function(otherNode) {
          return this === otherNode;
        },
        /**
         * Inserts a node before a reference node as a child of this node.
         *
         * @param {Node} newChild
         * The new child node to be inserted.
         * @param {Node | null} refChild
         * The reference node before which newChild will be inserted.
         * @returns {Node}
         * The new child node successfully inserted.
         * @throws {DOMException}
         * Throws a DOMException if inserting the node would result in a DOM tree that is not
         * well-formed, or if `child` is provided but is not a child of `parent`.
         * See {@link _insertBefore} for more details.
         * @since Modified in DOM L2
         */
        insertBefore: function(newChild, refChild) {
          return _insertBefore(this, newChild, refChild);
        },
        /**
         * Replaces an old child node with a new child node within this node.
         *
         * @param {Node} newChild
         * The new node that is to replace the old node.
         * If it already exists in the DOM, it is removed from its original position.
         * @param {Node} oldChild
         * The existing child node to be replaced.
         * @returns {Node}
         * Returns the replaced child node.
         * @throws {DOMException}
         * Throws a DOMException if replacing the node would result in a DOM tree that is not
         * well-formed, or if `oldChild` is not a child of `this`.
         * This can also occur if the pre-replacement validity assertion fails.
         * See {@link _insertBefore}, {@link Node.removeChild}, and
         * {@link assertPreReplacementValidityInDocument} for more details.
         * @see https://dom.spec.whatwg.org/#concept-node-replace
         */
        replaceChild: function(newChild, oldChild) {
          _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument);
          if (oldChild) {
            this.removeChild(oldChild);
          }
        },
        /**
         * Removes an existing child node from this node.
         *
         * @param {Node} oldChild
         * The child node to be removed.
         * @returns {Node}
         * Returns the removed child node.
         * @throws {DOMException}
         * Throws a DOMException if `oldChild` is not a child of `this`.
         * See {@link _removeChild} for more details.
         */
        removeChild: function(oldChild) {
          return _removeChild(this, oldChild);
        },
        /**
         * Appends a child node to this node.
         *
         * @param {Node} newChild
         * The child node to be appended to this node.
         * If it already exists in the DOM, it is removed from its original position.
         * @returns {Node}
         * Returns the appended child node.
         * @throws {DOMException}
         * Throws a DOMException if appending the node would result in a DOM tree that is not
         * well-formed, or if `newChild` is not a valid Node.
         * See {@link insertBefore} for more details.
         */
        appendChild: function(newChild) {
          return this.insertBefore(newChild, null);
        },
        /**
         * Determines whether this node has any child nodes.
         *
         * @returns {boolean}
         * Returns true if this node has any child nodes, and false otherwise.
         */
        hasChildNodes: function() {
          return this.firstChild != null;
        },
        /**
         * Creates a copy of the calling node.
         *
         * @param {boolean} deep
         * If true, the contents of the node are recursively copied.
         * If false, only the node itself (and its attributes, if it is an element) are copied.
         * @returns {Node}
         * Returns the newly created copy of the node.
         * @throws {DOMException}
         * May throw a DOMException if operations within {@link Element#setAttributeNode} or
         * {@link Node#appendChild} (which are potentially invoked in this method) do not meet their
         * specific constraints.
         * @see {@link cloneNode}
         */
        cloneNode: function(deep) {
          return cloneNode(this.ownerDocument || this, this, deep);
        },
        /**
         * Puts the specified node and all of its subtree into a "normalized" form. In a normalized
         * subtree, no text nodes in the subtree are empty and there are no adjacent text nodes.
         *
         * Specifically, this method merges any adjacent text nodes (i.e., nodes for which `nodeType`
         * is `TEXT_NODE`) into a single node with the combined data. It also removes any empty text
         * nodes.
         *
         * This method iterativly traverses all child nodes to normalize all descendent nodes within
         * the subtree.
         *
         * @throws {DOMException}
         * May throw a DOMException if operations within removeChild or appendData (which are
         * potentially invoked in this method) do not meet their specific constraints.
         * @since Modified in DOM Level 2
         * @see {@link Node.removeChild}
         * @see {@link CharacterData.appendData}
         * @see ../docs/walk-dom.md.
         */
        normalize: function() {
          walkDOM(this, null, {
            enter: function(node) {
              var child = node.firstChild;
              while (child) {
                var next = child.nextSibling;
                if (next !== null && next.nodeType === TEXT_NODE && child.nodeType === TEXT_NODE) {
                  node.removeChild(next);
                  child.appendData(next.data);
                } else {
                  child = next;
                }
              }
              return true;
            }
          });
        },
        /**
         * Checks whether the DOM implementation implements a specific feature and its version.
         *
         * @deprecated
         * Since `DOMImplementation.hasFeature` is deprecated and always returns true.
         * @param {string} feature
         * The package name of the feature to test. This is the same name that can be passed to the
         * method `hasFeature` on `DOMImplementation`.
         * @param {string} version
         * This is the version number of the package name to test.
         * @returns {boolean}
         * Returns true in all cases in the current implementation.
         * @since Introduced in DOM Level 2
         * @see {@link DOMImplementation.hasFeature}
         */
        isSupported: function(feature, version) {
          return this.ownerDocument.implementation.hasFeature(feature, version);
        },
        /**
         * Look up the prefix associated to the given namespace URI, starting from this node.
         * **The default namespace declarations are ignored by this method.**
         * See Namespace Prefix Lookup for details on the algorithm used by this method.
         *
         * **This behavior is different from the in the specs**:
         * - no node type specific handling
         * - uses the internal attribute _nsMap for resolving namespaces that is updated when changing attributes
         *
         * @param {string | null} namespaceURI
         * The namespace URI for which to find the associated prefix.
         * @returns {string | null}
         * The associated prefix, if found; otherwise, null.
         * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespacePrefix
         * @see https://www.w3.org/TR/DOM-Level-3-Core/namespaces-algorithms.html#lookupNamespacePrefixAlgo
         * @see https://dom.spec.whatwg.org/#dom-node-lookupprefix
         * @see https://github.com/xmldom/xmldom/issues/322
         * @prettierignore
         */
        lookupPrefix: function(namespaceURI) {
          var el = this;
          while (el) {
            var map = el._nsMap;
            if (map) {
              for (var n in map) {
                if (hasOwn(map, n) && map[n] === namespaceURI) {
                  return n;
                }
              }
            }
            el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
          }
          return null;
        },
        /**
         * This function is used to look up the namespace URI associated with the given prefix,
         * starting from this node.
         *
         * **This behavior is different from the in the specs**:
         * - no node type specific handling
         * - uses the internal attribute _nsMap for resolving namespaces that is updated when changing attributes
         *
         * @param {string | null} prefix
         * The prefix for which to find the associated namespace URI.
         * @returns {string | null}
         * The associated namespace URI, if found; otherwise, null.
         * @since DOM Level 3
         * @see https://dom.spec.whatwg.org/#dom-node-lookupnamespaceuri
         * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespaceURI
         * @prettierignore
         */
        lookupNamespaceURI: function(prefix) {
          var el = this;
          while (el) {
            var map = el._nsMap;
            if (map) {
              if (hasOwn(map, prefix)) {
                return map[prefix];
              }
            }
            el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
          }
          return null;
        },
        /**
         * Determines whether the given namespace URI is the default namespace.
         *
         * The function works by looking up the prefix associated with the given namespace URI. If no
         * prefix is found (i.e., the namespace URI is not registered in the namespace map of this
         * node or any of its ancestors), it returns `true`, implying the namespace URI is considered
         * the default.
         *
         * **This behavior is different from the in the specs**:
         * - no node type specific handling
         * - uses the internal attribute _nsMap for resolving namespaces that is updated when changing attributes
         *
         * @param {string | null} namespaceURI
         * The namespace URI to be checked.
         * @returns {boolean}
         * Returns true if the given namespace URI is the default namespace, false otherwise.
         * @since DOM Level 3
         * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-isDefaultNamespace
         * @see https://dom.spec.whatwg.org/#dom-node-isdefaultnamespace
         * @prettierignore
         */
        isDefaultNamespace: function(namespaceURI) {
          var prefix = this.lookupPrefix(namespaceURI);
          return prefix == null;
        },
        /**
         * Compares the reference node with a node with regard to their position in the document and
         * according to the document order.
         *
         * @param {Node} other
         * The node to compare the reference node to.
         * @returns {number}
         * Returns how the node is positioned relatively to the reference node according to the
         * bitmask. 0 if reference node and given node are the same.
         * @since DOM Level 3
         * @see https://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#Node3-compare
         * @see https://dom.spec.whatwg.org/#dom-node-comparedocumentposition
         */
        compareDocumentPosition: function(other) {
          if (this === other) return 0;
          var node1 = other;
          var node2 = this;
          var attr1 = null;
          var attr2 = null;
          if (node1 instanceof Attr) {
            attr1 = node1;
            node1 = attr1.ownerElement;
          }
          if (node2 instanceof Attr) {
            attr2 = node2;
            node2 = attr2.ownerElement;
            if (attr1 && node1 && node2 === node1) {
              for (var i = 0, attr; attr = node2.attributes[i]; i++) {
                if (attr === attr1)
                  return DocumentPosition.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC + DocumentPosition.DOCUMENT_POSITION_PRECEDING;
                if (attr === attr2)
                  return DocumentPosition.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC + DocumentPosition.DOCUMENT_POSITION_FOLLOWING;
              }
            }
          }
          if (!node1 || !node2 || node2.ownerDocument !== node1.ownerDocument) {
            return DocumentPosition.DOCUMENT_POSITION_DISCONNECTED + DocumentPosition.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC + (docGUID(node2.ownerDocument) > docGUID(node1.ownerDocument) ? DocumentPosition.DOCUMENT_POSITION_FOLLOWING : DocumentPosition.DOCUMENT_POSITION_PRECEDING);
          }
          if (attr2 && node1 === node2) {
            return DocumentPosition.DOCUMENT_POSITION_CONTAINS + DocumentPosition.DOCUMENT_POSITION_PRECEDING;
          }
          if (attr1 && node1 === node2) {
            return DocumentPosition.DOCUMENT_POSITION_CONTAINED_BY + DocumentPosition.DOCUMENT_POSITION_FOLLOWING;
          }
          var chain1 = [];
          var ancestor1 = node1.parentNode;
          while (ancestor1) {
            if (!attr2 && ancestor1 === node2) {
              return DocumentPosition.DOCUMENT_POSITION_CONTAINED_BY + DocumentPosition.DOCUMENT_POSITION_FOLLOWING;
            }
            chain1.push(ancestor1);
            ancestor1 = ancestor1.parentNode;
          }
          chain1.reverse();
          var chain2 = [];
          var ancestor2 = node2.parentNode;
          while (ancestor2) {
            if (!attr1 && ancestor2 === node1) {
              return DocumentPosition.DOCUMENT_POSITION_CONTAINS + DocumentPosition.DOCUMENT_POSITION_PRECEDING;
            }
            chain2.push(ancestor2);
            ancestor2 = ancestor2.parentNode;
          }
          chain2.reverse();
          var ca = commonAncestor(chain1, chain2);
          for (var n in ca.childNodes) {
            var child = ca.childNodes[n];
            if (child === node2) return DocumentPosition.DOCUMENT_POSITION_FOLLOWING;
            if (child === node1) return DocumentPosition.DOCUMENT_POSITION_PRECEDING;
            if (chain2.indexOf(child) >= 0) return DocumentPosition.DOCUMENT_POSITION_FOLLOWING;
            if (chain1.indexOf(child) >= 0) return DocumentPosition.DOCUMENT_POSITION_PRECEDING;
          }
          return 0;
        }
      };
      function _xmlEncoder(c) {
        return c == "<" && "&lt;" || c == ">" && "&gt;" || c == "&" && "&amp;" || c == '"' && "&quot;" || "&#" + c.charCodeAt() + ";";
      }
      copy(NodeType, Node);
      copy(NodeType, Node.prototype);
      copy(DocumentPosition, Node);
      copy(DocumentPosition, Node.prototype);
      function _visitNode(node, callback) {
        walkDOM(node, null, {
          enter: function(n) {
            return callback(n) ? walkDOM.STOP : true;
          }
        });
      }
      function walkDOM(node, context, callbacks) {
        var stack = [{ node, context, phase: walkDOM.ENTER }];
        while (stack.length > 0) {
          var frame = stack.pop();
          if (frame.phase === walkDOM.ENTER) {
            var childContext = callbacks.enter(frame.node, frame.context);
            if (childContext === walkDOM.STOP) {
              return walkDOM.STOP;
            }
            stack.push({ node: frame.node, context: childContext, phase: walkDOM.EXIT });
            if (childContext === null || childContext === void 0) {
              continue;
            }
            var child = frame.node.lastChild;
            while (child) {
              stack.push({ node: child, context: childContext, phase: walkDOM.ENTER });
              child = child.previousSibling;
            }
          } else {
            if (callbacks.exit) {
              callbacks.exit(frame.node, frame.context);
            }
          }
        }
      }
      walkDOM.STOP = /* @__PURE__ */ Symbol("walkDOM.STOP");
      walkDOM.ENTER = 0;
      walkDOM.EXIT = 1;
      function Document(symbol, options) {
        checkSymbol(symbol);
        var opt = options || {};
        this.ownerDocument = this;
        this.contentType = opt.contentType || MIME_TYPE.XML_APPLICATION;
        this.type = isHTMLMimeType(this.contentType) ? "html" : "xml";
      }
      function _onAddAttribute(doc, el, newAttr) {
        doc && doc._inc++;
        var ns = newAttr.namespaceURI;
        if (ns === NAMESPACE.XMLNS) {
          el._nsMap[newAttr.prefix ? newAttr.localName : ""] = newAttr.value;
        }
      }
      function _onRemoveAttribute(doc, el, newAttr, remove) {
        doc && doc._inc++;
        var ns = newAttr.namespaceURI;
        if (ns === NAMESPACE.XMLNS) {
          delete el._nsMap[newAttr.prefix ? newAttr.localName : ""];
        }
      }
      function _onUpdateChild(doc, parent, newChild) {
        if (doc && doc._inc) {
          doc._inc++;
          var childNodes = parent.childNodes;
          if (newChild && !newChild.nextSibling) {
            childNodes[childNodes.length++] = newChild;
          } else {
            var child = parent.firstChild;
            var i = 0;
            while (child) {
              childNodes[i++] = child;
              child = child.nextSibling;
            }
            childNodes.length = i;
            delete childNodes[childNodes.length];
          }
        }
      }
      function _removeChild(parentNode, child) {
        if (parentNode !== child.parentNode) {
          throw new DOMException(DOMException.NOT_FOUND_ERR, "child's parent is not parent");
        }
        var oldPreviousSibling = child.previousSibling;
        var oldNextSibling = child.nextSibling;
        if (oldPreviousSibling) {
          oldPreviousSibling.nextSibling = oldNextSibling;
        } else {
          parentNode.firstChild = oldNextSibling;
        }
        if (oldNextSibling) {
          oldNextSibling.previousSibling = oldPreviousSibling;
        } else {
          parentNode.lastChild = oldPreviousSibling;
        }
        _onUpdateChild(parentNode.ownerDocument, parentNode);
        child.parentNode = null;
        child.previousSibling = null;
        child.nextSibling = null;
        return child;
      }
      function hasValidParentNodeType(node) {
        return node && (node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.ELEMENT_NODE);
      }
      function hasInsertableNodeType(node) {
        return node && (node.nodeType === Node.CDATA_SECTION_NODE || node.nodeType === Node.COMMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.DOCUMENT_TYPE_NODE || node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.PROCESSING_INSTRUCTION_NODE || node.nodeType === Node.TEXT_NODE);
      }
      function isDocTypeNode(node) {
        return node && node.nodeType === Node.DOCUMENT_TYPE_NODE;
      }
      function isElementNode(node) {
        return node && node.nodeType === Node.ELEMENT_NODE;
      }
      function isTextNode(node) {
        return node && node.nodeType === Node.TEXT_NODE;
      }
      function isElementInsertionPossible(doc, child) {
        var parentChildNodes = doc.childNodes || [];
        if (find(parentChildNodes, isElementNode) || isDocTypeNode(child)) {
          return false;
        }
        var docTypeNode = find(parentChildNodes, isDocTypeNode);
        return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child));
      }
      function isElementReplacementPossible(doc, child) {
        var parentChildNodes = doc.childNodes || [];
        function hasElementChildThatIsNotChild(node) {
          return isElementNode(node) && node !== child;
        }
        if (find(parentChildNodes, hasElementChildThatIsNotChild)) {
          return false;
        }
        var docTypeNode = find(parentChildNodes, isDocTypeNode);
        return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child));
      }
      function assertPreInsertionValidity1to5(parent, node, child) {
        if (!hasValidParentNodeType(parent)) {
          throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Unexpected parent node type " + parent.nodeType);
        }
        if (child && child.parentNode !== parent) {
          throw new DOMException(DOMException.NOT_FOUND_ERR, "child not in parent");
        }
        if (
          // 4. If `node` is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException.
          !hasInsertableNodeType(node) || // 5. If either `node` is a Text node and `parent` is a document,
          // the sax parser currently adds top level text nodes, this will be fixed in 0.9.0
          // || (node.nodeType === Node.TEXT_NODE && parent.nodeType === Node.DOCUMENT_NODE)
          // or `node` is a doctype and `parent` is not a document, then throw a "HierarchyRequestError" DOMException.
          isDocTypeNode(node) && parent.nodeType !== Node.DOCUMENT_NODE
        ) {
          throw new DOMException(
            DOMException.HIERARCHY_REQUEST_ERR,
            "Unexpected node type " + node.nodeType + " for parent node type " + parent.nodeType
          );
        }
      }
      function assertPreInsertionValidityInDocument(parent, node, child) {
        var parentChildNodes = parent.childNodes || [];
        var nodeChildNodes = node.childNodes || [];
        if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
          var nodeChildElements = nodeChildNodes.filter(isElementNode);
          if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) {
            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "More than one element or text in fragment");
          }
          if (nodeChildElements.length === 1 && !isElementInsertionPossible(parent, child)) {
            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Element in fragment can not be inserted before doctype");
          }
        }
        if (isElementNode(node)) {
          if (!isElementInsertionPossible(parent, child)) {
            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Only one element can be added and only after doctype");
          }
        }
        if (isDocTypeNode(node)) {
          if (find(parentChildNodes, isDocTypeNode)) {
            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Only one doctype is allowed");
          }
          var parentElementChild = find(parentChildNodes, isElementNode);
          if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) {
            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Doctype can only be inserted before an element");
          }
          if (!child && parentElementChild) {
            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Doctype can not be appended since element is present");
          }
        }
      }
      function assertPreReplacementValidityInDocument(parent, node, child) {
        var parentChildNodes = parent.childNodes || [];
        var nodeChildNodes = node.childNodes || [];
        if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
          var nodeChildElements = nodeChildNodes.filter(isElementNode);
          if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) {
            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "More than one element or text in fragment");
          }
          if (nodeChildElements.length === 1 && !isElementReplacementPossible(parent, child)) {
            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Element in fragment can not be inserted before doctype");
          }
        }
        if (isElementNode(node)) {
          if (!isElementReplacementPossible(parent, child)) {
            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Only one element can be added and only after doctype");
          }
        }
        if (isDocTypeNode(node)) {
          let hasDoctypeChildThatIsNotChild = function(node2) {
            return isDocTypeNode(node2) && node2 !== child;
          };
          if (find(parentChildNodes, hasDoctypeChildThatIsNotChild)) {
            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Only one doctype is allowed");
          }
          var parentElementChild = find(parentChildNodes, isElementNode);
          if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) {
            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Doctype can only be inserted before an element");
          }
        }
      }
      function _insertBefore(parent, node, child, _inDocumentAssertion) {
        assertPreInsertionValidity1to5(parent, node, child);
        if (parent.nodeType === Node.DOCUMENT_NODE) {
          (_inDocumentAssertion || assertPreInsertionValidityInDocument)(parent, node, child);
        }
        var cp = node.parentNode;
        if (cp) {
          cp.removeChild(node);
        }
        if (node.nodeType === DOCUMENT_FRAGMENT_NODE) {
          var newFirst = node.firstChild;
          if (newFirst == null) {
            return node;
          }
          var newLast = node.lastChild;
        } else {
          newFirst = newLast = node;
        }
        var pre = child ? child.previousSibling : parent.lastChild;
        newFirst.previousSibling = pre;
        newLast.nextSibling = child;
        if (pre) {
          pre.nextSibling = newFirst;
        } else {
          parent.firstChild = newFirst;
        }
        if (child == null) {
          parent.lastChild = newLast;
        } else {
          child.previousSibling = newLast;
        }
        do {
          newFirst.parentNode = parent;
        } while (newFirst !== newLast && (newFirst = newFirst.nextSibling));
        _onUpdateChild(parent.ownerDocument || parent, parent, node);
        if (node.nodeType == DOCUMENT_FRAGMENT_NODE) {
          node.firstChild = node.lastChild = null;
        }
        return node;
      }
      Document.prototype = {
        /**
         * The implementation that created this document.
         *
         * @type DOMImplementation
         * @readonly
         */
        implementation: null,
        nodeName: "#document",
        nodeType: DOCUMENT_NODE,
        /**
         * The DocumentType node of the document.
         *
         * @type DocumentType
         * @readonly
         */
        doctype: null,
        documentElement: null,
        _inc: 1,
        insertBefore: function(newChild, refChild) {
          if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) {
            var child = newChild.firstChild;
            while (child) {
              var next = child.nextSibling;
              this.insertBefore(child, refChild);
              child = next;
            }
            return newChild;
          }
          _insertBefore(this, newChild, refChild);
          newChild.ownerDocument = this;
          if (this.documentElement === null && newChild.nodeType === ELEMENT_NODE) {
            this.documentElement = newChild;
          }
          return newChild;
        },
        removeChild: function(oldChild) {
          var removed = _removeChild(this, oldChild);
          if (removed === this.documentElement) {
            this.documentElement = null;
          }
          return removed;
        },
        replaceChild: function(newChild, oldChild) {
          _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument);
          newChild.ownerDocument = this;
          if (oldChild) {
            this.removeChild(oldChild);
          }
          if (isElementNode(newChild)) {
            this.documentElement = newChild;
          }
        },
        /**
         * Imports a node from another document into this document, creating a new copy owned by this
         * document. The source node and its subtree are not modified.
         *
         * @param {Node} importedNode
         * The node to import.
         * @param {boolean} deep
         * If true, the contents of the node are recursively imported.
         * If false, only the node itself (and its attributes, if it is an element) are imported.
         * @returns {Node}
         * Returns the newly created import of the node.
         * @see {@link importNode}
         * @see {@link https://dom.spec.whatwg.org/#dom-document-importnode}
         */
        importNode: function(importedNode, deep) {
          return importNode(this, importedNode, deep);
        },
        // Introduced in DOM Level 2:
        getElementById: function(id) {
          var rtv = null;
          _visitNode(this.documentElement, function(node) {
            if (node.nodeType == ELEMENT_NODE) {
              if (node.getAttribute("id") == id) {
                rtv = node;
                return true;
              }
            }
          });
          return rtv;
        },
        /**
         * Creates a new `Element` that is owned by this `Document`.
         * In HTML Documents `localName` is the lower cased `tagName`,
         * otherwise no transformation is being applied.
         * When `contentType` implies the HTML namespace, it will be set as `namespaceURI`.
         *
         * __This implementation differs from the specification:__ - The provided name is not checked
         * against the `Name` production,
         * so no related error will be thrown.
         * - There is no interface `HTMLElement`, it is always an `Element`.
         * - There is no support for a second argument to indicate using custom elements.
         *
         * @param {string} tagName
         * @returns {Element}
         * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
         * @see https://dom.spec.whatwg.org/#dom-document-createelement
         * @see https://dom.spec.whatwg.org/#concept-create-element
         */
        createElement: function(tagName) {
          var node = new Element(PDC);
          node.ownerDocument = this;
          if (this.type === "html") {
            tagName = tagName.toLowerCase();
          }
          if (hasDefaultHTMLNamespace(this.contentType)) {
            node.namespaceURI = NAMESPACE.HTML;
          }
          node.nodeName = tagName;
          node.tagName = tagName;
          node.localName = tagName;
          node.childNodes = new NodeList();
          var attrs = node.attributes = new NamedNodeMap();
          attrs._ownerElement = node;
          return node;
        },
        /**
         * @returns {DocumentFragment}
         */
        createDocumentFragment: function() {
          var node = new DocumentFragment(PDC);
          node.ownerDocument = this;
          node.childNodes = new NodeList();
          return node;
        },
        /**
         * @param {string} data
         * @returns {Text}
         */
        createTextNode: function(data) {
          var node = new Text(PDC);
          node.ownerDocument = this;
          node.childNodes = new NodeList();
          node.appendData(data);
          return node;
        },
        /**
         * @param {string} data
         * @returns {Comment}
         * @see https://dom.spec.whatwg.org/#dom-document-createcomment
         * @see https://www.w3.org/TR/xml/#NT-Comment XML 1.0 production [15]
         * @see https://www.w3.org/TR/DOM-Parsing/#dfn-concept-serialize-xml §3.2.1.3
         *
         *      Note: no validation is performed at creation time. When the resulting document is
         *      serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError`
         *      if the comment data contains `--` anywhere, ends with `-`, or contains characters
         *      outside the XML Char production (W3C DOM Parsing §3.2.1.3). Without that option the
         *      data is emitted verbatim.
         */
        createComment: function(data) {
          var node = new Comment(PDC);
          node.ownerDocument = this;
          node.childNodes = new NodeList();
          node.appendData(data);
          return node;
        },
        /**
         * Returns a new CDATASection node whose data is `data`.
         *
         * __This implementation differs from the specification:__ - calling this method on an HTML
         * document does not throw `NotSupportedError`.
         *
         * @param {string} data
         * @returns {CDATASection}
         * @throws {DOMException}
         * With code `INVALID_CHARACTER_ERR` if `data` contains `"]]>"`.
         * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/createCDATASection
         * @see https://dom.spec.whatwg.org/#dom-document-createcdatasection
         */
        createCDATASection: function(data) {
          if (data.indexOf("]]>") !== -1) {
            throw new DOMException(DOMException.INVALID_CHARACTER_ERR, 'data contains "]]>"');
          }
          var node = new CDATASection(PDC);
          node.ownerDocument = this;
          node.childNodes = new NodeList();
          node.appendData(data);
          return node;
        },
        /**
         * Returns a ProcessingInstruction node whose target is target and data is data.
         *
         * __This behavior is slightly different from the in the specs__:
         * - it does not do any input validation on the arguments and doesn't throw
         * "InvalidCharacterError".
         *
         * Note: When the resulting document is serialized with `requireWellFormed: true`, the
         * serializer throws `InvalidStateError` if `.target` contains `:` or is an ASCII
         * case-insensitive match for `"xml"`, or if `.data` contains `?>` or characters outside the
         * XML Char production (W3C DOM Parsing §3.2.1.7). Without that option the data is emitted
         * verbatim.
         *
         * @param {string} target
         * @param {string} data
         * @returns {ProcessingInstruction}
         * @see https://developer.mozilla.org/docs/Web/API/Document/createProcessingInstruction
         * @see https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction
         * @see https://www.w3.org/TR/DOM-Parsing/#dfn-concept-serialize-xml §3.2.1.7
         */
        createProcessingInstruction: function(target, data) {
          var node = new ProcessingInstruction(PDC);
          node.ownerDocument = this;
          node.childNodes = new NodeList();
          node.nodeName = node.target = target;
          node.nodeValue = node.data = data;
          return node;
        },
        /**
         * Creates an `Attr` node that is owned by this document.
         * In HTML Documents `localName` is the lower cased `name`,
         * otherwise no transformation is being applied.
         *
         * __This implementation differs from the specification:__ - The provided name is not checked
         * against the `Name` production,
         * so no related error will be thrown.
         *
         * @param {string} name
         * @returns {Attr}
         * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/createAttribute
         * @see https://dom.spec.whatwg.org/#dom-document-createattribute
         */
        createAttribute: function(name2) {
          if (!g.QName_exact.test(name2)) {
            throw new DOMException(DOMException.INVALID_CHARACTER_ERR, 'invalid character in name "' + name2 + '"');
          }
          if (this.type === "html") {
            name2 = name2.toLowerCase();
          }
          return this._createAttribute(name2);
        },
        _createAttribute: function(name2) {
          var node = new Attr(PDC);
          node.ownerDocument = this;
          node.childNodes = new NodeList();
          node.name = name2;
          node.nodeName = name2;
          node.localName = name2;
          node.specified = true;
          return node;
        },
        /**
         * Creates an EntityReference object.
         * The current implementation does not fill the `childNodes` with those of the corresponding
         * `Entity`
         *
         * @deprecated
         * In DOM Level 4.
         * @param {string} name
         * The name of the entity to reference. No namespace well-formedness checks are performed.
         * @returns {EntityReference}
         * @throws {DOMException}
         * With code `INVALID_CHARACTER_ERR` when `name` is not valid.
         * @throws {DOMException}
         * with code `NOT_SUPPORTED_ERR` when the document is of type `html`
         * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-392B75AE
         */
        createEntityReference: function(name2) {
          if (!g.Name.test(name2)) {
            throw new DOMException(DOMException.INVALID_CHARACTER_ERR, 'not a valid xml name "' + name2 + '"');
          }
          if (this.type === "html") {
            throw new DOMException("document is an html document", DOMExceptionName.NotSupportedError);
          }
          var node = new EntityReference(PDC);
          node.ownerDocument = this;
          node.childNodes = new NodeList();
          node.nodeName = name2;
          return node;
        },
        // Introduced in DOM Level 2:
        /**
         * @param {string} namespaceURI
         * @param {string} qualifiedName
         * @returns {Element}
         */
        createElementNS: function(namespaceURI, qualifiedName) {
          var validated = validateAndExtract(namespaceURI, qualifiedName);
          var node = new Element(PDC);
          var attrs = node.attributes = new NamedNodeMap();
          node.childNodes = new NodeList();
          node.ownerDocument = this;
          node.nodeName = qualifiedName;
          node.tagName = qualifiedName;
          node.namespaceURI = validated[0];
          node.prefix = validated[1];
          node.localName = validated[2];
          attrs._ownerElement = node;
          return node;
        },
        // Introduced in DOM Level 2:
        /**
         * @param {string} namespaceURI
         * @param {string} qualifiedName
         * @returns {Attr}
         */
        createAttributeNS: function(namespaceURI, qualifiedName) {
          var validated = validateAndExtract(namespaceURI, qualifiedName);
          var node = new Attr(PDC);
          node.ownerDocument = this;
          node.childNodes = new NodeList();
          node.nodeName = qualifiedName;
          node.name = qualifiedName;
          node.specified = true;
          node.namespaceURI = validated[0];
          node.prefix = validated[1];
          node.localName = validated[2];
          return node;
        }
      };
      _extends(Document, Node);
      function Element(symbol) {
        checkSymbol(symbol);
        this._nsMap = /* @__PURE__ */ Object.create(null);
      }
      Element.prototype = {
        nodeType: ELEMENT_NODE,
        /**
         * The attributes of this element.
         *
         * @type {NamedNodeMap | null}
         */
        attributes: null,
        getQualifiedName: function() {
          return this.prefix ? this.prefix + ":" + this.localName : this.localName;
        },
        _isInHTMLDocumentAndNamespace: function() {
          return this.ownerDocument.type === "html" && this.namespaceURI === NAMESPACE.HTML;
        },
        /**
         * Implementaton of Level2 Core function hasAttributes.
         *
         * @returns {boolean}
         * True if attribute list is not empty.
         * @see https://www.w3.org/TR/DOM-Level-2-Core/#core-ID-NodeHasAttrs
         */
        hasAttributes: function() {
          return !!(this.attributes && this.attributes.length);
        },
        hasAttribute: function(name2) {
          return !!this.getAttributeNode(name2);
        },
        /**
         * Returns element’s first attribute whose qualified name is `name`, and `null`
         * if there is no such attribute.
         *
         * @param {string} name
         * @returns {string | null}
         */
        getAttribute: function(name2) {
          var attr = this.getAttributeNode(name2);
          return attr ? attr.value : null;
        },
        getAttributeNode: function(name2) {
          if (this._isInHTMLDocumentAndNamespace()) {
            name2 = name2.toLowerCase();
          }
          return this.attributes.getNamedItem(name2);
        },
        /**
         * Sets the value of element’s first attribute whose qualified name is qualifiedName to value.
         *
         * @param {string} name
         * @param {string} value
         */
        setAttribute: function(name2, value) {
          if (this._isInHTMLDocumentAndNamespace()) {
            name2 = name2.toLowerCase();
          }
          var attr = this.getAttributeNode(name2);
          if (attr) {
            attr.value = attr.nodeValue = "" + value;
          } else {
            attr = this.ownerDocument._createAttribute(name2);
            attr.value = attr.nodeValue = "" + value;
            this.setAttributeNode(attr);
          }
        },
        removeAttribute: function(name2) {
          var attr = this.getAttributeNode(name2);
          attr && this.removeAttributeNode(attr);
        },
        setAttributeNode: function(newAttr) {
          return this.attributes.setNamedItem(newAttr);
        },
        setAttributeNodeNS: function(newAttr) {
          return this.attributes.setNamedItemNS(newAttr);
        },
        removeAttributeNode: function(oldAttr) {
          return this.attributes.removeNamedItem(oldAttr.nodeName);
        },
        //get real attribute name,and remove it by removeAttributeNode
        removeAttributeNS: function(namespaceURI, localName) {
          var old = this.getAttributeNodeNS(namespaceURI, localName);
          old && this.removeAttributeNode(old);
        },
        hasAttributeNS: function(namespaceURI, localName) {
          return this.getAttributeNodeNS(namespaceURI, localName) != null;
        },
        /**
         * Returns element’s attribute whose namespace is `namespaceURI` and local name is
         * `localName`,
         * or `null` if there is no such attribute.
         *
         * @param {string} namespaceURI
         * @param {string} localName
         * @returns {string | null}
         */
        getAttributeNS: function(namespaceURI, localName) {
          var attr = this.getAttributeNodeNS(namespaceURI, localName);
          return attr ? attr.value : null;
        },
        /**
         * Sets the value of element’s attribute whose namespace is `namespaceURI` and local name is
         * `localName` to value.
         *
         * @param {string} namespaceURI
         * @param {string} qualifiedName
         * @param {string} value
         * @see https://dom.spec.whatwg.org/#dom-element-setattributens
         */
        setAttributeNS: function(namespaceURI, qualifiedName, value) {
          var validated = validateAndExtract(namespaceURI, qualifiedName);
          var localName = validated[2];
          var attr = this.getAttributeNodeNS(namespaceURI, localName);
          if (attr) {
            attr.value = attr.nodeValue = "" + value;
          } else {
            attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
            attr.value = attr.nodeValue = "" + value;
            this.setAttributeNode(attr);
          }
        },
        getAttributeNodeNS: function(namespaceURI, localName) {
          return this.attributes.getNamedItemNS(namespaceURI, localName);
        },
        /**
         * Returns a LiveNodeList of all child elements which have **all** of the given class name(s).
         *
         * Returns an empty list if `classNames` is an empty string or only contains HTML white space
         * characters.
         *
         * Warning: This returns a live LiveNodeList.
         * Changes in the DOM will reflect in the array as the changes occur.
         * If an element selected by this array no longer qualifies for the selector,
         * it will automatically be removed. Be aware of this for iteration purposes.
         *
         * @param {string} classNames
         * Is a string representing the class name(s) to match; multiple class names are separated by
         * (ASCII-)whitespace.
         * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName
         * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
         * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname
         */
        getElementsByClassName: function(classNames) {
          var classNamesSet = toOrderedSet(classNames);
          return new LiveNodeList(this, function(base) {
            var ls = [];
            if (classNamesSet.length > 0) {
              _visitNode(base, function(node) {
                if (node !== base && node.nodeType === ELEMENT_NODE) {
                  var nodeClassNames = node.getAttribute("class");
                  if (nodeClassNames) {
                    var matches = classNames === nodeClassNames;
                    if (!matches) {
                      var nodeClassNamesSet = toOrderedSet(nodeClassNames);
                      matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet));
                    }
                    if (matches) {
                      ls.push(node);
                    }
                  }
                }
              });
            }
            return ls;
          });
        },
        /**
         * Returns a LiveNodeList of elements with the given qualifiedName.
         * Searching for all descendants can be done by passing `*` as `qualifiedName`.
         *
         * All descendants of the specified element are searched, but not the element itself.
         * The returned list is live, which means it updates itself with the DOM tree automatically.
         * Therefore, there is no need to call `Element.getElementsByTagName()`
         * with the same element and arguments repeatedly if the DOM changes in between calls.
         *
         * When called on an HTML element in an HTML document,
         * `getElementsByTagName` lower-cases the argument before searching for it.
         * This is undesirable when trying to match camel-cased SVG elements (such as
         * `<linearGradient>`) in an HTML document.
         * Instead, use `Element.getElementsByTagNameNS()`,
         * which preserves the capitalization of the tag name.
         *
         * `Element.getElementsByTagName` is similar to `Document.getElementsByTagName()`,
         * except that it only searches for elements that are descendants of the specified element.
         *
         * @param {string} qualifiedName
         * @returns {LiveNodeList}
         * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
         * @see https://dom.spec.whatwg.org/#concept-getelementsbytagname
         */
        getElementsByTagName: function(qualifiedName) {
          var isHTMLDocument = (this.nodeType === DOCUMENT_NODE ? this : this.ownerDocument).type === "html";
          var lowerQualifiedName = qualifiedName.toLowerCase();
          return new LiveNodeList(this, function(base) {
            var ls = [];
            _visitNode(base, function(node) {
              if (node === base || node.nodeType !== ELEMENT_NODE) {
                return;
              }
              if (qualifiedName === "*") {
                ls.push(node);
              } else {
                var nodeQualifiedName = node.getQualifiedName();
                var matchingQName = isHTMLDocument && node.namespaceURI === NAMESPACE.HTML ? lowerQualifiedName : qualifiedName;
                if (nodeQualifiedName === matchingQName) {
                  ls.push(node);
                }
              }
            });
            return ls;
          });
        },
        getElementsByTagNameNS: function(namespaceURI, localName) {
          return new LiveNodeList(this, function(base) {
            var ls = [];
            _visitNode(base, function(node) {
              if (node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === "*" || node.namespaceURI === namespaceURI) && (localName === "*" || node.localName == localName)) {
                ls.push(node);
              }
            });
            return ls;
          });
        }
      };
      Document.prototype.getElementsByClassName = Element.prototype.getElementsByClassName;
      Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
      Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
      _extends(Element, Node);
      function Attr(symbol) {
        checkSymbol(symbol);
        this.namespaceURI = null;
        this.prefix = null;
        this.ownerElement = null;
      }
      Attr.prototype.nodeType = ATTRIBUTE_NODE;
      _extends(Attr, Node);
      function CharacterData(symbol) {
        checkSymbol(symbol);
      }
      CharacterData.prototype = {
        data: "",
        substringData: function(offset, count) {
          return this.data.substring(offset, offset + count);
        },
        appendData: function(text) {
          text = this.data + text;
          this.nodeValue = this.data = text;
          this.length = text.length;
        },
        insertData: function(offset, text) {
          this.replaceData(offset, 0, text);
        },
        deleteData: function(offset, count) {
          this.replaceData(offset, count, "");
        },
        replaceData: function(offset, count, text) {
          var start = this.data.substring(0, offset);
          var end = this.data.substring(offset + count);
          text = start + text + end;
          this.nodeValue = this.data = text;
          this.length = text.length;
        }
      };
      _extends(CharacterData, Node);
      function Text(symbol) {
        checkSymbol(symbol);
      }
      Text.prototype = {
        nodeName: "#text",
        nodeType: TEXT_NODE,
        splitText: function(offset) {
          var text = this.data;
          var newText = text.substring(offset);
          text = text.substring(0, offset);
          this.data = this.nodeValue = text;
          this.length = text.length;
          var newNode = this.ownerDocument.createTextNode(newText);
          if (this.parentNode) {
            this.parentNode.insertBefore(newNode, this.nextSibling);
          }
          return newNode;
        }
      };
      _extends(Text, CharacterData);
      function Comment(symbol) {
        checkSymbol(symbol);
      }
      Comment.prototype = {
        nodeName: "#comment",
        nodeType: COMMENT_NODE
      };
      _extends(Comment, CharacterData);
      function CDATASection(symbol) {
        checkSymbol(symbol);
      }
      CDATASection.prototype = {
        nodeName: "#cdata-section",
        nodeType: CDATA_SECTION_NODE
      };
      _extends(CDATASection, Text);
      function DocumentType(symbol) {
        checkSymbol(symbol);
      }
      DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
      _extends(DocumentType, Node);
      function Notation(symbol) {
        checkSymbol(symbol);
      }
      Notation.prototype.nodeType = NOTATION_NODE;
      _extends(Notation, Node);
      function Entity(symbol) {
        checkSymbol(symbol);
      }
      Entity.prototype.nodeType = ENTITY_NODE;
      _extends(Entity, Node);
      function EntityReference(symbol) {
        checkSymbol(symbol);
      }
      EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
      _extends(EntityReference, Node);
      function DocumentFragment(symbol) {
        checkSymbol(symbol);
      }
      DocumentFragment.prototype.nodeName = "#document-fragment";
      DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
      _extends(DocumentFragment, Node);
      function ProcessingInstruction(symbol) {
        checkSymbol(symbol);
      }
      ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
      _extends(ProcessingInstruction, CharacterData);
      function XMLSerializer2() {
      }
      XMLSerializer2.prototype.serializeToString = function(node, options) {
        return nodeSerializeToString.call(node, options);
      };
      Node.prototype.toString = nodeSerializeToString;
      function nodeSerializeToString(options) {
        var opts;
        if (typeof options === "function") {
          opts = { requireWellFormed: false, splitCDATASections: true, nodeFilter: options };
        } else if (options != null) {
          opts = {
            requireWellFormed: !!options.requireWellFormed,
            splitCDATASections: options.splitCDATASections !== false,
            nodeFilter: options.nodeFilter || null
          };
        } else {
          opts = { requireWellFormed: false, splitCDATASections: true, nodeFilter: null };
        }
        var buf = [];
        var refNode = this.nodeType === DOCUMENT_NODE && this.documentElement || this;
        var prefix = refNode.prefix;
        var uri = refNode.namespaceURI;
        if (uri && prefix == null) {
          var prefix = refNode.lookupPrefix(uri);
          if (prefix == null) {
            var visibleNamespaces = [
              { namespace: uri, prefix: null }
              //{namespace:uri,prefix:''}
            ];
          }
        }
        serializeToString(this, buf, visibleNamespaces, opts);
        return buf.join("");
      }
      function needNamespaceDefine(node, isHTML, visibleNamespaces) {
        var prefix = node.prefix || "";
        var uri = node.namespaceURI;
        if (!uri) {
          return false;
        }
        if (prefix === "xml" && uri === NAMESPACE.XML || uri === NAMESPACE.XMLNS) {
          return false;
        }
        var i = visibleNamespaces.length;
        while (i--) {
          var ns = visibleNamespaces[i];
          if (ns.prefix === prefix) {
            return ns.namespace !== uri;
          }
        }
        return true;
      }
      function addSerializedAttribute(buf, qualifiedName, value) {
        buf.push(" ", qualifiedName, '="', value.replace(/[<>&"\t\n\r]/g, _xmlEncoder), '"');
      }
      function serializeToString(node, buf, visibleNamespaces, opts) {
        if (!visibleNamespaces) {
          visibleNamespaces = [];
        }
        var nodeFilter = opts.nodeFilter;
        var requireWellFormed = opts.requireWellFormed;
        var splitCDATASections = opts.splitCDATASections;
        var doc = node.nodeType === DOCUMENT_NODE ? node : node.ownerDocument;
        var isHTML = doc.type === "html";
        walkDOM(
          node,
          { ns: visibleNamespaces },
          {
            enter: function(n, ctx) {
              var namespaces = ctx.ns;
              if (nodeFilter) {
                n = nodeFilter(n);
                if (n) {
                  if (typeof n == "string") {
                    buf.push(n);
                    return null;
                  }
                } else {
                  return null;
                }
              }
              switch (n.nodeType) {
                case ELEMENT_NODE:
                  var attrs = n.attributes;
                  var len = attrs.length;
                  var nodeName = n.tagName;
                  var prefixedNodeName = nodeName;
                  if (!isHTML && !n.prefix && n.namespaceURI) {
                    var defaultNS;
                    for (var ai = 0; ai < attrs.length; ai++) {
                      if (attrs.item(ai).name === "xmlns") {
                        defaultNS = attrs.item(ai).value;
                        break;
                      }
                    }
                    if (!defaultNS) {
                      for (var nsi = namespaces.length - 1; nsi >= 0; nsi--) {
                        var nsEntry = namespaces[nsi];
                        if (nsEntry.prefix === "" && nsEntry.namespace === n.namespaceURI) {
                          defaultNS = nsEntry.namespace;
                          break;
                        }
                      }
                    }
                    if (defaultNS !== n.namespaceURI) {
                      for (var nsi = namespaces.length - 1; nsi >= 0; nsi--) {
                        var nsEntry = namespaces[nsi];
                        if (nsEntry.namespace === n.namespaceURI) {
                          if (nsEntry.prefix) {
                            prefixedNodeName = nsEntry.prefix + ":" + nodeName;
                          }
                          break;
                        }
                      }
                    }
                  }
                  buf.push("<", prefixedNodeName);
                  var childNamespaces = namespaces.slice();
                  for (var i = 0; i < len; i++) {
                    var attr = attrs.item(i);
                    if (attr.prefix == "xmlns") {
                      childNamespaces.push({
                        prefix: attr.localName,
                        namespace: attr.value
                      });
                    } else if (attr.nodeName == "xmlns") {
                      childNamespaces.push({ prefix: "", namespace: attr.value });
                    }
                  }
                  for (var i = 0; i < len; i++) {
                    var attr = attrs.item(i);
                    if (needNamespaceDefine(attr, isHTML, childNamespaces)) {
                      var attrPrefix = attr.prefix || "";
                      var uri = attr.namespaceURI;
                      addSerializedAttribute(buf, attrPrefix ? "xmlns:" + attrPrefix : "xmlns", uri);
                      childNamespaces.push({ prefix: attrPrefix, namespace: uri });
                    }
                    var filteredAttr = nodeFilter ? nodeFilter(attr) : attr;
                    if (filteredAttr) {
                      if (typeof filteredAttr === "string") {
                        buf.push(filteredAttr);
                      } else {
                        addSerializedAttribute(buf, filteredAttr.name, filteredAttr.value);
                      }
                    }
                  }
                  if (nodeName === prefixedNodeName && needNamespaceDefine(n, isHTML, childNamespaces)) {
                    var nodePrefix = n.prefix || "";
                    var uri = n.namespaceURI;
                    addSerializedAttribute(buf, nodePrefix ? "xmlns:" + nodePrefix : "xmlns", uri);
                    childNamespaces.push({ prefix: nodePrefix, namespace: uri });
                  }
                  var canCloseTag = !n.firstChild;
                  if (canCloseTag && (isHTML || n.namespaceURI === NAMESPACE.HTML)) {
                    canCloseTag = isHTMLVoidElement(nodeName);
                  }
                  if (canCloseTag) {
                    buf.push("/>");
                    return null;
                  }
                  buf.push(">");
                  if (isHTML && isHTMLRawTextElement(nodeName)) {
                    var child = n.firstChild;
                    while (child) {
                      if (child.data) {
                        buf.push(child.data);
                      } else {
                        serializeToString(child, buf, childNamespaces.slice(), opts);
                      }
                      child = child.nextSibling;
                    }
                    buf.push("</", prefixedNodeName, ">");
                    return null;
                  }
                  return { ns: childNamespaces, tag: prefixedNodeName };
                case DOCUMENT_NODE:
                case DOCUMENT_FRAGMENT_NODE:
                  if (requireWellFormed && n.nodeType === DOCUMENT_NODE && n.documentElement == null) {
                    throw new DOMException("The Document has no documentElement", DOMExceptionName.InvalidStateError);
                  }
                  return { ns: namespaces };
                case ATTRIBUTE_NODE:
                  addSerializedAttribute(buf, n.name, n.value);
                  return null;
                case TEXT_NODE:
                  if (requireWellFormed && g.InvalidChar.test(n.data)) {
                    throw new DOMException(
                      "The Text node data contains characters outside the XML Char production",
                      DOMExceptionName.InvalidStateError
                    );
                  }
                  buf.push(n.data.replace(/[<&>]/g, _xmlEncoder));
                  return null;
                case CDATA_SECTION_NODE:
                  if (requireWellFormed && n.data.indexOf("]]>") !== -1) {
                    throw new DOMException('The CDATASection data contains "]]>"', DOMExceptionName.InvalidStateError);
                  }
                  if (splitCDATASections) {
                    buf.push(g.CDATA_START, n.data.replace(/]]>/g, "]]]]><![CDATA[>"), g.CDATA_END);
                  } else {
                    buf.push(g.CDATA_START, n.data, g.CDATA_END);
                  }
                  return null;
                case COMMENT_NODE:
                  if (requireWellFormed) {
                    if (g.InvalidChar.test(n.data)) {
                      throw new DOMException(
                        "The comment node data contains characters outside the XML Char production",
                        DOMExceptionName.InvalidStateError
                      );
                    }
                    if (n.data.indexOf("--") !== -1 || n.data[n.data.length - 1] === "-") {
                      throw new DOMException(
                        'The comment node data contains "--" or ends with "-"',
                        DOMExceptionName.InvalidStateError
                      );
                    }
                  }
                  buf.push(g.COMMENT_START, n.data, g.COMMENT_END);
                  return null;
                case DOCUMENT_TYPE_NODE:
                  var pubid = n.publicId;
                  var sysid = n.systemId;
                  if (requireWellFormed) {
                    if (pubid && !g.PubidLiteral_match.test(pubid)) {
                      throw new DOMException("DocumentType publicId is not a valid PubidLiteral", DOMExceptionName.InvalidStateError);
                    }
                    if (sysid && sysid !== "." && !g.SystemLiteral_match.test(sysid)) {
                      throw new DOMException("DocumentType systemId is not a valid SystemLiteral", DOMExceptionName.InvalidStateError);
                    }
                    if (n.internalSubset && n.internalSubset.indexOf("]>") !== -1) {
                      throw new DOMException('DocumentType internalSubset contains "]>"', DOMExceptionName.InvalidStateError);
                    }
                  }
                  buf.push(g.DOCTYPE_DECL_START, " ", n.name);
                  if (pubid) {
                    buf.push(" ", g.PUBLIC, " ", pubid);
                    if (sysid && sysid !== ".") {
                      buf.push(" ", sysid);
                    }
                  } else if (sysid && sysid !== ".") {
                    buf.push(" ", g.SYSTEM, " ", sysid);
                  }
                  if (n.internalSubset) {
                    buf.push(" [", n.internalSubset, "]");
                  }
                  buf.push(">");
                  return null;
                case PROCESSING_INSTRUCTION_NODE:
                  if (requireWellFormed) {
                    if (n.target.indexOf(":") !== -1 || n.target.toLowerCase() === "xml") {
                      throw new DOMException("The ProcessingInstruction target is not well-formed", DOMExceptionName.InvalidStateError);
                    }
                    if (g.InvalidChar.test(n.data)) {
                      throw new DOMException(
                        "The ProcessingInstruction data contains characters outside the XML Char production",
                        DOMExceptionName.InvalidStateError
                      );
                    }
                    if (n.data.indexOf("?>") !== -1) {
                      throw new DOMException('The ProcessingInstruction data contains "?>"', DOMExceptionName.InvalidStateError);
                    }
                  }
                  buf.push("<?", n.target, " ", n.data, "?>");
                  return null;
                case ENTITY_REFERENCE_NODE:
                  buf.push("&", n.nodeName, ";");
                  return null;
                //case ENTITY_NODE:
                //case NOTATION_NODE:
                default:
                  buf.push("??", n.nodeName);
                  return null;
              }
            },
            exit: function(n, childCtx) {
              if (childCtx && childCtx.tag) {
                buf.push("</", childCtx.tag, ">");
              }
            }
          }
        );
      }
      function importNode(doc, node, deep) {
        var destRoot;
        walkDOM(node, null, {
          enter: function(srcNode, destParent) {
            var destNode = srcNode.cloneNode(false);
            destNode.ownerDocument = doc;
            destNode.parentNode = null;
            if (destParent === null) {
              destRoot = destNode;
            } else {
              destParent.appendChild(destNode);
            }
            var shouldDeep = srcNode.nodeType === ATTRIBUTE_NODE || deep;
            return shouldDeep ? destNode : null;
          }
        });
        return destRoot;
      }
      function cloneNode(doc, node, deep) {
        var destRoot;
        walkDOM(node, null, {
          enter: function(srcNode, destParent) {
            var destNode = new srcNode.constructor(PDC);
            for (var n in srcNode) {
              if (hasOwn(srcNode, n)) {
                var v = srcNode[n];
                if (typeof v != "object") {
                  if (v != destNode[n]) {
                    destNode[n] = v;
                  }
                }
              }
            }
            if (srcNode.childNodes) {
              destNode.childNodes = new NodeList();
            }
            destNode.ownerDocument = doc;
            var shouldDeep = deep;
            switch (destNode.nodeType) {
              case ELEMENT_NODE:
                var attrs = srcNode.attributes;
                var attrs2 = destNode.attributes = new NamedNodeMap();
                var len = attrs.length;
                attrs2._ownerElement = destNode;
                for (var i = 0; i < len; i++) {
                  destNode.setAttributeNode(cloneNode(doc, attrs.item(i), true));
                }
                break;
              case ATTRIBUTE_NODE:
                shouldDeep = true;
            }
            if (destParent !== null) {
              destParent.appendChild(destNode);
            } else {
              destRoot = destNode;
            }
            return shouldDeep ? destNode : null;
          }
        });
        return destRoot;
      }
      function __set__(object, key, value) {
        object[key] = value;
      }
      function childrenRefresh(node) {
        var ls = [];
        var child = node.firstChild;
        while (child) {
          if (child.nodeType === ELEMENT_NODE) {
            ls.push(child);
          }
          child = child.nextSibling;
        }
        return ls;
      }
      try {
        if (Object.defineProperty) {
          Object.defineProperty(LiveNodeList.prototype, "length", {
            get: function() {
              _updateLiveList(this);
              return this.$$length;
            }
          });
          Object.defineProperty(Node.prototype, "textContent", {
            get: function() {
              if (this.nodeType === ELEMENT_NODE || this.nodeType === DOCUMENT_FRAGMENT_NODE) {
                var buf = [];
                walkDOM(this, null, {
                  enter: function(n) {
                    if (n.nodeType === ELEMENT_NODE || n.nodeType === DOCUMENT_FRAGMENT_NODE) {
                      return true;
                    }
                    if (n.nodeType === PROCESSING_INSTRUCTION_NODE || n.nodeType === COMMENT_NODE) {
                      return null;
                    }
                    buf.push(n.nodeValue);
                  }
                });
                return buf.join("");
              }
              return this.nodeValue;
            },
            set: function(data) {
              switch (this.nodeType) {
                case ELEMENT_NODE:
                case DOCUMENT_FRAGMENT_NODE:
                  while (this.firstChild) {
                    this.removeChild(this.firstChild);
                  }
                  if (data || String(data)) {
                    this.appendChild(this.ownerDocument.createTextNode(data));
                  }
                  break;
                default:
                  this.data = data;
                  this.value = data;
                  this.nodeValue = data;
              }
            }
          });
          Object.defineProperty(Element.prototype, "children", {
            get: function() {
              return new LiveNodeList(this, childrenRefresh);
            }
          });
          Object.defineProperty(Document.prototype, "children", {
            get: function() {
              return new LiveNodeList(this, childrenRefresh);
            }
          });
          Object.defineProperty(DocumentFragment.prototype, "children", {
            get: function() {
              return new LiveNodeList(this, childrenRefresh);
            }
          });
          __set__ = function(object, key, value) {
            object["$$" + key] = value;
          };
        }
      } catch (e) {
      }
      exports2._updateLiveList = _updateLiveList;
      exports2.Attr = Attr;
      exports2.CDATASection = CDATASection;
      exports2.CharacterData = CharacterData;
      exports2.Comment = Comment;
      exports2.Document = Document;
      exports2.DocumentFragment = DocumentFragment;
      exports2.DocumentType = DocumentType;
      exports2.DOMImplementation = DOMImplementation;
      exports2.Element = Element;
      exports2.Entity = Entity;
      exports2.EntityReference = EntityReference;
      exports2.LiveNodeList = LiveNodeList;
      exports2.NamedNodeMap = NamedNodeMap;
      exports2.Node = Node;
      exports2.NodeList = NodeList;
      exports2.Notation = Notation;
      exports2.Text = Text;
      exports2.ProcessingInstruction = ProcessingInstruction;
      exports2.walkDOM = walkDOM;
      exports2.XMLSerializer = XMLSerializer2;
    }
  });

  // node_modules/@xmldom/xmldom/lib/entities.js
  var require_entities = __commonJS({
    "node_modules/@xmldom/xmldom/lib/entities.js"(exports2) {
      "use strict";
      var freeze = require_conventions().freeze;
      exports2.XML_ENTITIES = freeze({
        amp: "&",
        apos: "'",
        gt: ">",
        lt: "<",
        quot: '"'
      });
      exports2.HTML_ENTITIES = freeze({
        Aacute: "\xC1",
        aacute: "\xE1",
        Abreve: "\u0102",
        abreve: "\u0103",
        ac: "\u223E",
        acd: "\u223F",
        acE: "\u223E\u0333",
        Acirc: "\xC2",
        acirc: "\xE2",
        acute: "\xB4",
        Acy: "\u0410",
        acy: "\u0430",
        AElig: "\xC6",
        aelig: "\xE6",
        af: "\u2061",
        Afr: "\u{1D504}",
        afr: "\u{1D51E}",
        Agrave: "\xC0",
        agrave: "\xE0",
        alefsym: "\u2135",
        aleph: "\u2135",
        Alpha: "\u0391",
        alpha: "\u03B1",
        Amacr: "\u0100",
        amacr: "\u0101",
        amalg: "\u2A3F",
        AMP: "&",
        amp: "&",
        And: "\u2A53",
        and: "\u2227",
        andand: "\u2A55",
        andd: "\u2A5C",
        andslope: "\u2A58",
        andv: "\u2A5A",
        ang: "\u2220",
        ange: "\u29A4",
        angle: "\u2220",
        angmsd: "\u2221",
        angmsdaa: "\u29A8",
        angmsdab: "\u29A9",
        angmsdac: "\u29AA",
        angmsdad: "\u29AB",
        angmsdae: "\u29AC",
        angmsdaf: "\u29AD",
        angmsdag: "\u29AE",
        angmsdah: "\u29AF",
        angrt: "\u221F",
        angrtvb: "\u22BE",
        angrtvbd: "\u299D",
        angsph: "\u2222",
        angst: "\xC5",
        angzarr: "\u237C",
        Aogon: "\u0104",
        aogon: "\u0105",
        Aopf: "\u{1D538}",
        aopf: "\u{1D552}",
        ap: "\u2248",
        apacir: "\u2A6F",
        apE: "\u2A70",
        ape: "\u224A",
        apid: "\u224B",
        apos: "'",
        ApplyFunction: "\u2061",
        approx: "\u2248",
        approxeq: "\u224A",
        Aring: "\xC5",
        aring: "\xE5",
        Ascr: "\u{1D49C}",
        ascr: "\u{1D4B6}",
        Assign: "\u2254",
        ast: "*",
        asymp: "\u2248",
        asympeq: "\u224D",
        Atilde: "\xC3",
        atilde: "\xE3",
        Auml: "\xC4",
        auml: "\xE4",
        awconint: "\u2233",
        awint: "\u2A11",
        backcong: "\u224C",
        backepsilon: "\u03F6",
        backprime: "\u2035",
        backsim: "\u223D",
        backsimeq: "\u22CD",
        Backslash: "\u2216",
        Barv: "\u2AE7",
        barvee: "\u22BD",
        Barwed: "\u2306",
        barwed: "\u2305",
        barwedge: "\u2305",
        bbrk: "\u23B5",
        bbrktbrk: "\u23B6",
        bcong: "\u224C",
        Bcy: "\u0411",
        bcy: "\u0431",
        bdquo: "\u201E",
        becaus: "\u2235",
        Because: "\u2235",
        because: "\u2235",
        bemptyv: "\u29B0",
        bepsi: "\u03F6",
        bernou: "\u212C",
        Bernoullis: "\u212C",
        Beta: "\u0392",
        beta: "\u03B2",
        beth: "\u2136",
        between: "\u226C",
        Bfr: "\u{1D505}",
        bfr: "\u{1D51F}",
        bigcap: "\u22C2",
        bigcirc: "\u25EF",
        bigcup: "\u22C3",
        bigodot: "\u2A00",
        bigoplus: "\u2A01",
        bigotimes: "\u2A02",
        bigsqcup: "\u2A06",
        bigstar: "\u2605",
        bigtriangledown: "\u25BD",
        bigtriangleup: "\u25B3",
        biguplus: "\u2A04",
        bigvee: "\u22C1",
        bigwedge: "\u22C0",
        bkarow: "\u290D",
        blacklozenge: "\u29EB",
        blacksquare: "\u25AA",
        blacktriangle: "\u25B4",
        blacktriangledown: "\u25BE",
        blacktriangleleft: "\u25C2",
        blacktriangleright: "\u25B8",
        blank: "\u2423",
        blk12: "\u2592",
        blk14: "\u2591",
        blk34: "\u2593",
        block: "\u2588",
        bne: "=\u20E5",
        bnequiv: "\u2261\u20E5",
        bNot: "\u2AED",
        bnot: "\u2310",
        Bopf: "\u{1D539}",
        bopf: "\u{1D553}",
        bot: "\u22A5",
        bottom: "\u22A5",
        bowtie: "\u22C8",
        boxbox: "\u29C9",
        boxDL: "\u2557",
        boxDl: "\u2556",
        boxdL: "\u2555",
        boxdl: "\u2510",
        boxDR: "\u2554",
        boxDr: "\u2553",
        boxdR: "\u2552",
        boxdr: "\u250C",
        boxH: "\u2550",
        boxh: "\u2500",
        boxHD: "\u2566",
        boxHd: "\u2564",
        boxhD: "\u2565",
        boxhd: "\u252C",
        boxHU: "\u2569",
        boxHu: "\u2567",
        boxhU: "\u2568",
        boxhu: "\u2534",
        boxminus: "\u229F",
        boxplus: "\u229E",
        boxtimes: "\u22A0",
        boxUL: "\u255D",
        boxUl: "\u255C",
        boxuL: "\u255B",
        boxul: "\u2518",
        boxUR: "\u255A",
        boxUr: "\u2559",
        boxuR: "\u2558",
        boxur: "\u2514",
        boxV: "\u2551",
        boxv: "\u2502",
        boxVH: "\u256C",
        boxVh: "\u256B",
        boxvH: "\u256A",
        boxvh: "\u253C",
        boxVL: "\u2563",
        boxVl: "\u2562",
        boxvL: "\u2561",
        boxvl: "\u2524",
        boxVR: "\u2560",
        boxVr: "\u255F",
        boxvR: "\u255E",
        boxvr: "\u251C",
        bprime: "\u2035",
        Breve: "\u02D8",
        breve: "\u02D8",
        brvbar: "\xA6",
        Bscr: "\u212C",
        bscr: "\u{1D4B7}",
        bsemi: "\u204F",
        bsim: "\u223D",
        bsime: "\u22CD",
        bsol: "\\",
        bsolb: "\u29C5",
        bsolhsub: "\u27C8",
        bull: "\u2022",
        bullet: "\u2022",
        bump: "\u224E",
        bumpE: "\u2AAE",
        bumpe: "\u224F",
        Bumpeq: "\u224E",
        bumpeq: "\u224F",
        Cacute: "\u0106",
        cacute: "\u0107",
        Cap: "\u22D2",
        cap: "\u2229",
        capand: "\u2A44",
        capbrcup: "\u2A49",
        capcap: "\u2A4B",
        capcup: "\u2A47",
        capdot: "\u2A40",
        CapitalDifferentialD: "\u2145",
        caps: "\u2229\uFE00",
        caret: "\u2041",
        caron: "\u02C7",
        Cayleys: "\u212D",
        ccaps: "\u2A4D",
        Ccaron: "\u010C",
        ccaron: "\u010D",
        Ccedil: "\xC7",
        ccedil: "\xE7",
        Ccirc: "\u0108",
        ccirc: "\u0109",
        Cconint: "\u2230",
        ccups: "\u2A4C",
        ccupssm: "\u2A50",
        Cdot: "\u010A",
        cdot: "\u010B",
        cedil: "\xB8",
        Cedilla: "\xB8",
        cemptyv: "\u29B2",
        cent: "\xA2",
        CenterDot: "\xB7",
        centerdot: "\xB7",
        Cfr: "\u212D",
        cfr: "\u{1D520}",
        CHcy: "\u0427",
        chcy: "\u0447",
        check: "\u2713",
        checkmark: "\u2713",
        Chi: "\u03A7",
        chi: "\u03C7",
        cir: "\u25CB",
        circ: "\u02C6",
        circeq: "\u2257",
        circlearrowleft: "\u21BA",
        circlearrowright: "\u21BB",
        circledast: "\u229B",
        circledcirc: "\u229A",
        circleddash: "\u229D",
        CircleDot: "\u2299",
        circledR: "\xAE",
        circledS: "\u24C8",
        CircleMinus: "\u2296",
        CirclePlus: "\u2295",
        CircleTimes: "\u2297",
        cirE: "\u29C3",
        cire: "\u2257",
        cirfnint: "\u2A10",
        cirmid: "\u2AEF",
        cirscir: "\u29C2",
        ClockwiseContourIntegral: "\u2232",
        CloseCurlyDoubleQuote: "\u201D",
        CloseCurlyQuote: "\u2019",
        clubs: "\u2663",
        clubsuit: "\u2663",
        Colon: "\u2237",
        colon: ":",
        Colone: "\u2A74",
        colone: "\u2254",
        coloneq: "\u2254",
        comma: ",",
        commat: "@",
        comp: "\u2201",
        compfn: "\u2218",
        complement: "\u2201",
        complexes: "\u2102",
        cong: "\u2245",
        congdot: "\u2A6D",
        Congruent: "\u2261",
        Conint: "\u222F",
        conint: "\u222E",
        ContourIntegral: "\u222E",
        Copf: "\u2102",
        copf: "\u{1D554}",
        coprod: "\u2210",
        Coproduct: "\u2210",
        COPY: "\xA9",
        copy: "\xA9",
        copysr: "\u2117",
        CounterClockwiseContourIntegral: "\u2233",
        crarr: "\u21B5",
        Cross: "\u2A2F",
        cross: "\u2717",
        Cscr: "\u{1D49E}",
        cscr: "\u{1D4B8}",
        csub: "\u2ACF",
        csube: "\u2AD1",
        csup: "\u2AD0",
        csupe: "\u2AD2",
        ctdot: "\u22EF",
        cudarrl: "\u2938",
        cudarrr: "\u2935",
        cuepr: "\u22DE",
        cuesc: "\u22DF",
        cularr: "\u21B6",
        cularrp: "\u293D",
        Cup: "\u22D3",
        cup: "\u222A",
        cupbrcap: "\u2A48",
        CupCap: "\u224D",
        cupcap: "\u2A46",
        cupcup: "\u2A4A",
        cupdot: "\u228D",
        cupor: "\u2A45",
        cups: "\u222A\uFE00",
        curarr: "\u21B7",
        curarrm: "\u293C",
        curlyeqprec: "\u22DE",
        curlyeqsucc: "\u22DF",
        curlyvee: "\u22CE",
        curlywedge: "\u22CF",
        curren: "\xA4",
        curvearrowleft: "\u21B6",
        curvearrowright: "\u21B7",
        cuvee: "\u22CE",
        cuwed: "\u22CF",
        cwconint: "\u2232",
        cwint: "\u2231",
        cylcty: "\u232D",
        Dagger: "\u2021",
        dagger: "\u2020",
        daleth: "\u2138",
        Darr: "\u21A1",
        dArr: "\u21D3",
        darr: "\u2193",
        dash: "\u2010",
        Dashv: "\u2AE4",
        dashv: "\u22A3",
        dbkarow: "\u290F",
        dblac: "\u02DD",
        Dcaron: "\u010E",
        dcaron: "\u010F",
        Dcy: "\u0414",
        dcy: "\u0434",
        DD: "\u2145",
        dd: "\u2146",
        ddagger: "\u2021",
        ddarr: "\u21CA",
        DDotrahd: "\u2911",
        ddotseq: "\u2A77",
        deg: "\xB0",
        Del: "\u2207",
        Delta: "\u0394",
        delta: "\u03B4",
        demptyv: "\u29B1",
        dfisht: "\u297F",
        Dfr: "\u{1D507}",
        dfr: "\u{1D521}",
        dHar: "\u2965",
        dharl: "\u21C3",
        dharr: "\u21C2",
        DiacriticalAcute: "\xB4",
        DiacriticalDot: "\u02D9",
        DiacriticalDoubleAcute: "\u02DD",
        DiacriticalGrave: "`",
        DiacriticalTilde: "\u02DC",
        diam: "\u22C4",
        Diamond: "\u22C4",
        diamond: "\u22C4",
        diamondsuit: "\u2666",
        diams: "\u2666",
        die: "\xA8",
        DifferentialD: "\u2146",
        digamma: "\u03DD",
        disin: "\u22F2",
        div: "\xF7",
        divide: "\xF7",
        divideontimes: "\u22C7",
        divonx: "\u22C7",
        DJcy: "\u0402",
        djcy: "\u0452",
        dlcorn: "\u231E",
        dlcrop: "\u230D",
        dollar: "$",
        Dopf: "\u{1D53B}",
        dopf: "\u{1D555}",
        Dot: "\xA8",
        dot: "\u02D9",
        DotDot: "\u20DC",
        doteq: "\u2250",
        doteqdot: "\u2251",
        DotEqual: "\u2250",
        dotminus: "\u2238",
        dotplus: "\u2214",
        dotsquare: "\u22A1",
        doublebarwedge: "\u2306",
        DoubleContourIntegral: "\u222F",
        DoubleDot: "\xA8",
        DoubleDownArrow: "\u21D3",
        DoubleLeftArrow: "\u21D0",
        DoubleLeftRightArrow: "\u21D4",
        DoubleLeftTee: "\u2AE4",
        DoubleLongLeftArrow: "\u27F8",
        DoubleLongLeftRightArrow: "\u27FA",
        DoubleLongRightArrow: "\u27F9",
        DoubleRightArrow: "\u21D2",
        DoubleRightTee: "\u22A8",
        DoubleUpArrow: "\u21D1",
        DoubleUpDownArrow: "\u21D5",
        DoubleVerticalBar: "\u2225",
        DownArrow: "\u2193",
        Downarrow: "\u21D3",
        downarrow: "\u2193",
        DownArrowBar: "\u2913",
        DownArrowUpArrow: "\u21F5",
        DownBreve: "\u0311",
        downdownarrows: "\u21CA",
        downharpoonleft: "\u21C3",
        downharpoonright: "\u21C2",
        DownLeftRightVector: "\u2950",
        DownLeftTeeVector: "\u295E",
        DownLeftVector: "\u21BD",
        DownLeftVectorBar: "\u2956",
        DownRightTeeVector: "\u295F",
        DownRightVector: "\u21C1",
        DownRightVectorBar: "\u2957",
        DownTee: "\u22A4",
        DownTeeArrow: "\u21A7",
        drbkarow: "\u2910",
        drcorn: "\u231F",
        drcrop: "\u230C",
        Dscr: "\u{1D49F}",
        dscr: "\u{1D4B9}",
        DScy: "\u0405",
        dscy: "\u0455",
        dsol: "\u29F6",
        Dstrok: "\u0110",
        dstrok: "\u0111",
        dtdot: "\u22F1",
        dtri: "\u25BF",
        dtrif: "\u25BE",
        duarr: "\u21F5",
        duhar: "\u296F",
        dwangle: "\u29A6",
        DZcy: "\u040F",
        dzcy: "\u045F",
        dzigrarr: "\u27FF",
        Eacute: "\xC9",
        eacute: "\xE9",
        easter: "\u2A6E",
        Ecaron: "\u011A",
        ecaron: "\u011B",
        ecir: "\u2256",
        Ecirc: "\xCA",
        ecirc: "\xEA",
        ecolon: "\u2255",
        Ecy: "\u042D",
        ecy: "\u044D",
        eDDot: "\u2A77",
        Edot: "\u0116",
        eDot: "\u2251",
        edot: "\u0117",
        ee: "\u2147",
        efDot: "\u2252",
        Efr: "\u{1D508}",
        efr: "\u{1D522}",
        eg: "\u2A9A",
        Egrave: "\xC8",
        egrave: "\xE8",
        egs: "\u2A96",
        egsdot: "\u2A98",
        el: "\u2A99",
        Element: "\u2208",
        elinters: "\u23E7",
        ell: "\u2113",
        els: "\u2A95",
        elsdot: "\u2A97",
        Emacr: "\u0112",
        emacr: "\u0113",
        empty: "\u2205",
        emptyset: "\u2205",
        EmptySmallSquare: "\u25FB",
        emptyv: "\u2205",
        EmptyVerySmallSquare: "\u25AB",
        emsp: "\u2003",
        emsp13: "\u2004",
        emsp14: "\u2005",
        ENG: "\u014A",
        eng: "\u014B",
        ensp: "\u2002",
        Eogon: "\u0118",
        eogon: "\u0119",
        Eopf: "\u{1D53C}",
        eopf: "\u{1D556}",
        epar: "\u22D5",
        eparsl: "\u29E3",
        eplus: "\u2A71",
        epsi: "\u03B5",
        Epsilon: "\u0395",
        epsilon: "\u03B5",
        epsiv: "\u03F5",
        eqcirc: "\u2256",
        eqcolon: "\u2255",
        eqsim: "\u2242",
        eqslantgtr: "\u2A96",
        eqslantless: "\u2A95",
        Equal: "\u2A75",
        equals: "=",
        EqualTilde: "\u2242",
        equest: "\u225F",
        Equilibrium: "\u21CC",
        equiv: "\u2261",
        equivDD: "\u2A78",
        eqvparsl: "\u29E5",
        erarr: "\u2971",
        erDot: "\u2253",
        Escr: "\u2130",
        escr: "\u212F",
        esdot: "\u2250",
        Esim: "\u2A73",
        esim: "\u2242",
        Eta: "\u0397",
        eta: "\u03B7",
        ETH: "\xD0",
        eth: "\xF0",
        Euml: "\xCB",
        euml: "\xEB",
        euro: "\u20AC",
        excl: "!",
        exist: "\u2203",
        Exists: "\u2203",
        expectation: "\u2130",
        ExponentialE: "\u2147",
        exponentiale: "\u2147",
        fallingdotseq: "\u2252",
        Fcy: "\u0424",
        fcy: "\u0444",
        female: "\u2640",
        ffilig: "\uFB03",
        fflig: "\uFB00",
        ffllig: "\uFB04",
        Ffr: "\u{1D509}",
        ffr: "\u{1D523}",
        filig: "\uFB01",
        FilledSmallSquare: "\u25FC",
        FilledVerySmallSquare: "\u25AA",
        fjlig: "fj",
        flat: "\u266D",
        fllig: "\uFB02",
        fltns: "\u25B1",
        fnof: "\u0192",
        Fopf: "\u{1D53D}",
        fopf: "\u{1D557}",
        ForAll: "\u2200",
        forall: "\u2200",
        fork: "\u22D4",
        forkv: "\u2AD9",
        Fouriertrf: "\u2131",
        fpartint: "\u2A0D",
        frac12: "\xBD",
        frac13: "\u2153",
        frac14: "\xBC",
        frac15: "\u2155",
        frac16: "\u2159",
        frac18: "\u215B",
        frac23: "\u2154",
        frac25: "\u2156",
        frac34: "\xBE",
        frac35: "\u2157",
        frac38: "\u215C",
        frac45: "\u2158",
        frac56: "\u215A",
        frac58: "\u215D",
        frac78: "\u215E",
        frasl: "\u2044",
        frown: "\u2322",
        Fscr: "\u2131",
        fscr: "\u{1D4BB}",
        gacute: "\u01F5",
        Gamma: "\u0393",
        gamma: "\u03B3",
        Gammad: "\u03DC",
        gammad: "\u03DD",
        gap: "\u2A86",
        Gbreve: "\u011E",
        gbreve: "\u011F",
        Gcedil: "\u0122",
        Gcirc: "\u011C",
        gcirc: "\u011D",
        Gcy: "\u0413",
        gcy: "\u0433",
        Gdot: "\u0120",
        gdot: "\u0121",
        gE: "\u2267",
        ge: "\u2265",
        gEl: "\u2A8C",
        gel: "\u22DB",
        geq: "\u2265",
        geqq: "\u2267",
        geqslant: "\u2A7E",
        ges: "\u2A7E",
        gescc: "\u2AA9",
        gesdot: "\u2A80",
        gesdoto: "\u2A82",
        gesdotol: "\u2A84",
        gesl: "\u22DB\uFE00",
        gesles: "\u2A94",
        Gfr: "\u{1D50A}",
        gfr: "\u{1D524}",
        Gg: "\u22D9",
        gg: "\u226B",
        ggg: "\u22D9",
        gimel: "\u2137",
        GJcy: "\u0403",
        gjcy: "\u0453",
        gl: "\u2277",
        gla: "\u2AA5",
        glE: "\u2A92",
        glj: "\u2AA4",
        gnap: "\u2A8A",
        gnapprox: "\u2A8A",
        gnE: "\u2269",
        gne: "\u2A88",
        gneq: "\u2A88",
        gneqq: "\u2269",
        gnsim: "\u22E7",
        Gopf: "\u{1D53E}",
        gopf: "\u{1D558}",
        grave: "`",
        GreaterEqual: "\u2265",
        GreaterEqualLess: "\u22DB",
        GreaterFullEqual: "\u2267",
        GreaterGreater: "\u2AA2",
        GreaterLess: "\u2277",
        GreaterSlantEqual: "\u2A7E",
        GreaterTilde: "\u2273",
        Gscr: "\u{1D4A2}",
        gscr: "\u210A",
        gsim: "\u2273",
        gsime: "\u2A8E",
        gsiml: "\u2A90",
        Gt: "\u226B",
        GT: ">",
        gt: ">",
        gtcc: "\u2AA7",
        gtcir: "\u2A7A",
        gtdot: "\u22D7",
        gtlPar: "\u2995",
        gtquest: "\u2A7C",
        gtrapprox: "\u2A86",
        gtrarr: "\u2978",
        gtrdot: "\u22D7",
        gtreqless: "\u22DB",
        gtreqqless: "\u2A8C",
        gtrless: "\u2277",
        gtrsim: "\u2273",
        gvertneqq: "\u2269\uFE00",
        gvnE: "\u2269\uFE00",
        Hacek: "\u02C7",
        hairsp: "\u200A",
        half: "\xBD",
        hamilt: "\u210B",
        HARDcy: "\u042A",
        hardcy: "\u044A",
        hArr: "\u21D4",
        harr: "\u2194",
        harrcir: "\u2948",
        harrw: "\u21AD",
        Hat: "^",
        hbar: "\u210F",
        Hcirc: "\u0124",
        hcirc: "\u0125",
        hearts: "\u2665",
        heartsuit: "\u2665",
        hellip: "\u2026",
        hercon: "\u22B9",
        Hfr: "\u210C",
        hfr: "\u{1D525}",
        HilbertSpace: "\u210B",
        hksearow: "\u2925",
        hkswarow: "\u2926",
        hoarr: "\u21FF",
        homtht: "\u223B",
        hookleftarrow: "\u21A9",
        hookrightarrow: "\u21AA",
        Hopf: "\u210D",
        hopf: "\u{1D559}",
        horbar: "\u2015",
        HorizontalLine: "\u2500",
        Hscr: "\u210B",
        hscr: "\u{1D4BD}",
        hslash: "\u210F",
        Hstrok: "\u0126",
        hstrok: "\u0127",
        HumpDownHump: "\u224E",
        HumpEqual: "\u224F",
        hybull: "\u2043",
        hyphen: "\u2010",
        Iacute: "\xCD",
        iacute: "\xED",
        ic: "\u2063",
        Icirc: "\xCE",
        icirc: "\xEE",
        Icy: "\u0418",
        icy: "\u0438",
        Idot: "\u0130",
        IEcy: "\u0415",
        iecy: "\u0435",
        iexcl: "\xA1",
        iff: "\u21D4",
        Ifr: "\u2111",
        ifr: "\u{1D526}",
        Igrave: "\xCC",
        igrave: "\xEC",
        ii: "\u2148",
        iiiint: "\u2A0C",
        iiint: "\u222D",
        iinfin: "\u29DC",
        iiota: "\u2129",
        IJlig: "\u0132",
        ijlig: "\u0133",
        Im: "\u2111",
        Imacr: "\u012A",
        imacr: "\u012B",
        image: "\u2111",
        ImaginaryI: "\u2148",
        imagline: "\u2110",
        imagpart: "\u2111",
        imath: "\u0131",
        imof: "\u22B7",
        imped: "\u01B5",
        Implies: "\u21D2",
        in: "\u2208",
        incare: "\u2105",
        infin: "\u221E",
        infintie: "\u29DD",
        inodot: "\u0131",
        Int: "\u222C",
        int: "\u222B",
        intcal: "\u22BA",
        integers: "\u2124",
        Integral: "\u222B",
        intercal: "\u22BA",
        Intersection: "\u22C2",
        intlarhk: "\u2A17",
        intprod: "\u2A3C",
        InvisibleComma: "\u2063",
        InvisibleTimes: "\u2062",
        IOcy: "\u0401",
        iocy: "\u0451",
        Iogon: "\u012E",
        iogon: "\u012F",
        Iopf: "\u{1D540}",
        iopf: "\u{1D55A}",
        Iota: "\u0399",
        iota: "\u03B9",
        iprod: "\u2A3C",
        iquest: "\xBF",
        Iscr: "\u2110",
        iscr: "\u{1D4BE}",
        isin: "\u2208",
        isindot: "\u22F5",
        isinE: "\u22F9",
        isins: "\u22F4",
        isinsv: "\u22F3",
        isinv: "\u2208",
        it: "\u2062",
        Itilde: "\u0128",
        itilde: "\u0129",
        Iukcy: "\u0406",
        iukcy: "\u0456",
        Iuml: "\xCF",
        iuml: "\xEF",
        Jcirc: "\u0134",
        jcirc: "\u0135",
        Jcy: "\u0419",
        jcy: "\u0439",
        Jfr: "\u{1D50D}",
        jfr: "\u{1D527}",
        jmath: "\u0237",
        Jopf: "\u{1D541}",
        jopf: "\u{1D55B}",
        Jscr: "\u{1D4A5}",
        jscr: "\u{1D4BF}",
        Jsercy: "\u0408",
        jsercy: "\u0458",
        Jukcy: "\u0404",
        jukcy: "\u0454",
        Kappa: "\u039A",
        kappa: "\u03BA",
        kappav: "\u03F0",
        Kcedil: "\u0136",
        kcedil: "\u0137",
        Kcy: "\u041A",
        kcy: "\u043A",
        Kfr: "\u{1D50E}",
        kfr: "\u{1D528}",
        kgreen: "\u0138",
        KHcy: "\u0425",
        khcy: "\u0445",
        KJcy: "\u040C",
        kjcy: "\u045C",
        Kopf: "\u{1D542}",
        kopf: "\u{1D55C}",
        Kscr: "\u{1D4A6}",
        kscr: "\u{1D4C0}",
        lAarr: "\u21DA",
        Lacute: "\u0139",
        lacute: "\u013A",
        laemptyv: "\u29B4",
        lagran: "\u2112",
        Lambda: "\u039B",
        lambda: "\u03BB",
        Lang: "\u27EA",
        lang: "\u27E8",
        langd: "\u2991",
        langle: "\u27E8",
        lap: "\u2A85",
        Laplacetrf: "\u2112",
        laquo: "\xAB",
        Larr: "\u219E",
        lArr: "\u21D0",
        larr: "\u2190",
        larrb: "\u21E4",
        larrbfs: "\u291F",
        larrfs: "\u291D",
        larrhk: "\u21A9",
        larrlp: "\u21AB",
        larrpl: "\u2939",
        larrsim: "\u2973",
        larrtl: "\u21A2",
        lat: "\u2AAB",
        lAtail: "\u291B",
        latail: "\u2919",
        late: "\u2AAD",
        lates: "\u2AAD\uFE00",
        lBarr: "\u290E",
        lbarr: "\u290C",
        lbbrk: "\u2772",
        lbrace: "{",
        lbrack: "[",
        lbrke: "\u298B",
        lbrksld: "\u298F",
        lbrkslu: "\u298D",
        Lcaron: "\u013D",
        lcaron: "\u013E",
        Lcedil: "\u013B",
        lcedil: "\u013C",
        lceil: "\u2308",
        lcub: "{",
        Lcy: "\u041B",
        lcy: "\u043B",
        ldca: "\u2936",
        ldquo: "\u201C",
        ldquor: "\u201E",
        ldrdhar: "\u2967",
        ldrushar: "\u294B",
        ldsh: "\u21B2",
        lE: "\u2266",
        le: "\u2264",
        LeftAngleBracket: "\u27E8",
        LeftArrow: "\u2190",
        Leftarrow: "\u21D0",
        leftarrow: "\u2190",
        LeftArrowBar: "\u21E4",
        LeftArrowRightArrow: "\u21C6",
        leftarrowtail: "\u21A2",
        LeftCeiling: "\u2308",
        LeftDoubleBracket: "\u27E6",
        LeftDownTeeVector: "\u2961",
        LeftDownVector: "\u21C3",
        LeftDownVectorBar: "\u2959",
        LeftFloor: "\u230A",
        leftharpoondown: "\u21BD",
        leftharpoonup: "\u21BC",
        leftleftarrows: "\u21C7",
        LeftRightArrow: "\u2194",
        Leftrightarrow: "\u21D4",
        leftrightarrow: "\u2194",
        leftrightarrows: "\u21C6",
        leftrightharpoons: "\u21CB",
        leftrightsquigarrow: "\u21AD",
        LeftRightVector: "\u294E",
        LeftTee: "\u22A3",
        LeftTeeArrow: "\u21A4",
        LeftTeeVector: "\u295A",
        leftthreetimes: "\u22CB",
        LeftTriangle: "\u22B2",
        LeftTriangleBar: "\u29CF",
        LeftTriangleEqual: "\u22B4",
        LeftUpDownVector: "\u2951",
        LeftUpTeeVector: "\u2960",
        LeftUpVector: "\u21BF",
        LeftUpVectorBar: "\u2958",
        LeftVector: "\u21BC",
        LeftVectorBar: "\u2952",
        lEg: "\u2A8B",
        leg: "\u22DA",
        leq: "\u2264",
        leqq: "\u2266",
        leqslant: "\u2A7D",
        les: "\u2A7D",
        lescc: "\u2AA8",
        lesdot: "\u2A7F",
        lesdoto: "\u2A81",
        lesdotor: "\u2A83",
        lesg: "\u22DA\uFE00",
        lesges: "\u2A93",
        lessapprox: "\u2A85",
        lessdot: "\u22D6",
        lesseqgtr: "\u22DA",
        lesseqqgtr: "\u2A8B",
        LessEqualGreater: "\u22DA",
        LessFullEqual: "\u2266",
        LessGreater: "\u2276",
        lessgtr: "\u2276",
        LessLess: "\u2AA1",
        lesssim: "\u2272",
        LessSlantEqual: "\u2A7D",
        LessTilde: "\u2272",
        lfisht: "\u297C",
        lfloor: "\u230A",
        Lfr: "\u{1D50F}",
        lfr: "\u{1D529}",
        lg: "\u2276",
        lgE: "\u2A91",
        lHar: "\u2962",
        lhard: "\u21BD",
        lharu: "\u21BC",
        lharul: "\u296A",
        lhblk: "\u2584",
        LJcy: "\u0409",
        ljcy: "\u0459",
        Ll: "\u22D8",
        ll: "\u226A",
        llarr: "\u21C7",
        llcorner: "\u231E",
        Lleftarrow: "\u21DA",
        llhard: "\u296B",
        lltri: "\u25FA",
        Lmidot: "\u013F",
        lmidot: "\u0140",
        lmoust: "\u23B0",
        lmoustache: "\u23B0",
        lnap: "\u2A89",
        lnapprox: "\u2A89",
        lnE: "\u2268",
        lne: "\u2A87",
        lneq: "\u2A87",
        lneqq: "\u2268",
        lnsim: "\u22E6",
        loang: "\u27EC",
        loarr: "\u21FD",
        lobrk: "\u27E6",
        LongLeftArrow: "\u27F5",
        Longleftarrow: "\u27F8",
        longleftarrow: "\u27F5",
        LongLeftRightArrow: "\u27F7",
        Longleftrightarrow: "\u27FA",
        longleftrightarrow: "\u27F7",
        longmapsto: "\u27FC",
        LongRightArrow: "\u27F6",
        Longrightarrow: "\u27F9",
        longrightarrow: "\u27F6",
        looparrowleft: "\u21AB",
        looparrowright: "\u21AC",
        lopar: "\u2985",
        Lopf: "\u{1D543}",
        lopf: "\u{1D55D}",
        loplus: "\u2A2D",
        lotimes: "\u2A34",
        lowast: "\u2217",
        lowbar: "_",
        LowerLeftArrow: "\u2199",
        LowerRightArrow: "\u2198",
        loz: "\u25CA",
        lozenge: "\u25CA",
        lozf: "\u29EB",
        lpar: "(",
        lparlt: "\u2993",
        lrarr: "\u21C6",
        lrcorner: "\u231F",
        lrhar: "\u21CB",
        lrhard: "\u296D",
        lrm: "\u200E",
        lrtri: "\u22BF",
        lsaquo: "\u2039",
        Lscr: "\u2112",
        lscr: "\u{1D4C1}",
        Lsh: "\u21B0",
        lsh: "\u21B0",
        lsim: "\u2272",
        lsime: "\u2A8D",
        lsimg: "\u2A8F",
        lsqb: "[",
        lsquo: "\u2018",
        lsquor: "\u201A",
        Lstrok: "\u0141",
        lstrok: "\u0142",
        Lt: "\u226A",
        LT: "<",
        lt: "<",
        ltcc: "\u2AA6",
        ltcir: "\u2A79",
        ltdot: "\u22D6",
        lthree: "\u22CB",
        ltimes: "\u22C9",
        ltlarr: "\u2976",
        ltquest: "\u2A7B",
        ltri: "\u25C3",
        ltrie: "\u22B4",
        ltrif: "\u25C2",
        ltrPar: "\u2996",
        lurdshar: "\u294A",
        luruhar: "\u2966",
        lvertneqq: "\u2268\uFE00",
        lvnE: "\u2268\uFE00",
        macr: "\xAF",
        male: "\u2642",
        malt: "\u2720",
        maltese: "\u2720",
        Map: "\u2905",
        map: "\u21A6",
        mapsto: "\u21A6",
        mapstodown: "\u21A7",
        mapstoleft: "\u21A4",
        mapstoup: "\u21A5",
        marker: "\u25AE",
        mcomma: "\u2A29",
        Mcy: "\u041C",
        mcy: "\u043C",
        mdash: "\u2014",
        mDDot: "\u223A",
        measuredangle: "\u2221",
        MediumSpace: "\u205F",
        Mellintrf: "\u2133",
        Mfr: "\u{1D510}",
        mfr: "\u{1D52A}",
        mho: "\u2127",
        micro: "\xB5",
        mid: "\u2223",
        midast: "*",
        midcir: "\u2AF0",
        middot: "\xB7",
        minus: "\u2212",
        minusb: "\u229F",
        minusd: "\u2238",
        minusdu: "\u2A2A",
        MinusPlus: "\u2213",
        mlcp: "\u2ADB",
        mldr: "\u2026",
        mnplus: "\u2213",
        models: "\u22A7",
        Mopf: "\u{1D544}",
        mopf: "\u{1D55E}",
        mp: "\u2213",
        Mscr: "\u2133",
        mscr: "\u{1D4C2}",
        mstpos: "\u223E",
        Mu: "\u039C",
        mu: "\u03BC",
        multimap: "\u22B8",
        mumap: "\u22B8",
        nabla: "\u2207",
        Nacute: "\u0143",
        nacute: "\u0144",
        nang: "\u2220\u20D2",
        nap: "\u2249",
        napE: "\u2A70\u0338",
        napid: "\u224B\u0338",
        napos: "\u0149",
        napprox: "\u2249",
        natur: "\u266E",
        natural: "\u266E",
        naturals: "\u2115",
        nbsp: "\xA0",
        nbump: "\u224E\u0338",
        nbumpe: "\u224F\u0338",
        ncap: "\u2A43",
        Ncaron: "\u0147",
        ncaron: "\u0148",
        Ncedil: "\u0145",
        ncedil: "\u0146",
        ncong: "\u2247",
        ncongdot: "\u2A6D\u0338",
        ncup: "\u2A42",
        Ncy: "\u041D",
        ncy: "\u043D",
        ndash: "\u2013",
        ne: "\u2260",
        nearhk: "\u2924",
        neArr: "\u21D7",
        nearr: "\u2197",
        nearrow: "\u2197",
        nedot: "\u2250\u0338",
        NegativeMediumSpace: "\u200B",
        NegativeThickSpace: "\u200B",
        NegativeThinSpace: "\u200B",
        NegativeVeryThinSpace: "\u200B",
        nequiv: "\u2262",
        nesear: "\u2928",
        nesim: "\u2242\u0338",
        NestedGreaterGreater: "\u226B",
        NestedLessLess: "\u226A",
        NewLine: "\n",
        nexist: "\u2204",
        nexists: "\u2204",
        Nfr: "\u{1D511}",
        nfr: "\u{1D52B}",
        ngE: "\u2267\u0338",
        nge: "\u2271",
        ngeq: "\u2271",
        ngeqq: "\u2267\u0338",
        ngeqslant: "\u2A7E\u0338",
        nges: "\u2A7E\u0338",
        nGg: "\u22D9\u0338",
        ngsim: "\u2275",
        nGt: "\u226B\u20D2",
        ngt: "\u226F",
        ngtr: "\u226F",
        nGtv: "\u226B\u0338",
        nhArr: "\u21CE",
        nharr: "\u21AE",
        nhpar: "\u2AF2",
        ni: "\u220B",
        nis: "\u22FC",
        nisd: "\u22FA",
        niv: "\u220B",
        NJcy: "\u040A",
        njcy: "\u045A",
        nlArr: "\u21CD",
        nlarr: "\u219A",
        nldr: "\u2025",
        nlE: "\u2266\u0338",
        nle: "\u2270",
        nLeftarrow: "\u21CD",
        nleftarrow: "\u219A",
        nLeftrightarrow: "\u21CE",
        nleftrightarrow: "\u21AE",
        nleq: "\u2270",
        nleqq: "\u2266\u0338",
        nleqslant: "\u2A7D\u0338",
        nles: "\u2A7D\u0338",
        nless: "\u226E",
        nLl: "\u22D8\u0338",
        nlsim: "\u2274",
        nLt: "\u226A\u20D2",
        nlt: "\u226E",
        nltri: "\u22EA",
        nltrie: "\u22EC",
        nLtv: "\u226A\u0338",
        nmid: "\u2224",
        NoBreak: "\u2060",
        NonBreakingSpace: "\xA0",
        Nopf: "\u2115",
        nopf: "\u{1D55F}",
        Not: "\u2AEC",
        not: "\xAC",
        NotCongruent: "\u2262",
        NotCupCap: "\u226D",
        NotDoubleVerticalBar: "\u2226",
        NotElement: "\u2209",
        NotEqual: "\u2260",
        NotEqualTilde: "\u2242\u0338",
        NotExists: "\u2204",
        NotGreater: "\u226F",
        NotGreaterEqual: "\u2271",
        NotGreaterFullEqual: "\u2267\u0338",
        NotGreaterGreater: "\u226B\u0338",
        NotGreaterLess: "\u2279",
        NotGreaterSlantEqual: "\u2A7E\u0338",
        NotGreaterTilde: "\u2275",
        NotHumpDownHump: "\u224E\u0338",
        NotHumpEqual: "\u224F\u0338",
        notin: "\u2209",
        notindot: "\u22F5\u0338",
        notinE: "\u22F9\u0338",
        notinva: "\u2209",
        notinvb: "\u22F7",
        notinvc: "\u22F6",
        NotLeftTriangle: "\u22EA",
        NotLeftTriangleBar: "\u29CF\u0338",
        NotLeftTriangleEqual: "\u22EC",
        NotLess: "\u226E",
        NotLessEqual: "\u2270",
        NotLessGreater: "\u2278",
        NotLessLess: "\u226A\u0338",
        NotLessSlantEqual: "\u2A7D\u0338",
        NotLessTilde: "\u2274",
        NotNestedGreaterGreater: "\u2AA2\u0338",
        NotNestedLessLess: "\u2AA1\u0338",
        notni: "\u220C",
        notniva: "\u220C",
        notnivb: "\u22FE",
        notnivc: "\u22FD",
        NotPrecedes: "\u2280",
        NotPrecedesEqual: "\u2AAF\u0338",
        NotPrecedesSlantEqual: "\u22E0",
        NotReverseElement: "\u220C",
        NotRightTriangle: "\u22EB",
        NotRightTriangleBar: "\u29D0\u0338",
        NotRightTriangleEqual: "\u22ED",
        NotSquareSubset: "\u228F\u0338",
        NotSquareSubsetEqual: "\u22E2",
        NotSquareSuperset: "\u2290\u0338",
        NotSquareSupersetEqual: "\u22E3",
        NotSubset: "\u2282\u20D2",
        NotSubsetEqual: "\u2288",
        NotSucceeds: "\u2281",
        NotSucceedsEqual: "\u2AB0\u0338",
        NotSucceedsSlantEqual: "\u22E1",
        NotSucceedsTilde: "\u227F\u0338",
        NotSuperset: "\u2283\u20D2",
        NotSupersetEqual: "\u2289",
        NotTilde: "\u2241",
        NotTildeEqual: "\u2244",
        NotTildeFullEqual: "\u2247",
        NotTildeTilde: "\u2249",
        NotVerticalBar: "\u2224",
        npar: "\u2226",
        nparallel: "\u2226",
        nparsl: "\u2AFD\u20E5",
        npart: "\u2202\u0338",
        npolint: "\u2A14",
        npr: "\u2280",
        nprcue: "\u22E0",
        npre: "\u2AAF\u0338",
        nprec: "\u2280",
        npreceq: "\u2AAF\u0338",
        nrArr: "\u21CF",
        nrarr: "\u219B",
        nrarrc: "\u2933\u0338",
        nrarrw: "\u219D\u0338",
        nRightarrow: "\u21CF",
        nrightarrow: "\u219B",
        nrtri: "\u22EB",
        nrtrie: "\u22ED",
        nsc: "\u2281",
        nsccue: "\u22E1",
        nsce: "\u2AB0\u0338",
        Nscr: "\u{1D4A9}",
        nscr: "\u{1D4C3}",
        nshortmid: "\u2224",
        nshortparallel: "\u2226",
        nsim: "\u2241",
        nsime: "\u2244",
        nsimeq: "\u2244",
        nsmid: "\u2224",
        nspar: "\u2226",
        nsqsube: "\u22E2",
        nsqsupe: "\u22E3",
        nsub: "\u2284",
        nsubE: "\u2AC5\u0338",
        nsube: "\u2288",
        nsubset: "\u2282\u20D2",
        nsubseteq: "\u2288",
        nsubseteqq: "\u2AC5\u0338",
        nsucc: "\u2281",
        nsucceq: "\u2AB0\u0338",
        nsup: "\u2285",
        nsupE: "\u2AC6\u0338",
        nsupe: "\u2289",
        nsupset: "\u2283\u20D2",
        nsupseteq: "\u2289",
        nsupseteqq: "\u2AC6\u0338",
        ntgl: "\u2279",
        Ntilde: "\xD1",
        ntilde: "\xF1",
        ntlg: "\u2278",
        ntriangleleft: "\u22EA",
        ntrianglelefteq: "\u22EC",
        ntriangleright: "\u22EB",
        ntrianglerighteq: "\u22ED",
        Nu: "\u039D",
        nu: "\u03BD",
        num: "#",
        numero: "\u2116",
        numsp: "\u2007",
        nvap: "\u224D\u20D2",
        nVDash: "\u22AF",
        nVdash: "\u22AE",
        nvDash: "\u22AD",
        nvdash: "\u22AC",
        nvge: "\u2265\u20D2",
        nvgt: ">\u20D2",
        nvHarr: "\u2904",
        nvinfin: "\u29DE",
        nvlArr: "\u2902",
        nvle: "\u2264\u20D2",
        nvlt: "<\u20D2",
        nvltrie: "\u22B4\u20D2",
        nvrArr: "\u2903",
        nvrtrie: "\u22B5\u20D2",
        nvsim: "\u223C\u20D2",
        nwarhk: "\u2923",
        nwArr: "\u21D6",
        nwarr: "\u2196",
        nwarrow: "\u2196",
        nwnear: "\u2927",
        Oacute: "\xD3",
        oacute: "\xF3",
        oast: "\u229B",
        ocir: "\u229A",
        Ocirc: "\xD4",
        ocirc: "\xF4",
        Ocy: "\u041E",
        ocy: "\u043E",
        odash: "\u229D",
        Odblac: "\u0150",
        odblac: "\u0151",
        odiv: "\u2A38",
        odot: "\u2299",
        odsold: "\u29BC",
        OElig: "\u0152",
        oelig: "\u0153",
        ofcir: "\u29BF",
        Ofr: "\u{1D512}",
        ofr: "\u{1D52C}",
        ogon: "\u02DB",
        Ograve: "\xD2",
        ograve: "\xF2",
        ogt: "\u29C1",
        ohbar: "\u29B5",
        ohm: "\u03A9",
        oint: "\u222E",
        olarr: "\u21BA",
        olcir: "\u29BE",
        olcross: "\u29BB",
        oline: "\u203E",
        olt: "\u29C0",
        Omacr: "\u014C",
        omacr: "\u014D",
        Omega: "\u03A9",
        omega: "\u03C9",
        Omicron: "\u039F",
        omicron: "\u03BF",
        omid: "\u29B6",
        ominus: "\u2296",
        Oopf: "\u{1D546}",
        oopf: "\u{1D560}",
        opar: "\u29B7",
        OpenCurlyDoubleQuote: "\u201C",
        OpenCurlyQuote: "\u2018",
        operp: "\u29B9",
        oplus: "\u2295",
        Or: "\u2A54",
        or: "\u2228",
        orarr: "\u21BB",
        ord: "\u2A5D",
        order: "\u2134",
        orderof: "\u2134",
        ordf: "\xAA",
        ordm: "\xBA",
        origof: "\u22B6",
        oror: "\u2A56",
        orslope: "\u2A57",
        orv: "\u2A5B",
        oS: "\u24C8",
        Oscr: "\u{1D4AA}",
        oscr: "\u2134",
        Oslash: "\xD8",
        oslash: "\xF8",
        osol: "\u2298",
        Otilde: "\xD5",
        otilde: "\xF5",
        Otimes: "\u2A37",
        otimes: "\u2297",
        otimesas: "\u2A36",
        Ouml: "\xD6",
        ouml: "\xF6",
        ovbar: "\u233D",
        OverBar: "\u203E",
        OverBrace: "\u23DE",
        OverBracket: "\u23B4",
        OverParenthesis: "\u23DC",
        par: "\u2225",
        para: "\xB6",
        parallel: "\u2225",
        parsim: "\u2AF3",
        parsl: "\u2AFD",
        part: "\u2202",
        PartialD: "\u2202",
        Pcy: "\u041F",
        pcy: "\u043F",
        percnt: "%",
        period: ".",
        permil: "\u2030",
        perp: "\u22A5",
        pertenk: "\u2031",
        Pfr: "\u{1D513}",
        pfr: "\u{1D52D}",
        Phi: "\u03A6",
        phi: "\u03C6",
        phiv: "\u03D5",
        phmmat: "\u2133",
        phone: "\u260E",
        Pi: "\u03A0",
        pi: "\u03C0",
        pitchfork: "\u22D4",
        piv: "\u03D6",
        planck: "\u210F",
        planckh: "\u210E",
        plankv: "\u210F",
        plus: "+",
        plusacir: "\u2A23",
        plusb: "\u229E",
        pluscir: "\u2A22",
        plusdo: "\u2214",
        plusdu: "\u2A25",
        pluse: "\u2A72",
        PlusMinus: "\xB1",
        plusmn: "\xB1",
        plussim: "\u2A26",
        plustwo: "\u2A27",
        pm: "\xB1",
        Poincareplane: "\u210C",
        pointint: "\u2A15",
        Popf: "\u2119",
        popf: "\u{1D561}",
        pound: "\xA3",
        Pr: "\u2ABB",
        pr: "\u227A",
        prap: "\u2AB7",
        prcue: "\u227C",
        prE: "\u2AB3",
        pre: "\u2AAF",
        prec: "\u227A",
        precapprox: "\u2AB7",
        preccurlyeq: "\u227C",
        Precedes: "\u227A",
        PrecedesEqual: "\u2AAF",
        PrecedesSlantEqual: "\u227C",
        PrecedesTilde: "\u227E",
        preceq: "\u2AAF",
        precnapprox: "\u2AB9",
        precneqq: "\u2AB5",
        precnsim: "\u22E8",
        precsim: "\u227E",
        Prime: "\u2033",
        prime: "\u2032",
        primes: "\u2119",
        prnap: "\u2AB9",
        prnE: "\u2AB5",
        prnsim: "\u22E8",
        prod: "\u220F",
        Product: "\u220F",
        profalar: "\u232E",
        profline: "\u2312",
        profsurf: "\u2313",
        prop: "\u221D",
        Proportion: "\u2237",
        Proportional: "\u221D",
        propto: "\u221D",
        prsim: "\u227E",
        prurel: "\u22B0",
        Pscr: "\u{1D4AB}",
        pscr: "\u{1D4C5}",
        Psi: "\u03A8",
        psi: "\u03C8",
        puncsp: "\u2008",
        Qfr: "\u{1D514}",
        qfr: "\u{1D52E}",
        qint: "\u2A0C",
        Qopf: "\u211A",
        qopf: "\u{1D562}",
        qprime: "\u2057",
        Qscr: "\u{1D4AC}",
        qscr: "\u{1D4C6}",
        quaternions: "\u210D",
        quatint: "\u2A16",
        quest: "?",
        questeq: "\u225F",
        QUOT: '"',
        quot: '"',
        rAarr: "\u21DB",
        race: "\u223D\u0331",
        Racute: "\u0154",
        racute: "\u0155",
        radic: "\u221A",
        raemptyv: "\u29B3",
        Rang: "\u27EB",
        rang: "\u27E9",
        rangd: "\u2992",
        range: "\u29A5",
        rangle: "\u27E9",
        raquo: "\xBB",
        Rarr: "\u21A0",
        rArr: "\u21D2",
        rarr: "\u2192",
        rarrap: "\u2975",
        rarrb: "\u21E5",
        rarrbfs: "\u2920",
        rarrc: "\u2933",
        rarrfs: "\u291E",
        rarrhk: "\u21AA",
        rarrlp: "\u21AC",
        rarrpl: "\u2945",
        rarrsim: "\u2974",
        Rarrtl: "\u2916",
        rarrtl: "\u21A3",
        rarrw: "\u219D",
        rAtail: "\u291C",
        ratail: "\u291A",
        ratio: "\u2236",
        rationals: "\u211A",
        RBarr: "\u2910",
        rBarr: "\u290F",
        rbarr: "\u290D",
        rbbrk: "\u2773",
        rbrace: "}",
        rbrack: "]",
        rbrke: "\u298C",
        rbrksld: "\u298E",
        rbrkslu: "\u2990",
        Rcaron: "\u0158",
        rcaron: "\u0159",
        Rcedil: "\u0156",
        rcedil: "\u0157",
        rceil: "\u2309",
        rcub: "}",
        Rcy: "\u0420",
        rcy: "\u0440",
        rdca: "\u2937",
        rdldhar: "\u2969",
        rdquo: "\u201D",
        rdquor: "\u201D",
        rdsh: "\u21B3",
        Re: "\u211C",
        real: "\u211C",
        realine: "\u211B",
        realpart: "\u211C",
        reals: "\u211D",
        rect: "\u25AD",
        REG: "\xAE",
        reg: "\xAE",
        ReverseElement: "\u220B",
        ReverseEquilibrium: "\u21CB",
        ReverseUpEquilibrium: "\u296F",
        rfisht: "\u297D",
        rfloor: "\u230B",
        Rfr: "\u211C",
        rfr: "\u{1D52F}",
        rHar: "\u2964",
        rhard: "\u21C1",
        rharu: "\u21C0",
        rharul: "\u296C",
        Rho: "\u03A1",
        rho: "\u03C1",
        rhov: "\u03F1",
        RightAngleBracket: "\u27E9",
        RightArrow: "\u2192",
        Rightarrow: "\u21D2",
        rightarrow: "\u2192",
        RightArrowBar: "\u21E5",
        RightArrowLeftArrow: "\u21C4",
        rightarrowtail: "\u21A3",
        RightCeiling: "\u2309",
        RightDoubleBracket: "\u27E7",
        RightDownTeeVector: "\u295D",
        RightDownVector: "\u21C2",
        RightDownVectorBar: "\u2955",
        RightFloor: "\u230B",
        rightharpoondown: "\u21C1",
        rightharpoonup: "\u21C0",
        rightleftarrows: "\u21C4",
        rightleftharpoons: "\u21CC",
        rightrightarrows: "\u21C9",
        rightsquigarrow: "\u219D",
        RightTee: "\u22A2",
        RightTeeArrow: "\u21A6",
        RightTeeVector: "\u295B",
        rightthreetimes: "\u22CC",
        RightTriangle: "\u22B3",
        RightTriangleBar: "\u29D0",
        RightTriangleEqual: "\u22B5",
        RightUpDownVector: "\u294F",
        RightUpTeeVector: "\u295C",
        RightUpVector: "\u21BE",
        RightUpVectorBar: "\u2954",
        RightVector: "\u21C0",
        RightVectorBar: "\u2953",
        ring: "\u02DA",
        risingdotseq: "\u2253",
        rlarr: "\u21C4",
        rlhar: "\u21CC",
        rlm: "\u200F",
        rmoust: "\u23B1",
        rmoustache: "\u23B1",
        rnmid: "\u2AEE",
        roang: "\u27ED",
        roarr: "\u21FE",
        robrk: "\u27E7",
        ropar: "\u2986",
        Ropf: "\u211D",
        ropf: "\u{1D563}",
        roplus: "\u2A2E",
        rotimes: "\u2A35",
        RoundImplies: "\u2970",
        rpar: ")",
        rpargt: "\u2994",
        rppolint: "\u2A12",
        rrarr: "\u21C9",
        Rrightarrow: "\u21DB",
        rsaquo: "\u203A",
        Rscr: "\u211B",
        rscr: "\u{1D4C7}",
        Rsh: "\u21B1",
        rsh: "\u21B1",
        rsqb: "]",
        rsquo: "\u2019",
        rsquor: "\u2019",
        rthree: "\u22CC",
        rtimes: "\u22CA",
        rtri: "\u25B9",
        rtrie: "\u22B5",
        rtrif: "\u25B8",
        rtriltri: "\u29CE",
        RuleDelayed: "\u29F4",
        ruluhar: "\u2968",
        rx: "\u211E",
        Sacute: "\u015A",
        sacute: "\u015B",
        sbquo: "\u201A",
        Sc: "\u2ABC",
        sc: "\u227B",
        scap: "\u2AB8",
        Scaron: "\u0160",
        scaron: "\u0161",
        sccue: "\u227D",
        scE: "\u2AB4",
        sce: "\u2AB0",
        Scedil: "\u015E",
        scedil: "\u015F",
        Scirc: "\u015C",
        scirc: "\u015D",
        scnap: "\u2ABA",
        scnE: "\u2AB6",
        scnsim: "\u22E9",
        scpolint: "\u2A13",
        scsim: "\u227F",
        Scy: "\u0421",
        scy: "\u0441",
        sdot: "\u22C5",
        sdotb: "\u22A1",
        sdote: "\u2A66",
        searhk: "\u2925",
        seArr: "\u21D8",
        searr: "\u2198",
        searrow: "\u2198",
        sect: "\xA7",
        semi: ";",
        seswar: "\u2929",
        setminus: "\u2216",
        setmn: "\u2216",
        sext: "\u2736",
        Sfr: "\u{1D516}",
        sfr: "\u{1D530}",
        sfrown: "\u2322",
        sharp: "\u266F",
        SHCHcy: "\u0429",
        shchcy: "\u0449",
        SHcy: "\u0428",
        shcy: "\u0448",
        ShortDownArrow: "\u2193",
        ShortLeftArrow: "\u2190",
        shortmid: "\u2223",
        shortparallel: "\u2225",
        ShortRightArrow: "\u2192",
        ShortUpArrow: "\u2191",
        shy: "\xAD",
        Sigma: "\u03A3",
        sigma: "\u03C3",
        sigmaf: "\u03C2",
        sigmav: "\u03C2",
        sim: "\u223C",
        simdot: "\u2A6A",
        sime: "\u2243",
        simeq: "\u2243",
        simg: "\u2A9E",
        simgE: "\u2AA0",
        siml: "\u2A9D",
        simlE: "\u2A9F",
        simne: "\u2246",
        simplus: "\u2A24",
        simrarr: "\u2972",
        slarr: "\u2190",
        SmallCircle: "\u2218",
        smallsetminus: "\u2216",
        smashp: "\u2A33",
        smeparsl: "\u29E4",
        smid: "\u2223",
        smile: "\u2323",
        smt: "\u2AAA",
        smte: "\u2AAC",
        smtes: "\u2AAC\uFE00",
        SOFTcy: "\u042C",
        softcy: "\u044C",
        sol: "/",
        solb: "\u29C4",
        solbar: "\u233F",
        Sopf: "\u{1D54A}",
        sopf: "\u{1D564}",
        spades: "\u2660",
        spadesuit: "\u2660",
        spar: "\u2225",
        sqcap: "\u2293",
        sqcaps: "\u2293\uFE00",
        sqcup: "\u2294",
        sqcups: "\u2294\uFE00",
        Sqrt: "\u221A",
        sqsub: "\u228F",
        sqsube: "\u2291",
        sqsubset: "\u228F",
        sqsubseteq: "\u2291",
        sqsup: "\u2290",
        sqsupe: "\u2292",
        sqsupset: "\u2290",
        sqsupseteq: "\u2292",
        squ: "\u25A1",
        Square: "\u25A1",
        square: "\u25A1",
        SquareIntersection: "\u2293",
        SquareSubset: "\u228F",
        SquareSubsetEqual: "\u2291",
        SquareSuperset: "\u2290",
        SquareSupersetEqual: "\u2292",
        SquareUnion: "\u2294",
        squarf: "\u25AA",
        squf: "\u25AA",
        srarr: "\u2192",
        Sscr: "\u{1D4AE}",
        sscr: "\u{1D4C8}",
        ssetmn: "\u2216",
        ssmile: "\u2323",
        sstarf: "\u22C6",
        Star: "\u22C6",
        star: "\u2606",
        starf: "\u2605",
        straightepsilon: "\u03F5",
        straightphi: "\u03D5",
        strns: "\xAF",
        Sub: "\u22D0",
        sub: "\u2282",
        subdot: "\u2ABD",
        subE: "\u2AC5",
        sube: "\u2286",
        subedot: "\u2AC3",
        submult: "\u2AC1",
        subnE: "\u2ACB",
        subne: "\u228A",
        subplus: "\u2ABF",
        subrarr: "\u2979",
        Subset: "\u22D0",
        subset: "\u2282",
        subseteq: "\u2286",
        subseteqq: "\u2AC5",
        SubsetEqual: "\u2286",
        subsetneq: "\u228A",
        subsetneqq: "\u2ACB",
        subsim: "\u2AC7",
        subsub: "\u2AD5",
        subsup: "\u2AD3",
        succ: "\u227B",
        succapprox: "\u2AB8",
        succcurlyeq: "\u227D",
        Succeeds: "\u227B",
        SucceedsEqual: "\u2AB0",
        SucceedsSlantEqual: "\u227D",
        SucceedsTilde: "\u227F",
        succeq: "\u2AB0",
        succnapprox: "\u2ABA",
        succneqq: "\u2AB6",
        succnsim: "\u22E9",
        succsim: "\u227F",
        SuchThat: "\u220B",
        Sum: "\u2211",
        sum: "\u2211",
        sung: "\u266A",
        Sup: "\u22D1",
        sup: "\u2283",
        sup1: "\xB9",
        sup2: "\xB2",
        sup3: "\xB3",
        supdot: "\u2ABE",
        supdsub: "\u2AD8",
        supE: "\u2AC6",
        supe: "\u2287",
        supedot: "\u2AC4",
        Superset: "\u2283",
        SupersetEqual: "\u2287",
        suphsol: "\u27C9",
        suphsub: "\u2AD7",
        suplarr: "\u297B",
        supmult: "\u2AC2",
        supnE: "\u2ACC",
        supne: "\u228B",
        supplus: "\u2AC0",
        Supset: "\u22D1",
        supset: "\u2283",
        supseteq: "\u2287",
        supseteqq: "\u2AC6",
        supsetneq: "\u228B",
        supsetneqq: "\u2ACC",
        supsim: "\u2AC8",
        supsub: "\u2AD4",
        supsup: "\u2AD6",
        swarhk: "\u2926",
        swArr: "\u21D9",
        swarr: "\u2199",
        swarrow: "\u2199",
        swnwar: "\u292A",
        szlig: "\xDF",
        Tab: "	",
        target: "\u2316",
        Tau: "\u03A4",
        tau: "\u03C4",
        tbrk: "\u23B4",
        Tcaron: "\u0164",
        tcaron: "\u0165",
        Tcedil: "\u0162",
        tcedil: "\u0163",
        Tcy: "\u0422",
        tcy: "\u0442",
        tdot: "\u20DB",
        telrec: "\u2315",
        Tfr: "\u{1D517}",
        tfr: "\u{1D531}",
        there4: "\u2234",
        Therefore: "\u2234",
        therefore: "\u2234",
        Theta: "\u0398",
        theta: "\u03B8",
        thetasym: "\u03D1",
        thetav: "\u03D1",
        thickapprox: "\u2248",
        thicksim: "\u223C",
        ThickSpace: "\u205F\u200A",
        thinsp: "\u2009",
        ThinSpace: "\u2009",
        thkap: "\u2248",
        thksim: "\u223C",
        THORN: "\xDE",
        thorn: "\xFE",
        Tilde: "\u223C",
        tilde: "\u02DC",
        TildeEqual: "\u2243",
        TildeFullEqual: "\u2245",
        TildeTilde: "\u2248",
        times: "\xD7",
        timesb: "\u22A0",
        timesbar: "\u2A31",
        timesd: "\u2A30",
        tint: "\u222D",
        toea: "\u2928",
        top: "\u22A4",
        topbot: "\u2336",
        topcir: "\u2AF1",
        Topf: "\u{1D54B}",
        topf: "\u{1D565}",
        topfork: "\u2ADA",
        tosa: "\u2929",
        tprime: "\u2034",
        TRADE: "\u2122",
        trade: "\u2122",
        triangle: "\u25B5",
        triangledown: "\u25BF",
        triangleleft: "\u25C3",
        trianglelefteq: "\u22B4",
        triangleq: "\u225C",
        triangleright: "\u25B9",
        trianglerighteq: "\u22B5",
        tridot: "\u25EC",
        trie: "\u225C",
        triminus: "\u2A3A",
        TripleDot: "\u20DB",
        triplus: "\u2A39",
        trisb: "\u29CD",
        tritime: "\u2A3B",
        trpezium: "\u23E2",
        Tscr: "\u{1D4AF}",
        tscr: "\u{1D4C9}",
        TScy: "\u0426",
        tscy: "\u0446",
        TSHcy: "\u040B",
        tshcy: "\u045B",
        Tstrok: "\u0166",
        tstrok: "\u0167",
        twixt: "\u226C",
        twoheadleftarrow: "\u219E",
        twoheadrightarrow: "\u21A0",
        Uacute: "\xDA",
        uacute: "\xFA",
        Uarr: "\u219F",
        uArr: "\u21D1",
        uarr: "\u2191",
        Uarrocir: "\u2949",
        Ubrcy: "\u040E",
        ubrcy: "\u045E",
        Ubreve: "\u016C",
        ubreve: "\u016D",
        Ucirc: "\xDB",
        ucirc: "\xFB",
        Ucy: "\u0423",
        ucy: "\u0443",
        udarr: "\u21C5",
        Udblac: "\u0170",
        udblac: "\u0171",
        udhar: "\u296E",
        ufisht: "\u297E",
        Ufr: "\u{1D518}",
        ufr: "\u{1D532}",
        Ugrave: "\xD9",
        ugrave: "\xF9",
        uHar: "\u2963",
        uharl: "\u21BF",
        uharr: "\u21BE",
        uhblk: "\u2580",
        ulcorn: "\u231C",
        ulcorner: "\u231C",
        ulcrop: "\u230F",
        ultri: "\u25F8",
        Umacr: "\u016A",
        umacr: "\u016B",
        uml: "\xA8",
        UnderBar: "_",
        UnderBrace: "\u23DF",
        UnderBracket: "\u23B5",
        UnderParenthesis: "\u23DD",
        Union: "\u22C3",
        UnionPlus: "\u228E",
        Uogon: "\u0172",
        uogon: "\u0173",
        Uopf: "\u{1D54C}",
        uopf: "\u{1D566}",
        UpArrow: "\u2191",
        Uparrow: "\u21D1",
        uparrow: "\u2191",
        UpArrowBar: "\u2912",
        UpArrowDownArrow: "\u21C5",
        UpDownArrow: "\u2195",
        Updownarrow: "\u21D5",
        updownarrow: "\u2195",
        UpEquilibrium: "\u296E",
        upharpoonleft: "\u21BF",
        upharpoonright: "\u21BE",
        uplus: "\u228E",
        UpperLeftArrow: "\u2196",
        UpperRightArrow: "\u2197",
        Upsi: "\u03D2",
        upsi: "\u03C5",
        upsih: "\u03D2",
        Upsilon: "\u03A5",
        upsilon: "\u03C5",
        UpTee: "\u22A5",
        UpTeeArrow: "\u21A5",
        upuparrows: "\u21C8",
        urcorn: "\u231D",
        urcorner: "\u231D",
        urcrop: "\u230E",
        Uring: "\u016E",
        uring: "\u016F",
        urtri: "\u25F9",
        Uscr: "\u{1D4B0}",
        uscr: "\u{1D4CA}",
        utdot: "\u22F0",
        Utilde: "\u0168",
        utilde: "\u0169",
        utri: "\u25B5",
        utrif: "\u25B4",
        uuarr: "\u21C8",
        Uuml: "\xDC",
        uuml: "\xFC",
        uwangle: "\u29A7",
        vangrt: "\u299C",
        varepsilon: "\u03F5",
        varkappa: "\u03F0",
        varnothing: "\u2205",
        varphi: "\u03D5",
        varpi: "\u03D6",
        varpropto: "\u221D",
        vArr: "\u21D5",
        varr: "\u2195",
        varrho: "\u03F1",
        varsigma: "\u03C2",
        varsubsetneq: "\u228A\uFE00",
        varsubsetneqq: "\u2ACB\uFE00",
        varsupsetneq: "\u228B\uFE00",
        varsupsetneqq: "\u2ACC\uFE00",
        vartheta: "\u03D1",
        vartriangleleft: "\u22B2",
        vartriangleright: "\u22B3",
        Vbar: "\u2AEB",
        vBar: "\u2AE8",
        vBarv: "\u2AE9",
        Vcy: "\u0412",
        vcy: "\u0432",
        VDash: "\u22AB",
        Vdash: "\u22A9",
        vDash: "\u22A8",
        vdash: "\u22A2",
        Vdashl: "\u2AE6",
        Vee: "\u22C1",
        vee: "\u2228",
        veebar: "\u22BB",
        veeeq: "\u225A",
        vellip: "\u22EE",
        Verbar: "\u2016",
        verbar: "|",
        Vert: "\u2016",
        vert: "|",
        VerticalBar: "\u2223",
        VerticalLine: "|",
        VerticalSeparator: "\u2758",
        VerticalTilde: "\u2240",
        VeryThinSpace: "\u200A",
        Vfr: "\u{1D519}",
        vfr: "\u{1D533}",
        vltri: "\u22B2",
        vnsub: "\u2282\u20D2",
        vnsup: "\u2283\u20D2",
        Vopf: "\u{1D54D}",
        vopf: "\u{1D567}",
        vprop: "\u221D",
        vrtri: "\u22B3",
        Vscr: "\u{1D4B1}",
        vscr: "\u{1D4CB}",
        vsubnE: "\u2ACB\uFE00",
        vsubne: "\u228A\uFE00",
        vsupnE: "\u2ACC\uFE00",
        vsupne: "\u228B\uFE00",
        Vvdash: "\u22AA",
        vzigzag: "\u299A",
        Wcirc: "\u0174",
        wcirc: "\u0175",
        wedbar: "\u2A5F",
        Wedge: "\u22C0",
        wedge: "\u2227",
        wedgeq: "\u2259",
        weierp: "\u2118",
        Wfr: "\u{1D51A}",
        wfr: "\u{1D534}",
        Wopf: "\u{1D54E}",
        wopf: "\u{1D568}",
        wp: "\u2118",
        wr: "\u2240",
        wreath: "\u2240",
        Wscr: "\u{1D4B2}",
        wscr: "\u{1D4CC}",
        xcap: "\u22C2",
        xcirc: "\u25EF",
        xcup: "\u22C3",
        xdtri: "\u25BD",
        Xfr: "\u{1D51B}",
        xfr: "\u{1D535}",
        xhArr: "\u27FA",
        xharr: "\u27F7",
        Xi: "\u039E",
        xi: "\u03BE",
        xlArr: "\u27F8",
        xlarr: "\u27F5",
        xmap: "\u27FC",
        xnis: "\u22FB",
        xodot: "\u2A00",
        Xopf: "\u{1D54F}",
        xopf: "\u{1D569}",
        xoplus: "\u2A01",
        xotime: "\u2A02",
        xrArr: "\u27F9",
        xrarr: "\u27F6",
        Xscr: "\u{1D4B3}",
        xscr: "\u{1D4CD}",
        xsqcup: "\u2A06",
        xuplus: "\u2A04",
        xutri: "\u25B3",
        xvee: "\u22C1",
        xwedge: "\u22C0",
        Yacute: "\xDD",
        yacute: "\xFD",
        YAcy: "\u042F",
        yacy: "\u044F",
        Ycirc: "\u0176",
        ycirc: "\u0177",
        Ycy: "\u042B",
        ycy: "\u044B",
        yen: "\xA5",
        Yfr: "\u{1D51C}",
        yfr: "\u{1D536}",
        YIcy: "\u0407",
        yicy: "\u0457",
        Yopf: "\u{1D550}",
        yopf: "\u{1D56A}",
        Yscr: "\u{1D4B4}",
        yscr: "\u{1D4CE}",
        YUcy: "\u042E",
        yucy: "\u044E",
        Yuml: "\u0178",
        yuml: "\xFF",
        Zacute: "\u0179",
        zacute: "\u017A",
        Zcaron: "\u017D",
        zcaron: "\u017E",
        Zcy: "\u0417",
        zcy: "\u0437",
        Zdot: "\u017B",
        zdot: "\u017C",
        zeetrf: "\u2128",
        ZeroWidthSpace: "\u200B",
        Zeta: "\u0396",
        zeta: "\u03B6",
        Zfr: "\u2128",
        zfr: "\u{1D537}",
        ZHcy: "\u0416",
        zhcy: "\u0436",
        zigrarr: "\u21DD",
        Zopf: "\u2124",
        zopf: "\u{1D56B}",
        Zscr: "\u{1D4B5}",
        zscr: "\u{1D4CF}",
        zwj: "\u200D",
        zwnj: "\u200C"
      });
      exports2.entityMap = exports2.HTML_ENTITIES;
    }
  });

  // node_modules/@xmldom/xmldom/lib/sax.js
  var require_sax = __commonJS({
    "node_modules/@xmldom/xmldom/lib/sax.js"(exports2) {
      "use strict";
      var conventions = require_conventions();
      var g = require_grammar();
      var errors = require_errors2();
      var isHTMLEscapableRawTextElement = conventions.isHTMLEscapableRawTextElement;
      var isHTMLMimeType = conventions.isHTMLMimeType;
      var isHTMLRawTextElement = conventions.isHTMLRawTextElement;
      var hasOwn = conventions.hasOwn;
      var NAMESPACE = conventions.NAMESPACE;
      var ParseError = errors.ParseError;
      var DOMException = errors.DOMException;
      var S_TAG = 0;
      var S_ATTR = 1;
      var S_ATTR_SPACE = 2;
      var S_EQ = 3;
      var S_ATTR_NOQUOT_VALUE = 4;
      var S_ATTR_END = 5;
      var S_TAG_SPACE = 6;
      var S_TAG_CLOSE = 7;
      function XMLReader() {
      }
      XMLReader.prototype = {
        parse: function(source, defaultNSMap, entityMap) {
          var domBuilder = this.domBuilder;
          domBuilder.startDocument();
          _copy(defaultNSMap, defaultNSMap = /* @__PURE__ */ Object.create(null));
          parse(source, defaultNSMap, entityMap, domBuilder, this.errorHandler);
          domBuilder.endDocument();
        }
      };
      var ENTITY_REG = /&#?\w+;?/g;
      function parse(source, defaultNSMapCopy, entityMap, domBuilder, errorHandler) {
        var isHTML = isHTMLMimeType(domBuilder.mimeType);
        if (source.indexOf(g.UNICODE_REPLACEMENT_CHARACTER) >= 0) {
          errorHandler.warning("Unicode replacement character detected, source encoding issues?");
        }
        function fixedFromCharCode(code) {
          if (code > 65535) {
            code -= 65536;
            var surrogate1 = 55296 + (code >> 10), surrogate2 = 56320 + (code & 1023);
            return String.fromCharCode(surrogate1, surrogate2);
          } else {
            return String.fromCharCode(code);
          }
        }
        function entityReplacer(a2) {
          var complete = a2[a2.length - 1] === ";" ? a2 : a2 + ";";
          if (!isHTML && complete !== a2) {
            errorHandler.error("EntityRef: expecting ;");
            return a2;
          }
          var match = g.Reference.exec(complete);
          if (!match || match[0].length !== complete.length) {
            errorHandler.error("entity not matching Reference production: " + a2);
            return a2;
          }
          var k = complete.slice(1, -1);
          if (hasOwn(entityMap, k)) {
            return entityMap[k];
          } else if (k.charAt(0) === "#") {
            return fixedFromCharCode(parseInt(k.substring(1).replace("x", "0x")));
          } else {
            errorHandler.error("entity not found:" + a2);
            return a2;
          }
        }
        function appendText(end2) {
          if (end2 > start) {
            var xt = source.substring(start, end2).replace(ENTITY_REG, entityReplacer);
            locator && position(start);
            domBuilder.characters(xt, 0, end2 - start);
            start = end2;
          }
        }
        var lineStart = 0;
        var lineEnd = 0;
        var linePattern = /\r\n?|\n|$/g;
        var locator = domBuilder.locator;
        function position(p, m) {
          while (p >= lineEnd && (m = linePattern.exec(source))) {
            lineStart = lineEnd;
            lineEnd = m.index + m[0].length;
            locator.lineNumber++;
          }
          locator.columnNumber = p - lineStart + 1;
        }
        var parseStack = [{ currentNSMap: defaultNSMapCopy }];
        var unclosedTags = [];
        var start = 0;
        while (true) {
          try {
            var tagStart = source.indexOf("<", start);
            if (tagStart < 0) {
              if (!isHTML && unclosedTags.length > 0) {
                return errorHandler.fatalError("unclosed xml tag(s): " + unclosedTags.join(", "));
              }
              if (!source.substring(start).match(/^\s*$/)) {
                var doc = domBuilder.doc;
                var text = doc.createTextNode(source.substring(start));
                if (doc.documentElement) {
                  return errorHandler.error("Extra content at the end of the document");
                }
                doc.appendChild(text);
                domBuilder.currentElement = text;
              }
              return;
            }
            if (tagStart > start) {
              var fromSource = source.substring(start, tagStart);
              if (!isHTML && unclosedTags.length === 0) {
                fromSource = fromSource.replace(new RegExp(g.S_OPT.source, "g"), "");
                fromSource && errorHandler.error("Unexpected content outside root element: '" + fromSource + "'");
              }
              appendText(tagStart);
            }
            switch (source.charAt(tagStart + 1)) {
              case "/":
                var end = source.indexOf(">", tagStart + 2);
                var tagNameRaw = source.substring(tagStart + 2, end > 0 ? end : void 0);
                if (!tagNameRaw) {
                  return errorHandler.fatalError("end tag name missing");
                }
                var tagNameMatch = end > 0 && g.reg("^", g.QName_group, g.S_OPT, "$").exec(tagNameRaw);
                if (!tagNameMatch) {
                  return errorHandler.fatalError('end tag name contains invalid characters: "' + tagNameRaw + '"');
                }
                if (!domBuilder.currentElement && !domBuilder.doc.documentElement) {
                  return;
                }
                var currentTagName = unclosedTags[unclosedTags.length - 1] || domBuilder.currentElement.tagName || domBuilder.doc.documentElement.tagName || "";
                if (currentTagName !== tagNameMatch[1]) {
                  var tagNameLower = tagNameMatch[1].toLowerCase();
                  if (!isHTML || currentTagName.toLowerCase() !== tagNameLower) {
                    return errorHandler.fatalError('Opening and ending tag mismatch: "' + currentTagName + '" != "' + tagNameRaw + '"');
                  }
                }
                var config = parseStack.pop();
                unclosedTags.pop();
                var localNSMap = config.localNSMap;
                domBuilder.endElement(config.uri, config.localName, currentTagName);
                if (localNSMap) {
                  for (var prefix in localNSMap) {
                    if (hasOwn(localNSMap, prefix)) {
                      domBuilder.endPrefixMapping(prefix);
                    }
                  }
                }
                end++;
                break;
              // end element
              case "?":
                locator && position(tagStart);
                end = parseProcessingInstruction(source, tagStart, domBuilder, errorHandler);
                break;
              case "!":
                locator && position(tagStart);
                end = parseDoctypeCommentOrCData(source, tagStart, domBuilder, errorHandler, isHTML);
                break;
              default:
                locator && position(tagStart);
                var el = new ElementAttributes();
                var currentNSMap = parseStack[parseStack.length - 1].currentNSMap;
                var end = parseElementStartPart(source, tagStart, el, currentNSMap, entityReplacer, errorHandler, isHTML);
                var len = el.length;
                if (!el.closed) {
                  if (isHTML && conventions.isHTMLVoidElement(el.tagName)) {
                    el.closed = true;
                  } else {
                    unclosedTags.push(el.tagName);
                  }
                }
                if (locator && len) {
                  var locator2 = copyLocator(locator, {});
                  for (var i = 0; i < len; i++) {
                    var a = el[i];
                    position(a.offset);
                    a.locator = copyLocator(locator, {});
                  }
                  domBuilder.locator = locator2;
                  if (appendElement(el, domBuilder, currentNSMap)) {
                    parseStack.push(el);
                  }
                  domBuilder.locator = locator;
                } else {
                  if (appendElement(el, domBuilder, currentNSMap)) {
                    parseStack.push(el);
                  }
                }
                if (isHTML && !el.closed) {
                  end = parseHtmlSpecialContent(source, end, el.tagName, entityReplacer, domBuilder);
                } else {
                  end++;
                }
            }
          } catch (e) {
            if (e instanceof ParseError) {
              throw e;
            } else if (e instanceof DOMException) {
              throw new ParseError(e.name + ": " + e.message, domBuilder.locator, e);
            }
            errorHandler.error("element parse error: " + e);
            end = -1;
          }
          if (end > start) {
            start = end;
          } else {
            appendText(Math.max(tagStart, start) + 1);
          }
        }
      }
      function copyLocator(f, t) {
        t.lineNumber = f.lineNumber;
        t.columnNumber = f.columnNumber;
        return t;
      }
      function parseElementStartPart(source, start, el, currentNSMap, entityReplacer, errorHandler, isHTML) {
        function addAttribute(qname, value2, startIndex) {
          if (hasOwn(el.attributeNames, qname)) {
            return errorHandler.fatalError("Attribute " + qname + " redefined");
          }
          if (!isHTML && value2.indexOf("<") >= 0) {
            return errorHandler.fatalError("Unescaped '<' not allowed in attributes values");
          }
          el.addValue(
            qname,
            // @see https://www.w3.org/TR/xml/#AVNormalize
            // since the xmldom sax parser does not "interpret" DTD the following is not implemented:
            // - recursive replacement of (DTD) entity references
            // - trimming and collapsing multiple spaces into a single one for attributes that are not of type CDATA
            value2.replace(/[\t\n\r]/g, " ").replace(ENTITY_REG, entityReplacer),
            startIndex
          );
        }
        var attrName;
        var value;
        var p = ++start;
        var s = S_TAG;
        while (true) {
          var c = source.charAt(p);
          switch (c) {
            case "=":
              if (s === S_ATTR) {
                attrName = source.slice(start, p);
                s = S_EQ;
              } else if (s === S_ATTR_SPACE) {
                s = S_EQ;
              } else {
                throw new Error("attribute equal must after attrName");
              }
              break;
            case "'":
            case '"':
              if (s === S_EQ || s === S_ATTR) {
                if (s === S_ATTR) {
                  errorHandler.warning('attribute value must after "="');
                  attrName = source.slice(start, p);
                }
                start = p + 1;
                p = source.indexOf(c, start);
                if (p > 0) {
                  value = source.slice(start, p);
                  addAttribute(attrName, value, start - 1);
                  s = S_ATTR_END;
                } else {
                  throw new Error("attribute value no end '" + c + "' match");
                }
              } else if (s == S_ATTR_NOQUOT_VALUE) {
                value = source.slice(start, p);
                addAttribute(attrName, value, start);
                errorHandler.warning('attribute "' + attrName + '" missed start quot(' + c + ")!!");
                start = p + 1;
                s = S_ATTR_END;
              } else {
                throw new Error('attribute value must after "="');
              }
              break;
            case "/":
              switch (s) {
                case S_TAG:
                  el.setTagName(source.slice(start, p));
                case S_ATTR_END:
                case S_TAG_SPACE:
                case S_TAG_CLOSE:
                  s = S_TAG_CLOSE;
                  el.closed = true;
                case S_ATTR_NOQUOT_VALUE:
                case S_ATTR:
                  break;
                case S_ATTR_SPACE:
                  el.closed = true;
                  break;
                //case S_EQ:
                default:
                  throw new Error("attribute invalid close char('/')");
              }
              break;
            case "":
              errorHandler.error("unexpected end of input");
              if (s == S_TAG) {
                el.setTagName(source.slice(start, p));
              }
              return p;
            case ">":
              switch (s) {
                case S_TAG:
                  el.setTagName(source.slice(start, p));
                case S_ATTR_END:
                case S_TAG_SPACE:
                case S_TAG_CLOSE:
                  break;
                //normal
                case S_ATTR_NOQUOT_VALUE:
                //Compatible state
                case S_ATTR:
                  value = source.slice(start, p);
                  if (value.slice(-1) === "/") {
                    el.closed = true;
                    value = value.slice(0, -1);
                  }
                case S_ATTR_SPACE:
                  if (s === S_ATTR_SPACE) {
                    value = attrName;
                  }
                  if (s == S_ATTR_NOQUOT_VALUE) {
                    errorHandler.warning('attribute "' + value + '" missed quot(")!');
                    addAttribute(attrName, value, start);
                  } else {
                    if (!isHTML) {
                      errorHandler.warning('attribute "' + value + '" missed value!! "' + value + '" instead!!');
                    }
                    addAttribute(value, value, start);
                  }
                  break;
                case S_EQ:
                  if (!isHTML) {
                    return errorHandler.fatalError(`AttValue: ' or " expected`);
                  }
              }
              return p;
            /*xml space '\x20' | #x9 | #xD | #xA; */
            case "\x80":
              c = " ";
            default:
              if (c <= " ") {
                switch (s) {
                  case S_TAG:
                    el.setTagName(source.slice(start, p));
                    s = S_TAG_SPACE;
                    break;
                  case S_ATTR:
                    attrName = source.slice(start, p);
                    s = S_ATTR_SPACE;
                    break;
                  case S_ATTR_NOQUOT_VALUE:
                    var value = source.slice(start, p);
                    errorHandler.warning('attribute "' + value + '" missed quot(")!!');
                    addAttribute(attrName, value, start);
                  case S_ATTR_END:
                    s = S_TAG_SPACE;
                    break;
                }
              } else {
                switch (s) {
                  //case S_TAG:void();break;
                  //case S_ATTR:void();break;
                  //case S_ATTR_NOQUOT_VALUE:void();break;
                  case S_ATTR_SPACE:
                    if (!isHTML) {
                      errorHandler.warning('attribute "' + attrName + '" missed value!! "' + attrName + '" instead2!!');
                    }
                    addAttribute(attrName, attrName, start);
                    start = p;
                    s = S_ATTR;
                    break;
                  case S_ATTR_END:
                    errorHandler.warning('attribute space is required"' + attrName + '"!!');
                  case S_TAG_SPACE:
                    s = S_ATTR;
                    start = p;
                    break;
                  case S_EQ:
                    s = S_ATTR_NOQUOT_VALUE;
                    start = p;
                    break;
                  case S_TAG_CLOSE:
                    throw new Error("elements closed character '/' and '>' must be connected to");
                }
              }
          }
          p++;
        }
      }
      function appendElement(el, domBuilder, currentNSMap) {
        var tagName = el.tagName;
        var localNSMap = null;
        var i = el.length;
        while (i--) {
          var a = el[i];
          var qName = a.qName;
          var value = a.value;
          var nsp = qName.indexOf(":");
          if (nsp > 0) {
            var prefix = a.prefix = qName.slice(0, nsp);
            var localName = qName.slice(nsp + 1);
            var nsPrefix = prefix === "xmlns" && localName;
          } else {
            localName = qName;
            prefix = null;
            nsPrefix = qName === "xmlns" && "";
          }
          a.localName = localName;
          if (nsPrefix !== false) {
            if (localNSMap == null) {
              localNSMap = /* @__PURE__ */ Object.create(null);
              _copy(currentNSMap, currentNSMap = /* @__PURE__ */ Object.create(null));
            }
            currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
            a.uri = NAMESPACE.XMLNS;
            domBuilder.startPrefixMapping(nsPrefix, value);
          }
        }
        var i = el.length;
        while (i--) {
          a = el[i];
          if (a.prefix) {
            if (a.prefix === "xml") {
              a.uri = NAMESPACE.XML;
            }
            if (a.prefix !== "xmlns") {
              a.uri = currentNSMap[a.prefix];
            }
          }
        }
        var nsp = tagName.indexOf(":");
        if (nsp > 0) {
          prefix = el.prefix = tagName.slice(0, nsp);
          localName = el.localName = tagName.slice(nsp + 1);
        } else {
          prefix = null;
          localName = el.localName = tagName;
        }
        var ns = el.uri = currentNSMap[prefix || ""];
        domBuilder.startElement(ns, localName, tagName, el);
        if (el.closed) {
          domBuilder.endElement(ns, localName, tagName);
          if (localNSMap) {
            for (prefix in localNSMap) {
              if (hasOwn(localNSMap, prefix)) {
                domBuilder.endPrefixMapping(prefix);
              }
            }
          }
        } else {
          el.currentNSMap = currentNSMap;
          el.localNSMap = localNSMap;
          return true;
        }
      }
      function parseHtmlSpecialContent(source, elStartEnd, tagName, entityReplacer, domBuilder) {
        var isEscapableRaw = isHTMLEscapableRawTextElement(tagName);
        if (isEscapableRaw || isHTMLRawTextElement(tagName)) {
          var elEndStart = source.indexOf("</" + tagName + ">", elStartEnd);
          var text = source.substring(elStartEnd + 1, elEndStart);
          if (isEscapableRaw) {
            text = text.replace(ENTITY_REG, entityReplacer);
          }
          domBuilder.characters(text, 0, text.length);
          return elEndStart;
        }
        return elStartEnd + 1;
      }
      function _copy(source, target) {
        for (var n in source) {
          if (hasOwn(source, n)) {
            target[n] = source[n];
          }
        }
      }
      function parseUtils(source, start) {
        var index = start;
        function char(n) {
          n = n || 0;
          return source.charAt(index + n);
        }
        function skip(n) {
          n = n || 1;
          index += n;
        }
        function skipBlanks() {
          var blanks = 0;
          while (index < source.length) {
            var c = char();
            if (c !== " " && c !== "\n" && c !== "	" && c !== "\r") {
              return blanks;
            }
            blanks++;
            skip();
          }
          return -1;
        }
        function substringFromIndex() {
          return source.substring(index);
        }
        function substringStartsWith(text) {
          return source.substring(index, index + text.length) === text;
        }
        function substringStartsWithCaseInsensitive(text) {
          return source.substring(index, index + text.length).toUpperCase() === text.toUpperCase();
        }
        function getMatch(args) {
          var expr = g.reg("^", args);
          var match = expr.exec(substringFromIndex());
          if (match) {
            skip(match[0].length);
            return match[0];
          }
          return null;
        }
        return {
          char,
          getIndex: function() {
            return index;
          },
          getMatch,
          getSource: function() {
            return source;
          },
          skip,
          skipBlanks,
          substringFromIndex,
          substringStartsWith,
          substringStartsWithCaseInsensitive
        };
      }
      function parseDoctypeInternalSubset(p, errorHandler) {
        function parsePI(p2, errorHandler2) {
          var match = g.PI.exec(p2.substringFromIndex());
          if (!match) {
            return errorHandler2.fatalError("processing instruction is not well-formed at position " + p2.getIndex());
          }
          if (match[1].toLowerCase() === "xml") {
            return errorHandler2.fatalError(
              "xml declaration is only allowed at the start of the document, but found at position " + p2.getIndex()
            );
          }
          p2.skip(match[0].length);
          return match[0];
        }
        var source = p.getSource();
        if (p.char() === "[") {
          p.skip(1);
          var intSubsetStart = p.getIndex();
          while (p.getIndex() < source.length) {
            p.skipBlanks();
            if (p.char() === "]") {
              var internalSubset = source.substring(intSubsetStart, p.getIndex());
              p.skip(1);
              return internalSubset;
            }
            var current = null;
            if (p.char() === "<" && p.char(1) === "!") {
              switch (p.char(2)) {
                case "E":
                  if (p.char(3) === "L") {
                    current = p.getMatch(g.elementdecl);
                  } else if (p.char(3) === "N") {
                    current = p.getMatch(g.EntityDecl);
                  }
                  break;
                case "A":
                  current = p.getMatch(g.AttlistDecl);
                  break;
                case "N":
                  current = p.getMatch(g.NotationDecl);
                  break;
                case "-":
                  current = p.getMatch(g.Comment);
                  break;
              }
            } else if (p.char() === "<" && p.char(1) === "?") {
              current = parsePI(p, errorHandler);
            } else if (p.char() === "%") {
              current = p.getMatch(g.PEReference);
            } else {
              return errorHandler.fatalError("Error detected in Markup declaration");
            }
            if (!current) {
              return errorHandler.fatalError("Error in internal subset at position " + p.getIndex());
            }
          }
          return errorHandler.fatalError("doctype internal subset is not well-formed, missing ]");
        }
      }
      function parseDoctypeCommentOrCData(source, start, domBuilder, errorHandler, isHTML) {
        var p = parseUtils(source, start);
        switch (isHTML ? p.char(2).toUpperCase() : p.char(2)) {
          case "-":
            var comment = p.getMatch(g.Comment);
            if (comment) {
              domBuilder.comment(comment, g.COMMENT_START.length, comment.length - g.COMMENT_START.length - g.COMMENT_END.length);
              return p.getIndex();
            } else {
              return errorHandler.fatalError("comment is not well-formed at position " + p.getIndex());
            }
          case "[":
            var cdata = p.getMatch(g.CDSect);
            if (cdata) {
              if (!isHTML && !domBuilder.currentElement) {
                return errorHandler.fatalError("CDATA outside of element");
              }
              domBuilder.startCDATA();
              domBuilder.characters(cdata, g.CDATA_START.length, cdata.length - g.CDATA_START.length - g.CDATA_END.length);
              domBuilder.endCDATA();
              return p.getIndex();
            } else {
              return errorHandler.fatalError("Invalid CDATA starting at position " + start);
            }
          case "D": {
            if (domBuilder.doc && domBuilder.doc.documentElement) {
              return errorHandler.fatalError("Doctype not allowed inside or after documentElement at position " + p.getIndex());
            }
            if (isHTML ? !p.substringStartsWithCaseInsensitive(g.DOCTYPE_DECL_START) : !p.substringStartsWith(g.DOCTYPE_DECL_START)) {
              return errorHandler.fatalError("Expected " + g.DOCTYPE_DECL_START + " at position " + p.getIndex());
            }
            p.skip(g.DOCTYPE_DECL_START.length);
            if (p.skipBlanks() < 1) {
              return errorHandler.fatalError("Expected whitespace after " + g.DOCTYPE_DECL_START + " at position " + p.getIndex());
            }
            var doctype = {
              name: void 0,
              publicId: void 0,
              systemId: void 0,
              internalSubset: void 0
            };
            doctype.name = p.getMatch(g.Name);
            if (!doctype.name)
              return errorHandler.fatalError("doctype name missing or contains unexpected characters at position " + p.getIndex());
            if (isHTML && doctype.name.toLowerCase() !== "html") {
              errorHandler.warning("Unexpected DOCTYPE in HTML document at position " + p.getIndex());
            }
            p.skipBlanks();
            if (p.substringStartsWith(g.PUBLIC) || p.substringStartsWith(g.SYSTEM)) {
              var match = g.ExternalID_match.exec(p.substringFromIndex());
              if (!match) {
                return errorHandler.fatalError("doctype external id is not well-formed at position " + p.getIndex());
              }
              if (match.groups.SystemLiteralOnly !== void 0) {
                doctype.systemId = match.groups.SystemLiteralOnly;
              } else {
                doctype.systemId = match.groups.SystemLiteral;
                doctype.publicId = match.groups.PubidLiteral;
              }
              p.skip(match[0].length);
            } else if (isHTML && p.substringStartsWithCaseInsensitive(g.SYSTEM)) {
              p.skip(g.SYSTEM.length);
              if (p.skipBlanks() < 1) {
                return errorHandler.fatalError("Expected whitespace after " + g.SYSTEM + " at position " + p.getIndex());
              }
              doctype.systemId = p.getMatch(g.ABOUT_LEGACY_COMPAT_SystemLiteral);
              if (!doctype.systemId) {
                return errorHandler.fatalError(
                  "Expected " + g.ABOUT_LEGACY_COMPAT + " in single or double quotes after " + g.SYSTEM + " at position " + p.getIndex()
                );
              }
            }
            if (isHTML && doctype.systemId && !g.ABOUT_LEGACY_COMPAT_SystemLiteral.test(doctype.systemId)) {
              errorHandler.warning("Unexpected doctype.systemId in HTML document at position " + p.getIndex());
            }
            if (!isHTML) {
              p.skipBlanks();
              doctype.internalSubset = parseDoctypeInternalSubset(p, errorHandler);
            }
            p.skipBlanks();
            if (p.char() !== ">") {
              return errorHandler.fatalError("doctype not terminated with > at position " + p.getIndex());
            }
            p.skip(1);
            domBuilder.startDTD(doctype.name, doctype.publicId, doctype.systemId, doctype.internalSubset);
            domBuilder.endDTD();
            return p.getIndex();
          }
          default:
            return errorHandler.fatalError('Not well-formed XML starting with "<!" at position ' + start);
        }
      }
      function parseProcessingInstruction(source, start, domBuilder, errorHandler) {
        var match = source.substring(start).match(g.PI);
        if (!match) {
          return errorHandler.fatalError("Invalid processing instruction starting at position " + start);
        }
        if (match[1].toLowerCase() === "xml") {
          if (start > 0) {
            return errorHandler.fatalError(
              "processing instruction at position " + start + " is an xml declaration which is only at the start of the document"
            );
          }
          if (!g.XMLDecl.test(source.substring(start))) {
            return errorHandler.fatalError("xml declaration is not well-formed");
          }
        }
        domBuilder.processingInstruction(match[1], match[2]);
        return start + match[0].length;
      }
      function ElementAttributes() {
        this.attributeNames = /* @__PURE__ */ Object.create(null);
      }
      ElementAttributes.prototype = {
        setTagName: function(tagName) {
          if (!g.QName_exact.test(tagName)) {
            throw new Error("invalid tagName:" + tagName);
          }
          this.tagName = tagName;
        },
        addValue: function(qName, value, offset) {
          if (!g.QName_exact.test(qName)) {
            throw new Error("invalid attribute:" + qName);
          }
          this.attributeNames[qName] = this.length;
          this[this.length++] = { qName, value, offset };
        },
        length: 0,
        getLocalName: function(i) {
          return this[i].localName;
        },
        getLocator: function(i) {
          return this[i].locator;
        },
        getQName: function(i) {
          return this[i].qName;
        },
        getURI: function(i) {
          return this[i].uri;
        },
        getValue: function(i) {
          return this[i].value;
        }
        //	,getIndex:function(uri, localName)){
        //		if(localName){
        //
        //		}else{
        //			var qName = uri
        //		}
        //	},
        //	getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
        //	getType:function(uri,localName){}
        //	getType:function(i){},
      };
      exports2.XMLReader = XMLReader;
      exports2.parseUtils = parseUtils;
      exports2.parseDoctypeCommentOrCData = parseDoctypeCommentOrCData;
    }
  });

  // node_modules/@xmldom/xmldom/lib/dom-parser.js
  var require_dom_parser = __commonJS({
    "node_modules/@xmldom/xmldom/lib/dom-parser.js"(exports2) {
      "use strict";
      var conventions = require_conventions();
      var dom = require_dom();
      var errors = require_errors2();
      var entities = require_entities();
      var sax = require_sax();
      var DOMImplementation = dom.DOMImplementation;
      var hasDefaultHTMLNamespace = conventions.hasDefaultHTMLNamespace;
      var isHTMLMimeType = conventions.isHTMLMimeType;
      var isValidMimeType = conventions.isValidMimeType;
      var MIME_TYPE = conventions.MIME_TYPE;
      var NAMESPACE = conventions.NAMESPACE;
      var ParseError = errors.ParseError;
      var XMLReader = sax.XMLReader;
      function normalizeLineEndings(input) {
        return input.replace(/\r[\n\u0085]/g, "\n").replace(/[\r\u0085\u2028\u2029]/g, "\n");
      }
      function DOMParser2(options) {
        options = options || {};
        if (options.locator === void 0) {
          options.locator = true;
        }
        this.assign = options.assign || conventions.assign;
        this.domHandler = options.domHandler || DOMHandler;
        this.onError = options.onError || options.errorHandler;
        if (options.errorHandler && typeof options.errorHandler !== "function") {
          throw new TypeError("errorHandler object is no longer supported, switch to onError!");
        } else if (options.errorHandler) {
          options.errorHandler("warning", "The `errorHandler` option has been deprecated, use `onError` instead!", this);
        }
        this.normalizeLineEndings = options.normalizeLineEndings || normalizeLineEndings;
        this.locator = !!options.locator;
        this.xmlns = this.assign(/* @__PURE__ */ Object.create(null), options.xmlns);
      }
      DOMParser2.prototype.parseFromString = function(source, mimeType) {
        if (!isValidMimeType(mimeType)) {
          throw new TypeError('DOMParser.parseFromString: the provided mimeType "' + mimeType + '" is not valid.');
        }
        var defaultNSMap = this.assign(/* @__PURE__ */ Object.create(null), this.xmlns);
        var entityMap = entities.XML_ENTITIES;
        var defaultNamespace = defaultNSMap[""] || null;
        if (hasDefaultHTMLNamespace(mimeType)) {
          entityMap = entities.HTML_ENTITIES;
          defaultNamespace = NAMESPACE.HTML;
        } else if (mimeType === MIME_TYPE.XML_SVG_IMAGE) {
          defaultNamespace = NAMESPACE.SVG;
        }
        defaultNSMap[""] = defaultNamespace;
        defaultNSMap.xml = defaultNSMap.xml || NAMESPACE.XML;
        var domBuilder = new this.domHandler({
          mimeType,
          defaultNamespace,
          onError: this.onError
        });
        var locator = this.locator ? {} : void 0;
        if (this.locator) {
          domBuilder.setDocumentLocator(locator);
        }
        var sax2 = new XMLReader();
        sax2.errorHandler = domBuilder;
        sax2.domBuilder = domBuilder;
        var isXml = !conventions.isHTMLMimeType(mimeType);
        if (isXml && typeof source !== "string") {
          sax2.errorHandler.fatalError("source is not a string");
        }
        sax2.parse(this.normalizeLineEndings(String(source)), defaultNSMap, entityMap);
        if (!domBuilder.doc.documentElement) {
          sax2.errorHandler.fatalError("missing root element");
        }
        return domBuilder.doc;
      };
      function DOMHandler(options) {
        var opt = options || {};
        this.mimeType = opt.mimeType || MIME_TYPE.XML_APPLICATION;
        this.defaultNamespace = opt.defaultNamespace || null;
        this.cdata = false;
        this.currentElement = void 0;
        this.doc = void 0;
        this.locator = void 0;
        this.onError = opt.onError;
      }
      function position(locator, node) {
        node.lineNumber = locator.lineNumber;
        node.columnNumber = locator.columnNumber;
      }
      DOMHandler.prototype = {
        /**
         * Either creates an XML or an HTML document and stores it under `this.doc`.
         * If it is an XML document, `this.defaultNamespace` is used to create it,
         * and it will not contain any `childNodes`.
         * If it is an HTML document, it will be created without any `childNodes`.
         *
         * @see http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
         */
        startDocument: function() {
          var impl = new DOMImplementation();
          this.doc = isHTMLMimeType(this.mimeType) ? impl.createHTMLDocument(false) : impl.createDocument(this.defaultNamespace, "");
        },
        startElement: function(namespaceURI, localName, qName, attrs) {
          var doc = this.doc;
          var el = doc.createElementNS(namespaceURI, qName || localName);
          var len = attrs.length;
          appendElement(this, el);
          this.currentElement = el;
          this.locator && position(this.locator, el);
          for (var i = 0; i < len; i++) {
            var namespaceURI = attrs.getURI(i);
            var value = attrs.getValue(i);
            var qName = attrs.getQName(i);
            var attr = doc.createAttributeNS(namespaceURI, qName);
            this.locator && position(attrs.getLocator(i), attr);
            attr.value = attr.nodeValue = value;
            el.setAttributeNode(attr);
          }
        },
        endElement: function(namespaceURI, localName, qName) {
          this.currentElement = this.currentElement.parentNode;
        },
        startPrefixMapping: function(prefix, uri) {
        },
        endPrefixMapping: function(prefix) {
        },
        processingInstruction: function(target, data) {
          var ins = this.doc.createProcessingInstruction(target, data);
          this.locator && position(this.locator, ins);
          appendElement(this, ins);
        },
        ignorableWhitespace: function(ch, start, length) {
        },
        characters: function(chars, start, length) {
          chars = _toString.apply(this, arguments);
          if (chars) {
            if (this.cdata) {
              var charNode = this.doc.createCDATASection(chars);
            } else {
              var charNode = this.doc.createTextNode(chars);
            }
            if (this.currentElement) {
              this.currentElement.appendChild(charNode);
            } else if (/^\s*$/.test(chars)) {
              this.doc.appendChild(charNode);
            }
            this.locator && position(this.locator, charNode);
          }
        },
        skippedEntity: function(name2) {
        },
        endDocument: function() {
          this.doc.normalize();
        },
        /**
         * Stores the locator to be able to set the `columnNumber` and `lineNumber`
         * on the created DOM nodes.
         *
         * @param {Locator} locator
         */
        setDocumentLocator: function(locator) {
          if (locator) {
            locator.lineNumber = 0;
          }
          this.locator = locator;
        },
        //LexicalHandler
        comment: function(chars, start, length) {
          chars = _toString.apply(this, arguments);
          var comm = this.doc.createComment(chars);
          this.locator && position(this.locator, comm);
          appendElement(this, comm);
        },
        startCDATA: function() {
          this.cdata = true;
        },
        endCDATA: function() {
          this.cdata = false;
        },
        startDTD: function(name2, publicId, systemId, internalSubset) {
          var impl = this.doc.implementation;
          if (impl && impl.createDocumentType) {
            var dt = impl.createDocumentType(name2, publicId, systemId, internalSubset);
            this.locator && position(this.locator, dt);
            appendElement(this, dt);
            this.doc.doctype = dt;
          }
        },
        reportError: function(level, message) {
          if (typeof this.onError === "function") {
            try {
              this.onError(level, message, this);
            } catch (e) {
              throw new ParseError("Reporting " + level + ' "' + message + '" caused ' + e, this.locator);
            }
          } else {
            console.error("[xmldom " + level + "]	" + message, _locator(this.locator));
          }
        },
        /**
         * @see http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
         */
        warning: function(message) {
          this.reportError("warning", message);
        },
        error: function(message) {
          this.reportError("error", message);
        },
        /**
         * This function reports a fatal error and throws a ParseError.
         *
         * @param {string} message
         * - The message to be used for reporting and throwing the error.
         * @returns {never}
         * This function always throws an error and never returns a value.
         * @throws {ParseError}
         * Always throws a ParseError with the provided message.
         */
        fatalError: function(message) {
          this.reportError("fatalError", message);
          throw new ParseError(message, this.locator);
        }
      };
      function _locator(l) {
        if (l) {
          return "\n@#[line:" + l.lineNumber + ",col:" + l.columnNumber + "]";
        }
      }
      function _toString(chars, start, length) {
        if (typeof chars == "string") {
          return chars.substr(start, length);
        } else {
          if (chars.length >= start + length || start) {
            return new java.lang.String(chars, start, length) + "";
          }
          return chars;
        }
      }
      "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(
        /\w+/g,
        function(key) {
          DOMHandler.prototype[key] = function() {
            return null;
          };
        }
      );
      function appendElement(handler, node) {
        if (!handler.currentElement) {
          handler.doc.appendChild(node);
        } else {
          handler.currentElement.appendChild(node);
        }
      }
      function onErrorStopParsing(level) {
        if (level === "error") throw "onErrorStopParsing";
      }
      function onWarningStopParsing() {
        throw "onWarningStopParsing";
      }
      exports2.__DOMHandler = DOMHandler;
      exports2.DOMParser = DOMParser2;
      exports2.normalizeLineEndings = normalizeLineEndings;
      exports2.onErrorStopParsing = onErrorStopParsing;
      exports2.onWarningStopParsing = onWarningStopParsing;
    }
  });

  // node_modules/@xmldom/xmldom/lib/index.js
  var require_lib = __commonJS({
    "node_modules/@xmldom/xmldom/lib/index.js"(exports2) {
      "use strict";
      var conventions = require_conventions();
      exports2.assign = conventions.assign;
      exports2.hasDefaultHTMLNamespace = conventions.hasDefaultHTMLNamespace;
      exports2.isHTMLMimeType = conventions.isHTMLMimeType;
      exports2.isValidMimeType = conventions.isValidMimeType;
      exports2.MIME_TYPE = conventions.MIME_TYPE;
      exports2.NAMESPACE = conventions.NAMESPACE;
      var errors = require_errors2();
      exports2.DOMException = errors.DOMException;
      exports2.DOMExceptionName = errors.DOMExceptionName;
      exports2.ExceptionCode = errors.ExceptionCode;
      exports2.ParseError = errors.ParseError;
      var dom = require_dom();
      exports2.Attr = dom.Attr;
      exports2.CDATASection = dom.CDATASection;
      exports2.CharacterData = dom.CharacterData;
      exports2.Comment = dom.Comment;
      exports2.Document = dom.Document;
      exports2.DocumentFragment = dom.DocumentFragment;
      exports2.DocumentType = dom.DocumentType;
      exports2.DOMImplementation = dom.DOMImplementation;
      exports2.Element = dom.Element;
      exports2.Entity = dom.Entity;
      exports2.EntityReference = dom.EntityReference;
      exports2.LiveNodeList = dom.LiveNodeList;
      exports2.NamedNodeMap = dom.NamedNodeMap;
      exports2.Node = dom.Node;
      exports2.NodeList = dom.NodeList;
      exports2.Notation = dom.Notation;
      exports2.ProcessingInstruction = dom.ProcessingInstruction;
      exports2.Text = dom.Text;
      exports2.XMLSerializer = dom.XMLSerializer;
      var domParser = require_dom_parser();
      exports2.DOMParser = domParser.DOMParser;
      exports2.normalizeLineEndings = domParser.normalizeLineEndings;
      exports2.onErrorStopParsing = domParser.onErrorStopParsing;
      exports2.onWarningStopParsing = domParser.onWarningStopParsing;
    }
  });

  // node_modules/xpath/xpath.js
  var require_xpath = __commonJS({
    "node_modules/xpath/xpath.js"(exports2) {
      var xpath = typeof exports2 === "undefined" ? {} : exports2;
      (function(exports3) {
        "use strict";
        var NAMESPACE_NODE_NODETYPE = "__namespace";
        var isNil = function(x) {
          return x === null || x === void 0;
        };
        var isValidNodeType = function(nodeType) {
          return nodeType === NAMESPACE_NODE_NODETYPE || Number.isInteger(nodeType) && nodeType >= 1 && nodeType <= 11;
        };
        var isNodeLike = function(value) {
          return value && isValidNodeType(value.nodeType) && typeof value.nodeName === "string";
        };
        function curry(func) {
          var slice = Array.prototype.slice, totalargs = func.length, partial = function(args, fn3) {
            return function() {
              return fn3.apply(this, args.concat(slice.call(arguments)));
            };
          }, fn2 = function() {
            var args = slice.call(arguments);
            return args.length < totalargs ? partial(args, fn2) : func.apply(this, slice.apply(arguments, [0, totalargs]));
          };
          return fn2;
        }
        var forEach = function(f, xs) {
          for (var i = 0; i < xs.length; i += 1) {
            f(xs[i], i, xs);
          }
        };
        var reduce = function(f, seed, xs) {
          var acc = seed;
          forEach(function(x, i) {
            acc = f(acc, x, i);
          }, xs);
          return acc;
        };
        var map = function(f, xs) {
          var mapped = new Array(xs.length);
          forEach(function(x, i) {
            mapped[i] = f(x);
          }, xs);
          return mapped;
        };
        var filter = function(f, xs) {
          var filtered = [];
          forEach(function(x, i) {
            if (f(x, i)) {
              filtered.push(x);
            }
          }, xs);
          return filtered;
        };
        var includes = function(values, value) {
          for (var i = 0; i < values.length; i += 1) {
            if (values[i] === value) {
              return true;
            }
          }
          return false;
        };
        function always(value) {
          return function() {
            return value;
          };
        }
        function toString(x) {
          return x.toString();
        }
        var join = function(s, xs) {
          return xs.join(s);
        };
        var wrap = function(pref, suf, str) {
          return pref + str + suf;
        };
        var prototypeConcat = Array.prototype.concat;
        var sortNodes = function(nodes, reverse) {
          var ns = new XNodeSet();
          ns.addArray(nodes);
          var sorted = ns.toArray();
          return reverse ? sorted.reverse() : sorted;
        };
        var MAX_ARGUMENT_LENGTH = 32767;
        function flatten(arr) {
          var result = [];
          for (var start = 0; start < arr.length; start += MAX_ARGUMENT_LENGTH) {
            var chunk = arr.slice(start, start + MAX_ARGUMENT_LENGTH);
            result = prototypeConcat.apply(result, chunk);
          }
          return result;
        }
        function assign(target, varArgs) {
          var to = Object(target);
          for (var index = 1; index < arguments.length; index++) {
            var nextSource = arguments[index];
            if (nextSource != null) {
              for (var nextKey in nextSource) {
                if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                  to[nextKey] = nextSource[nextKey];
                }
              }
            }
          }
          return to;
        }
        var NodeTypes = {
          ELEMENT_NODE: 1,
          ATTRIBUTE_NODE: 2,
          TEXT_NODE: 3,
          CDATA_SECTION_NODE: 4,
          PROCESSING_INSTRUCTION_NODE: 7,
          COMMENT_NODE: 8,
          DOCUMENT_NODE: 9,
          DOCUMENT_TYPE_NODE: 10,
          DOCUMENT_FRAGMENT_NODE: 11,
          NAMESPACE_NODE: NAMESPACE_NODE_NODETYPE
        };
        XPathParser.prototype = new Object();
        XPathParser.prototype.constructor = XPathParser;
        XPathParser.superclass = Object.prototype;
        function XPathParser() {
          this.init();
        }
        XPathParser.prototype.init = function() {
          this.reduceActions = [];
          this.reduceActions[3] = function(rhs) {
            return new OrOperation(rhs[0], rhs[2]);
          };
          this.reduceActions[5] = function(rhs) {
            return new AndOperation(rhs[0], rhs[2]);
          };
          this.reduceActions[7] = function(rhs) {
            return new EqualsOperation(rhs[0], rhs[2]);
          };
          this.reduceActions[8] = function(rhs) {
            return new NotEqualOperation(rhs[0], rhs[2]);
          };
          this.reduceActions[10] = function(rhs) {
            return new LessThanOperation(rhs[0], rhs[2]);
          };
          this.reduceActions[11] = function(rhs) {
            return new GreaterThanOperation(rhs[0], rhs[2]);
          };
          this.reduceActions[12] = function(rhs) {
            return new LessThanOrEqualOperation(rhs[0], rhs[2]);
          };
          this.reduceActions[13] = function(rhs) {
            return new GreaterThanOrEqualOperation(rhs[0], rhs[2]);
          };
          this.reduceActions[15] = function(rhs) {
            return new PlusOperation(rhs[0], rhs[2]);
          };
          this.reduceActions[16] = function(rhs) {
            return new MinusOperation(rhs[0], rhs[2]);
          };
          this.reduceActions[18] = function(rhs) {
            return new MultiplyOperation(rhs[0], rhs[2]);
          };
          this.reduceActions[19] = function(rhs) {
            return new DivOperation(rhs[0], rhs[2]);
          };
          this.reduceActions[20] = function(rhs) {
            return new ModOperation(rhs[0], rhs[2]);
          };
          this.reduceActions[22] = function(rhs) {
            return new UnaryMinusOperation(rhs[1]);
          };
          this.reduceActions[24] = function(rhs) {
            return new BarOperation(rhs[0], rhs[2]);
          };
          this.reduceActions[25] = function(rhs) {
            return new PathExpr(void 0, void 0, rhs[0]);
          };
          this.reduceActions[27] = function(rhs) {
            rhs[0].locationPath = rhs[2];
            return rhs[0];
          };
          this.reduceActions[28] = function(rhs) {
            rhs[0].locationPath = rhs[2];
            rhs[0].locationPath.steps.unshift(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, []));
            return rhs[0];
          };
          this.reduceActions[29] = function(rhs) {
            return new PathExpr(rhs[0], [], void 0);
          };
          this.reduceActions[30] = function(rhs) {
            if (Utilities.instance_of(rhs[0], PathExpr)) {
              if (rhs[0].filterPredicates == void 0) {
                rhs[0].filterPredicates = [];
              }
              rhs[0].filterPredicates.push(rhs[1]);
              return rhs[0];
            } else {
              return new PathExpr(rhs[0], [rhs[1]], void 0);
            }
          };
          this.reduceActions[32] = function(rhs) {
            return rhs[1];
          };
          this.reduceActions[33] = function(rhs) {
            return new XString(rhs[0]);
          };
          this.reduceActions[34] = function(rhs) {
            return new XNumber(rhs[0]);
          };
          this.reduceActions[36] = function(rhs) {
            return new FunctionCall(rhs[0], []);
          };
          this.reduceActions[37] = function(rhs) {
            return new FunctionCall(rhs[0], rhs[2]);
          };
          this.reduceActions[38] = function(rhs) {
            return [rhs[0]];
          };
          this.reduceActions[39] = function(rhs) {
            rhs[2].unshift(rhs[0]);
            return rhs[2];
          };
          this.reduceActions[43] = function(rhs) {
            return new LocationPath(true, []);
          };
          this.reduceActions[44] = function(rhs) {
            rhs[1].absolute = true;
            return rhs[1];
          };
          this.reduceActions[46] = function(rhs) {
            return new LocationPath(false, [rhs[0]]);
          };
          this.reduceActions[47] = function(rhs) {
            rhs[0].steps.push(rhs[2]);
            return rhs[0];
          };
          this.reduceActions[49] = function(rhs) {
            return new Step(rhs[0], rhs[1], []);
          };
          this.reduceActions[50] = function(rhs) {
            return new Step(Step.CHILD, rhs[0], []);
          };
          this.reduceActions[51] = function(rhs) {
            return new Step(rhs[0], rhs[1], rhs[2]);
          };
          this.reduceActions[52] = function(rhs) {
            return new Step(Step.CHILD, rhs[0], rhs[1]);
          };
          this.reduceActions[54] = function(rhs) {
            return [rhs[0]];
          };
          this.reduceActions[55] = function(rhs) {
            rhs[1].unshift(rhs[0]);
            return rhs[1];
          };
          this.reduceActions[56] = function(rhs) {
            if (rhs[0] == "ancestor") {
              return Step.ANCESTOR;
            } else if (rhs[0] == "ancestor-or-self") {
              return Step.ANCESTORORSELF;
            } else if (rhs[0] == "attribute") {
              return Step.ATTRIBUTE;
            } else if (rhs[0] == "child") {
              return Step.CHILD;
            } else if (rhs[0] == "descendant") {
              return Step.DESCENDANT;
            } else if (rhs[0] == "descendant-or-self") {
              return Step.DESCENDANTORSELF;
            } else if (rhs[0] == "following") {
              return Step.FOLLOWING;
            } else if (rhs[0] == "following-sibling") {
              return Step.FOLLOWINGSIBLING;
            } else if (rhs[0] == "namespace") {
              return Step.NAMESPACE;
            } else if (rhs[0] == "parent") {
              return Step.PARENT;
            } else if (rhs[0] == "preceding") {
              return Step.PRECEDING;
            } else if (rhs[0] == "preceding-sibling") {
              return Step.PRECEDINGSIBLING;
            } else if (rhs[0] == "self") {
              return Step.SELF;
            }
            return -1;
          };
          this.reduceActions[57] = function(rhs) {
            return Step.ATTRIBUTE;
          };
          this.reduceActions[59] = function(rhs) {
            if (rhs[0] == "comment") {
              return NodeTest.commentTest;
            } else if (rhs[0] == "text") {
              return NodeTest.textTest;
            } else if (rhs[0] == "processing-instruction") {
              return NodeTest.anyPiTest;
            } else if (rhs[0] == "node") {
              return NodeTest.nodeTest;
            }
            return new NodeTest(-1, void 0);
          };
          this.reduceActions[60] = function(rhs) {
            return new NodeTest.PITest(rhs[2]);
          };
          this.reduceActions[61] = function(rhs) {
            return rhs[1];
          };
          this.reduceActions[63] = function(rhs) {
            rhs[1].absolute = true;
            rhs[1].steps.unshift(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, []));
            return rhs[1];
          };
          this.reduceActions[64] = function(rhs) {
            rhs[0].steps.push(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, []));
            rhs[0].steps.push(rhs[2]);
            return rhs[0];
          };
          this.reduceActions[65] = function(rhs) {
            return new Step(Step.SELF, NodeTest.nodeTest, []);
          };
          this.reduceActions[66] = function(rhs) {
            return new Step(Step.PARENT, NodeTest.nodeTest, []);
          };
          this.reduceActions[67] = function(rhs) {
            return new VariableReference(rhs[1]);
          };
          this.reduceActions[68] = function(rhs) {
            return NodeTest.nameTestAny;
          };
          this.reduceActions[69] = function(rhs) {
            return new NodeTest.NameTestPrefixAny(rhs[0].split(":")[0]);
          };
          this.reduceActions[70] = function(rhs) {
            return new NodeTest.NameTestQName(rhs[0]);
          };
        };
        XPathParser.actionTable = [
          " s s        sssssssss    s ss  s  ss",
          "                 s                  ",
          "r  rrrrrrrrr         rrrrrrr rr  r  ",
          "                rrrrr               ",
          " s s        sssssssss    s ss  s  ss",
          "rs  rrrrrrrr s  sssssrrrrrr  rrs rs ",
          " s s        sssssssss    s ss  s  ss",
          "                            s       ",
          "                            s       ",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          "  s                                 ",
          "                            s       ",
          " s           s  sssss          s  s ",
          "r  rrrrrrrrr         rrrrrrr rr  r  ",
          "a                                   ",
          "r       s                    rr  r  ",
          "r      sr                    rr  r  ",
          "r   s  rr            s       rr  r  ",
          "r   rssrr            rss     rr  r  ",
          "r   rrrrr            rrrss   rr  r  ",
          "r   rrrrrsss         rrrrr   rr  r  ",
          "r   rrrrrrrr         rrrrr   rr  r  ",
          "r   rrrrrrrr         rrrrrs  rr  r  ",
          "r   rrrrrrrr         rrrrrr  rr  r  ",
          "r   rrrrrrrr         rrrrrr  rr  r  ",
          "r  srrrrrrrr         rrrrrrs rr sr  ",
          "r  srrrrrrrr         rrrrrrs rr  r  ",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          "r   rrrrrrrr         rrrrrr  rr  r  ",
          "r   rrrrrrrr         rrrrrr  rr  r  ",
          "r  rrrrrrrrr         rrrrrrr rr  r  ",
          "r  rrrrrrrrr         rrrrrrr rr  r  ",
          "                sssss               ",
          "r  rrrrrrrrr         rrrrrrr rr sr  ",
          "r  rrrrrrrrr         rrrrrrr rr  r  ",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          "                             s      ",
          "r  srrrrrrrr         rrrrrrs rr  r  ",
          "r   rrrrrrrr         rrrrr   rr  r  ",
          "              s                     ",
          "                             s      ",
          "                rrrrr               ",
          " s s        sssssssss    s sss s  ss",
          "r  srrrrrrrr         rrrrrrs rr  r  ",
          " s s        sssssssss    s ss  s  ss",
          " s s        sssssssss    s ss  s  ss",
          " s s        sssssssss    s ss  s  ss",
          " s s        sssssssss    s ss  s  ss",
          " s s        sssssssss    s ss  s  ss",
          " s s        sssssssss    s ss  s  ss",
          " s s        sssssssss    s ss  s  ss",
          " s s        sssssssss    s ss  s  ss",
          " s s        sssssssss    s ss  s  ss",
          " s s        sssssssss    s ss  s  ss",
          " s s        sssssssss    s ss  s  ss",
          " s s        sssssssss    s ss  s  ss",
          " s s        sssssssss    s ss  s  ss",
          " s s        sssssssss      ss  s  ss",
          " s s        sssssssss    s ss  s  ss",
          " s           s  sssss          s  s ",
          " s           s  sssss          s  s ",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          " s           s  sssss          s  s ",
          " s           s  sssss          s  s ",
          "r  rrrrrrrrr         rrrrrrr rr sr  ",
          "r  rrrrrrrrr         rrrrrrr rr sr  ",
          "r  rrrrrrrrr         rrrrrrr rr  r  ",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          "                             s      ",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          "                             rr     ",
          "                             s      ",
          "                             rs     ",
          "r      sr                    rr  r  ",
          "r   s  rr            s       rr  r  ",
          "r   rssrr            rss     rr  r  ",
          "r   rssrr            rss     rr  r  ",
          "r   rrrrr            rrrss   rr  r  ",
          "r   rrrrr            rrrss   rr  r  ",
          "r   rrrrr            rrrss   rr  r  ",
          "r   rrrrr            rrrss   rr  r  ",
          "r   rrrrrsss         rrrrr   rr  r  ",
          "r   rrrrrsss         rrrrr   rr  r  ",
          "r   rrrrrrrr         rrrrr   rr  r  ",
          "r   rrrrrrrr         rrrrr   rr  r  ",
          "r   rrrrrrrr         rrrrr   rr  r  ",
          "r   rrrrrrrr         rrrrrr  rr  r  ",
          "                                 r  ",
          "                                 s  ",
          "r  srrrrrrrr         rrrrrrs rr  r  ",
          "r  srrrrrrrr         rrrrrrs rr  r  ",
          "r  rrrrrrrrr         rrrrrrr rr  r  ",
          "r  rrrrrrrrr         rrrrrrr rr  r  ",
          "r  rrrrrrrrr         rrrrrrr rr  r  ",
          "r  rrrrrrrrr         rrrrrrr rr  r  ",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          " s s        sssssssss    s ss  s  ss",
          "r  rrrrrrrrr         rrrrrrr rr rr  ",
          "                             r      "
        ];
        XPathParser.actionTableNumber = [
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          "                 J                  ",
          "a  aaaaaaaaa         aaaaaaa aa  a  ",
          "                YYYYY               ",
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          `K1  KKKKKKKK .  +*)('KKKKKK  KK# K" `,
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          "                            N       ",
          "                            O       ",
          "e  eeeeeeeee         eeeeeee ee ee  ",
          "f  fffffffff         fffffff ff ff  ",
          "d  ddddddddd         ddddddd dd dd  ",
          "B  BBBBBBBBB         BBBBBBB BB BB  ",
          "A  AAAAAAAAA         AAAAAAA AA AA  ",
          "  P                                 ",
          "                            Q       ",
          ` 1           .  +*)('          #  " `,
          "b  bbbbbbbbb         bbbbbbb bb  b  ",
          "                                    ",
          "!       S                    !!  !  ",
          '"      T"                    ""  "  ',
          "$   V  $$            U       $$  $  ",
          "&   &ZY&&            &XW     &&  &  ",
          ")   )))))            )))\\[   ))  )  ",
          ".   ....._^]         .....   ..  .  ",
          "1   11111111         11111   11  1  ",
          "5   55555555         55555`  55  5  ",
          "7   77777777         777777  77  7  ",
          "9   99999999         999999  99  9  ",
          ":  c::::::::         ::::::b :: a:  ",
          "I  fIIIIIIII         IIIIIIe II  I  ",
          "=  =========         ======= == ==  ",
          "?  ?????????         ??????? ?? ??  ",
          "C  CCCCCCCCC         CCCCCCC CC CC  ",
          "J   JJJJJJJJ         JJJJJJ  JJ  J  ",
          "M   MMMMMMMM         MMMMMM  MM  M  ",
          "N  NNNNNNNNN         NNNNNNN NN  N  ",
          "P  PPPPPPPPP         PPPPPPP PP  P  ",
          "                +*)('               ",
          "R  RRRRRRRRR         RRRRRRR RR aR  ",
          "U  UUUUUUUUU         UUUUUUU UU  U  ",
          "Z  ZZZZZZZZZ         ZZZZZZZ ZZ ZZ  ",
          "c  ccccccccc         ccccccc cc cc  ",
          "                             j      ",
          "L  fLLLLLLLL         LLLLLLe LL  L  ",
          "6   66666666         66666   66  6  ",
          "              k                     ",
          "                             l      ",
          "                XXXXX               ",
          ` 1 0        /.-,+*)('    & %$m #  "!`,
          "_  f________         ______e __  _  ",
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          ` 1 0        /.-,+*)('      %$  #  "!`,
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          ` 1           .  +*)('          #  " `,
          ` 1           .  +*)('          #  " `,
          ">  >>>>>>>>>         >>>>>>> >> >>  ",
          ` 1           .  +*)('          #  " `,
          ` 1           .  +*)('          #  " `,
          "Q  QQQQQQQQQ         QQQQQQQ QQ aQ  ",
          "V  VVVVVVVVV         VVVVVVV VV aV  ",
          "T  TTTTTTTTT         TTTTTTT TT  T  ",
          "@  @@@@@@@@@         @@@@@@@ @@ @@  ",
          "                             \x87      ",
          "[  [[[[[[[[[         [[[[[[[ [[ [[  ",
          "D  DDDDDDDDD         DDDDDDD DD DD  ",
          "                             HH     ",
          "                             \x88      ",
          "                             F\x89     ",
          "#      T#                    ##  #  ",
          "%   V  %%            U       %%  %  ",
          "'   'ZY''            'XW     ''  '  ",
          "(   (ZY((            (XW     ((  (  ",
          "+   +++++            +++\\[   ++  +  ",
          "*   *****            ***\\[   **  *  ",
          "-   -----            ---\\[   --  -  ",
          ",   ,,,,,            ,,,\\[   ,,  ,  ",
          "0   00000_^]         00000   00  0  ",
          "/   /////_^]         /////   //  /  ",
          "2   22222222         22222   22  2  ",
          "3   33333333         33333   33  3  ",
          "4   44444444         44444   44  4  ",
          "8   88888888         888888  88  8  ",
          "                                 ^  ",
          "                                 \x8A  ",
          ";  f;;;;;;;;         ;;;;;;e ;;  ;  ",
          "<  f<<<<<<<<         <<<<<<e <<  <  ",
          "O  OOOOOOOOO         OOOOOOO OO  O  ",
          "`  `````````         ``````` ``  `  ",
          "S  SSSSSSSSS         SSSSSSS SS  S  ",
          "W  WWWWWWWWW         WWWWWWW WW  W  ",
          "\\  \\\\\\\\\\\\\\\\\\         \\\\\\\\\\\\\\ \\\\ \\\\  ",
          "E  EEEEEEEEE         EEEEEEE EE EE  ",
          ` 1 0        /.-,+*)('    & %$  #  "!`,
          "]  ]]]]]]]]]         ]]]]]]] ]] ]]  ",
          "                             G      "
        ];
        XPathParser.gotoTable = [
          "3456789:;<=>?@ AB  CDEFGH IJ ",
          "                             ",
          "                             ",
          "                             ",
          "L456789:;<=>?@ AB  CDEFGH IJ ",
          "            M        EFGH IJ ",
          "       N;<=>?@ AB  CDEFGH IJ ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "            S        EFGH IJ ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "              e              ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                        h  J ",
          "              i          j   ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "o456789:;<=>?@ ABpqCDEFGH IJ ",
          "                             ",
          "  r6789:;<=>?@ AB  CDEFGH IJ ",
          "   s789:;<=>?@ AB  CDEFGH IJ ",
          "    t89:;<=>?@ AB  CDEFGH IJ ",
          "    u89:;<=>?@ AB  CDEFGH IJ ",
          "     v9:;<=>?@ AB  CDEFGH IJ ",
          "     w9:;<=>?@ AB  CDEFGH IJ ",
          "     x9:;<=>?@ AB  CDEFGH IJ ",
          "     y9:;<=>?@ AB  CDEFGH IJ ",
          "      z:;<=>?@ AB  CDEFGH IJ ",
          "      {:;<=>?@ AB  CDEFGH IJ ",
          "       |;<=>?@ AB  CDEFGH IJ ",
          "       };<=>?@ AB  CDEFGH IJ ",
          "       ~;<=>?@ AB  CDEFGH IJ ",
          "         \x7F=>?@ AB  CDEFGH IJ ",
          "\x80456789:;<=>?@ AB  CDEFGH IJ\x81",
          "            \x82        EFGH IJ ",
          "            \x83        EFGH IJ ",
          "                             ",
          "                     \x84 GH IJ ",
          "                     \x85 GH IJ ",
          "              i          \x86   ",
          "              i          \x87   ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "                             ",
          "o456789:;<=>?@ AB\x8CqCDEFGH IJ ",
          "                             ",
          "                             "
        ];
        XPathParser.productions = [
          [1, 1, 2],
          [2, 1, 3],
          [3, 1, 4],
          [3, 3, 3, -9, 4],
          [4, 1, 5],
          [4, 3, 4, -8, 5],
          [5, 1, 6],
          [5, 3, 5, -22, 6],
          [5, 3, 5, -5, 6],
          [6, 1, 7],
          [6, 3, 6, -23, 7],
          [6, 3, 6, -24, 7],
          [6, 3, 6, -6, 7],
          [6, 3, 6, -7, 7],
          [7, 1, 8],
          [7, 3, 7, -25, 8],
          [7, 3, 7, -26, 8],
          [8, 1, 9],
          [8, 3, 8, -12, 9],
          [8, 3, 8, -11, 9],
          [8, 3, 8, -10, 9],
          [9, 1, 10],
          [9, 2, -26, 9],
          [10, 1, 11],
          [10, 3, 10, -27, 11],
          [11, 1, 12],
          [11, 1, 13],
          [11, 3, 13, -28, 14],
          [11, 3, 13, -4, 14],
          [13, 1, 15],
          [13, 2, 13, 16],
          [15, 1, 17],
          [15, 3, -29, 2, -30],
          [15, 1, -15],
          [15, 1, -16],
          [15, 1, 18],
          [18, 3, -13, -29, -30],
          [18, 4, -13, -29, 19, -30],
          [19, 1, 20],
          [19, 3, 20, -31, 19],
          [20, 1, 2],
          [12, 1, 14],
          [12, 1, 21],
          [21, 1, -28],
          [21, 2, -28, 14],
          [21, 1, 22],
          [14, 1, 23],
          [14, 3, 14, -28, 23],
          [14, 1, 24],
          [23, 2, 25, 26],
          [23, 1, 26],
          [23, 3, 25, 26, 27],
          [23, 2, 26, 27],
          [23, 1, 28],
          [27, 1, 16],
          [27, 2, 16, 27],
          [25, 2, -14, -3],
          [25, 1, -32],
          [26, 1, 29],
          [26, 3, -20, -29, -30],
          [26, 4, -21, -29, -15, -30],
          [16, 3, -33, 30, -34],
          [30, 1, 2],
          [22, 2, -4, 14],
          [24, 3, 14, -4, 23],
          [28, 1, -35],
          [28, 1, -2],
          [17, 2, -36, -18],
          [29, 1, -17],
          [29, 1, -19],
          [29, 1, -18]
        ];
        XPathParser.DOUBLEDOT = 2;
        XPathParser.DOUBLECOLON = 3;
        XPathParser.DOUBLESLASH = 4;
        XPathParser.NOTEQUAL = 5;
        XPathParser.LESSTHANOREQUAL = 6;
        XPathParser.GREATERTHANOREQUAL = 7;
        XPathParser.AND = 8;
        XPathParser.OR = 9;
        XPathParser.MOD = 10;
        XPathParser.DIV = 11;
        XPathParser.MULTIPLYOPERATOR = 12;
        XPathParser.FUNCTIONNAME = 13;
        XPathParser.AXISNAME = 14;
        XPathParser.LITERAL = 15;
        XPathParser.NUMBER = 16;
        XPathParser.ASTERISKNAMETEST = 17;
        XPathParser.QNAME = 18;
        XPathParser.NCNAMECOLONASTERISK = 19;
        XPathParser.NODETYPE = 20;
        XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL = 21;
        XPathParser.EQUALS = 22;
        XPathParser.LESSTHAN = 23;
        XPathParser.GREATERTHAN = 24;
        XPathParser.PLUS = 25;
        XPathParser.MINUS = 26;
        XPathParser.BAR = 27;
        XPathParser.SLASH = 28;
        XPathParser.LEFTPARENTHESIS = 29;
        XPathParser.RIGHTPARENTHESIS = 30;
        XPathParser.COMMA = 31;
        XPathParser.AT = 32;
        XPathParser.LEFTBRACKET = 33;
        XPathParser.RIGHTBRACKET = 34;
        XPathParser.DOT = 35;
        XPathParser.DOLLAR = 36;
        XPathParser.prototype.tokenize = function(s1) {
          var types = [];
          var values = [];
          var s = s1 + "\0";
          var pos = 0;
          var c = s.charAt(pos++);
          while (1) {
            while (c == " " || c == "	" || c == "\r" || c == "\n") {
              c = s.charAt(pos++);
            }
            if (c == "\0" || pos >= s.length) {
              break;
            }
            if (c == "(") {
              types.push(XPathParser.LEFTPARENTHESIS);
              values.push(c);
              c = s.charAt(pos++);
              continue;
            }
            if (c == ")") {
              types.push(XPathParser.RIGHTPARENTHESIS);
              values.push(c);
              c = s.charAt(pos++);
              continue;
            }
            if (c == "[") {
              types.push(XPathParser.LEFTBRACKET);
              values.push(c);
              c = s.charAt(pos++);
              continue;
            }
            if (c == "]") {
              types.push(XPathParser.RIGHTBRACKET);
              values.push(c);
              c = s.charAt(pos++);
              continue;
            }
            if (c == "@") {
              types.push(XPathParser.AT);
              values.push(c);
              c = s.charAt(pos++);
              continue;
            }
            if (c == ",") {
              types.push(XPathParser.COMMA);
              values.push(c);
              c = s.charAt(pos++);
              continue;
            }
            if (c == "|") {
              types.push(XPathParser.BAR);
              values.push(c);
              c = s.charAt(pos++);
              continue;
            }
            if (c == "+") {
              types.push(XPathParser.PLUS);
              values.push(c);
              c = s.charAt(pos++);
              continue;
            }
            if (c == "-") {
              types.push(XPathParser.MINUS);
              values.push(c);
              c = s.charAt(pos++);
              continue;
            }
            if (c == "=") {
              types.push(XPathParser.EQUALS);
              values.push(c);
              c = s.charAt(pos++);
              continue;
            }
            if (c == "$") {
              types.push(XPathParser.DOLLAR);
              values.push(c);
              c = s.charAt(pos++);
              continue;
            }
            if (c == ".") {
              c = s.charAt(pos++);
              if (c == ".") {
                types.push(XPathParser.DOUBLEDOT);
                values.push("..");
                c = s.charAt(pos++);
                continue;
              }
              if (c >= "0" && c <= "9") {
                var number = "." + c;
                c = s.charAt(pos++);
                while (c >= "0" && c <= "9") {
                  number += c;
                  c = s.charAt(pos++);
                }
                types.push(XPathParser.NUMBER);
                values.push(number);
                continue;
              }
              types.push(XPathParser.DOT);
              values.push(".");
              continue;
            }
            if (c == "'" || c == '"') {
              var delimiter = c;
              var literal = "";
              while (pos < s.length && (c = s.charAt(pos)) !== delimiter) {
                literal += c;
                pos += 1;
              }
              if (c !== delimiter) {
                throw XPathException.fromMessage("Unterminated string literal: " + delimiter + literal);
              }
              pos += 1;
              types.push(XPathParser.LITERAL);
              values.push(literal);
              c = s.charAt(pos++);
              continue;
            }
            if (c >= "0" && c <= "9") {
              var number = c;
              c = s.charAt(pos++);
              while (c >= "0" && c <= "9") {
                number += c;
                c = s.charAt(pos++);
              }
              if (c == ".") {
                if (s.charAt(pos) >= "0" && s.charAt(pos) <= "9") {
                  number += c;
                  number += s.charAt(pos++);
                  c = s.charAt(pos++);
                  while (c >= "0" && c <= "9") {
                    number += c;
                    c = s.charAt(pos++);
                  }
                }
              }
              types.push(XPathParser.NUMBER);
              values.push(number);
              continue;
            }
            if (c == "*") {
              if (types.length > 0) {
                var last = types[types.length - 1];
                if (last != XPathParser.AT && last != XPathParser.DOUBLECOLON && last != XPathParser.LEFTPARENTHESIS && last != XPathParser.LEFTBRACKET && last != XPathParser.AND && last != XPathParser.OR && last != XPathParser.MOD && last != XPathParser.DIV && last != XPathParser.MULTIPLYOPERATOR && last != XPathParser.SLASH && last != XPathParser.DOUBLESLASH && last != XPathParser.BAR && last != XPathParser.PLUS && last != XPathParser.MINUS && last != XPathParser.EQUALS && last != XPathParser.NOTEQUAL && last != XPathParser.LESSTHAN && last != XPathParser.LESSTHANOREQUAL && last != XPathParser.GREATERTHAN && last != XPathParser.GREATERTHANOREQUAL) {
                  types.push(XPathParser.MULTIPLYOPERATOR);
                  values.push(c);
                  c = s.charAt(pos++);
                  continue;
                }
              }
              types.push(XPathParser.ASTERISKNAMETEST);
              values.push(c);
              c = s.charAt(pos++);
              continue;
            }
            if (c == ":") {
              if (s.charAt(pos) == ":") {
                types.push(XPathParser.DOUBLECOLON);
                values.push("::");
                pos++;
                c = s.charAt(pos++);
                continue;
              }
            }
            if (c == "/") {
              c = s.charAt(pos++);
              if (c == "/") {
                types.push(XPathParser.DOUBLESLASH);
                values.push("//");
                c = s.charAt(pos++);
                continue;
              }
              types.push(XPathParser.SLASH);
              values.push("/");
              continue;
            }
            if (c == "!") {
              if (s.charAt(pos) == "=") {
                types.push(XPathParser.NOTEQUAL);
                values.push("!=");
                pos++;
                c = s.charAt(pos++);
                continue;
              }
            }
            if (c == "<") {
              if (s.charAt(pos) == "=") {
                types.push(XPathParser.LESSTHANOREQUAL);
                values.push("<=");
                pos++;
                c = s.charAt(pos++);
                continue;
              }
              types.push(XPathParser.LESSTHAN);
              values.push("<");
              c = s.charAt(pos++);
              continue;
            }
            if (c == ">") {
              if (s.charAt(pos) == "=") {
                types.push(XPathParser.GREATERTHANOREQUAL);
                values.push(">=");
                pos++;
                c = s.charAt(pos++);
                continue;
              }
              types.push(XPathParser.GREATERTHAN);
              values.push(">");
              c = s.charAt(pos++);
              continue;
            }
            if (c == "_" || Utilities.isLetter(c.charCodeAt(0))) {
              var name2 = c;
              c = s.charAt(pos++);
              while (Utilities.isNCNameChar(c.charCodeAt(0))) {
                name2 += c;
                c = s.charAt(pos++);
              }
              if (types.length > 0) {
                var last = types[types.length - 1];
                if (last != XPathParser.AT && last != XPathParser.DOUBLECOLON && last != XPathParser.LEFTPARENTHESIS && last != XPathParser.LEFTBRACKET && last != XPathParser.AND && last != XPathParser.OR && last != XPathParser.MOD && last != XPathParser.DIV && last != XPathParser.MULTIPLYOPERATOR && last != XPathParser.SLASH && last != XPathParser.DOUBLESLASH && last != XPathParser.BAR && last != XPathParser.PLUS && last != XPathParser.MINUS && last != XPathParser.EQUALS && last != XPathParser.NOTEQUAL && last != XPathParser.LESSTHAN && last != XPathParser.LESSTHANOREQUAL && last != XPathParser.GREATERTHAN && last != XPathParser.GREATERTHANOREQUAL) {
                  if (name2 == "and") {
                    types.push(XPathParser.AND);
                    values.push(name2);
                    continue;
                  }
                  if (name2 == "or") {
                    types.push(XPathParser.OR);
                    values.push(name2);
                    continue;
                  }
                  if (name2 == "mod") {
                    types.push(XPathParser.MOD);
                    values.push(name2);
                    continue;
                  }
                  if (name2 == "div") {
                    types.push(XPathParser.DIV);
                    values.push(name2);
                    continue;
                  }
                }
              }
              if (c == ":") {
                if (s.charAt(pos) == "*") {
                  types.push(XPathParser.NCNAMECOLONASTERISK);
                  values.push(name2 + ":*");
                  pos++;
                  c = s.charAt(pos++);
                  continue;
                }
                if (s.charAt(pos) == "_" || Utilities.isLetter(s.charCodeAt(pos))) {
                  name2 += ":";
                  c = s.charAt(pos++);
                  while (Utilities.isNCNameChar(c.charCodeAt(0))) {
                    name2 += c;
                    c = s.charAt(pos++);
                  }
                  if (c == "(") {
                    types.push(XPathParser.FUNCTIONNAME);
                    values.push(name2);
                    continue;
                  }
                  types.push(XPathParser.QNAME);
                  values.push(name2);
                  continue;
                }
                if (s.charAt(pos) == ":") {
                  types.push(XPathParser.AXISNAME);
                  values.push(name2);
                  continue;
                }
              }
              if (c == "(") {
                if (name2 == "comment" || name2 == "text" || name2 == "node") {
                  types.push(XPathParser.NODETYPE);
                  values.push(name2);
                  continue;
                }
                if (name2 == "processing-instruction") {
                  if (s.charAt(pos) == ")") {
                    types.push(XPathParser.NODETYPE);
                  } else {
                    types.push(XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL);
                  }
                  values.push(name2);
                  continue;
                }
                types.push(XPathParser.FUNCTIONNAME);
                values.push(name2);
                continue;
              }
              types.push(XPathParser.QNAME);
              values.push(name2);
              continue;
            }
            throw new Error("Unexpected character " + c);
          }
          types.push(1);
          values.push("[EOF]");
          return [types, values];
        };
        XPathParser.SHIFT = "s";
        XPathParser.REDUCE = "r";
        XPathParser.ACCEPT = "a";
        XPathParser.prototype.parse = function(s) {
          if (!s) {
            throw new Error("XPath expression unspecified.");
          }
          if (typeof s !== "string") {
            throw new Error("XPath expression must be a string.");
          }
          var types;
          var values;
          var res = this.tokenize(s);
          if (res == void 0) {
            return void 0;
          }
          types = res[0];
          values = res[1];
          var tokenPos = 0;
          var state = [];
          var tokenType = [];
          var tokenValue = [];
          var s;
          var a;
          var t;
          state.push(0);
          tokenType.push(1);
          tokenValue.push("_S");
          a = types[tokenPos];
          t = values[tokenPos++];
          while (1) {
            s = state[state.length - 1];
            switch (XPathParser.actionTable[s].charAt(a - 1)) {
              case XPathParser.SHIFT:
                tokenType.push(-a);
                tokenValue.push(t);
                state.push(XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32);
                a = types[tokenPos];
                t = values[tokenPos++];
                break;
              case XPathParser.REDUCE:
                var num = XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][1];
                var rhs = [];
                for (var i = 0; i < num; i++) {
                  tokenType.pop();
                  rhs.unshift(tokenValue.pop());
                  state.pop();
                }
                var s_ = state[state.length - 1];
                tokenType.push(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0]);
                if (this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32] == void 0) {
                  tokenValue.push(rhs[0]);
                } else {
                  tokenValue.push(this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32](rhs));
                }
                state.push(XPathParser.gotoTable[s_].charCodeAt(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0] - 2) - 33);
                break;
              case XPathParser.ACCEPT:
                return new XPath(tokenValue.pop());
              default:
                throw new Error("XPath parse error");
            }
          }
        };
        XPath.prototype = new Object();
        XPath.prototype.constructor = XPath;
        XPath.superclass = Object.prototype;
        function XPath(e) {
          this.expression = e;
        }
        XPath.prototype.toString = function() {
          return this.expression.toString();
        };
        function setIfUnset(obj, prop, value) {
          if (!(prop in obj)) {
            obj[prop] = value;
          }
        }
        XPath.prototype.evaluate = function(c) {
          var node = c.expressionContextNode;
          if (!(isNil(node) || isNodeLike(node))) {
            throw new Error("Context node does not appear to be a valid DOM node.");
          }
          c.contextNode = c.expressionContextNode;
          c.contextSize = 1;
          c.contextPosition = 1;
          if (c.isHtml) {
            setIfUnset(c, "caseInsensitive", true);
            setIfUnset(c, "allowAnyNamespaceForNoPrefix", true);
          }
          setIfUnset(c, "caseInsensitive", false);
          return this.expression.evaluate(c);
        };
        XPath.XML_NAMESPACE_URI = "http://www.w3.org/XML/1998/namespace";
        XPath.XMLNS_NAMESPACE_URI = "http://www.w3.org/2000/xmlns/";
        Expression.prototype = new Object();
        Expression.prototype.constructor = Expression;
        Expression.superclass = Object.prototype;
        function Expression() {
        }
        Expression.prototype.init = function() {
        };
        Expression.prototype.toString = function() {
          return "<Expression>";
        };
        Expression.prototype.evaluate = function(c) {
          throw new Error("Could not evaluate expression.");
        };
        UnaryOperation.prototype = new Expression();
        UnaryOperation.prototype.constructor = UnaryOperation;
        UnaryOperation.superclass = Expression.prototype;
        function UnaryOperation(rhs) {
          if (arguments.length > 0) {
            this.init(rhs);
          }
        }
        UnaryOperation.prototype.init = function(rhs) {
          this.rhs = rhs;
        };
        UnaryMinusOperation.prototype = new UnaryOperation();
        UnaryMinusOperation.prototype.constructor = UnaryMinusOperation;
        UnaryMinusOperation.superclass = UnaryOperation.prototype;
        function UnaryMinusOperation(rhs) {
          if (arguments.length > 0) {
            this.init(rhs);
          }
        }
        UnaryMinusOperation.prototype.init = function(rhs) {
          UnaryMinusOperation.superclass.init.call(this, rhs);
        };
        UnaryMinusOperation.prototype.evaluate = function(c) {
          return this.rhs.evaluate(c).number().negate();
        };
        UnaryMinusOperation.prototype.toString = function() {
          return "-" + this.rhs.toString();
        };
        BinaryOperation.prototype = new Expression();
        BinaryOperation.prototype.constructor = BinaryOperation;
        BinaryOperation.superclass = Expression.prototype;
        function BinaryOperation(lhs, rhs) {
          if (arguments.length > 0) {
            this.init(lhs, rhs);
          }
        }
        BinaryOperation.prototype.init = function(lhs, rhs) {
          this.lhs = lhs;
          this.rhs = rhs;
        };
        OrOperation.prototype = new BinaryOperation();
        OrOperation.prototype.constructor = OrOperation;
        OrOperation.superclass = BinaryOperation.prototype;
        function OrOperation(lhs, rhs) {
          if (arguments.length > 0) {
            this.init(lhs, rhs);
          }
        }
        OrOperation.prototype.init = function(lhs, rhs) {
          OrOperation.superclass.init.call(this, lhs, rhs);
        };
        OrOperation.prototype.toString = function() {
          return "(" + this.lhs.toString() + " or " + this.rhs.toString() + ")";
        };
        OrOperation.prototype.evaluate = function(c) {
          var b = this.lhs.evaluate(c).bool();
          if (b.booleanValue()) {
            return b;
          }
          return this.rhs.evaluate(c).bool();
        };
        AndOperation.prototype = new BinaryOperation();
        AndOperation.prototype.constructor = AndOperation;
        AndOperation.superclass = BinaryOperation.prototype;
        function AndOperation(lhs, rhs) {
          if (arguments.length > 0) {
            this.init(lhs, rhs);
          }
        }
        AndOperation.prototype.init = function(lhs, rhs) {
          AndOperation.superclass.init.call(this, lhs, rhs);
        };
        AndOperation.prototype.toString = function() {
          return "(" + this.lhs.toString() + " and " + this.rhs.toString() + ")";
        };
        AndOperation.prototype.evaluate = function(c) {
          var b = this.lhs.evaluate(c).bool();
          if (!b.booleanValue()) {
            return b;
          }
          return this.rhs.evaluate(c).bool();
        };
        EqualsOperation.prototype = new BinaryOperation();
        EqualsOperation.prototype.constructor = EqualsOperation;
        EqualsOperation.superclass = BinaryOperation.prototype;
        function EqualsOperation(lhs, rhs) {
          if (arguments.length > 0) {
            this.init(lhs, rhs);
          }
        }
        EqualsOperation.prototype.init = function(lhs, rhs) {
          EqualsOperation.superclass.init.call(this, lhs, rhs);
        };
        EqualsOperation.prototype.toString = function() {
          return "(" + this.lhs.toString() + " = " + this.rhs.toString() + ")";
        };
        EqualsOperation.prototype.evaluate = function(c) {
          return this.lhs.evaluate(c).equals(this.rhs.evaluate(c));
        };
        NotEqualOperation.prototype = new BinaryOperation();
        NotEqualOperation.prototype.constructor = NotEqualOperation;
        NotEqualOperation.superclass = BinaryOperation.prototype;
        function NotEqualOperation(lhs, rhs) {
          if (arguments.length > 0) {
            this.init(lhs, rhs);
          }
        }
        NotEqualOperation.prototype.init = function(lhs, rhs) {
          NotEqualOperation.superclass.init.call(this, lhs, rhs);
        };
        NotEqualOperation.prototype.toString = function() {
          return "(" + this.lhs.toString() + " != " + this.rhs.toString() + ")";
        };
        NotEqualOperation.prototype.evaluate = function(c) {
          return this.lhs.evaluate(c).notequal(this.rhs.evaluate(c));
        };
        LessThanOperation.prototype = new BinaryOperation();
        LessThanOperation.prototype.constructor = LessThanOperation;
        LessThanOperation.superclass = BinaryOperation.prototype;
        function LessThanOperation(lhs, rhs) {
          if (arguments.length > 0) {
            this.init(lhs, rhs);
          }
        }
        LessThanOperation.prototype.init = function(lhs, rhs) {
          LessThanOperation.superclass.init.call(this, lhs, rhs);
        };
        LessThanOperation.prototype.evaluate = function(c) {
          return this.lhs.evaluate(c).lessthan(this.rhs.evaluate(c));
        };
        LessThanOperation.prototype.toString = function() {
          return "(" + this.lhs.toString() + " < " + this.rhs.toString() + ")";
        };
        GreaterThanOperation.prototype = new BinaryOperation();
        GreaterThanOperation.prototype.constructor = GreaterThanOperation;
        GreaterThanOperation.superclass = BinaryOperation.prototype;
        function GreaterThanOperation(lhs, rhs) {
          if (arguments.length > 0) {
            this.init(lhs, rhs);
          }
        }
        GreaterThanOperation.prototype.init = function(lhs, rhs) {
          GreaterThanOperation.superclass.init.call(this, lhs, rhs);
        };
        GreaterThanOperation.prototype.evaluate = function(c) {
          return this.lhs.evaluate(c).greaterthan(this.rhs.evaluate(c));
        };
        GreaterThanOperation.prototype.toString = function() {
          return "(" + this.lhs.toString() + " > " + this.rhs.toString() + ")";
        };
        LessThanOrEqualOperation.prototype = new BinaryOperation();
        LessThanOrEqualOperation.prototype.constructor = LessThanOrEqualOperation;
        LessThanOrEqualOperation.superclass = BinaryOperation.prototype;
        function LessThanOrEqualOperation(lhs, rhs) {
          if (arguments.length > 0) {
            this.init(lhs, rhs);
          }
        }
        LessThanOrEqualOperation.prototype.init = function(lhs, rhs) {
          LessThanOrEqualOperation.superclass.init.call(this, lhs, rhs);
        };
        LessThanOrEqualOperation.prototype.evaluate = function(c) {
          return this.lhs.evaluate(c).lessthanorequal(this.rhs.evaluate(c));
        };
        LessThanOrEqualOperation.prototype.toString = function() {
          return "(" + this.lhs.toString() + " <= " + this.rhs.toString() + ")";
        };
        GreaterThanOrEqualOperation.prototype = new BinaryOperation();
        GreaterThanOrEqualOperation.prototype.constructor = GreaterThanOrEqualOperation;
        GreaterThanOrEqualOperation.superclass = BinaryOperation.prototype;
        function GreaterThanOrEqualOperation(lhs, rhs) {
          if (arguments.length > 0) {
            this.init(lhs, rhs);
          }
        }
        GreaterThanOrEqualOperation.prototype.init = function(lhs, rhs) {
          GreaterThanOrEqualOperation.superclass.init.call(this, lhs, rhs);
        };
        GreaterThanOrEqualOperation.prototype.evaluate = function(c) {
          return this.lhs.evaluate(c).greaterthanorequal(this.rhs.evaluate(c));
        };
        GreaterThanOrEqualOperation.prototype.toString = function() {
          return "(" + this.lhs.toString() + " >= " + this.rhs.toString() + ")";
        };
        PlusOperation.prototype = new BinaryOperation();
        PlusOperation.prototype.constructor = PlusOperation;
        PlusOperation.superclass = BinaryOperation.prototype;
        function PlusOperation(lhs, rhs) {
          if (arguments.length > 0) {
            this.init(lhs, rhs);
          }
        }
        PlusOperation.prototype.init = function(lhs, rhs) {
          PlusOperation.superclass.init.call(this, lhs, rhs);
        };
        PlusOperation.prototype.evaluate = function(c) {
          return this.lhs.evaluate(c).number().plus(this.rhs.evaluate(c).number());
        };
        PlusOperation.prototype.toString = function() {
          return "(" + this.lhs.toString() + " + " + this.rhs.toString() + ")";
        };
        MinusOperation.prototype = new BinaryOperation();
        MinusOperation.prototype.constructor = MinusOperation;
        MinusOperation.superclass = BinaryOperation.prototype;
        function MinusOperation(lhs, rhs) {
          if (arguments.length > 0) {
            this.init(lhs, rhs);
          }
        }
        MinusOperation.prototype.init = function(lhs, rhs) {
          MinusOperation.superclass.init.call(this, lhs, rhs);
        };
        MinusOperation.prototype.evaluate = function(c) {
          return this.lhs.evaluate(c).number().minus(this.rhs.evaluate(c).number());
        };
        MinusOperation.prototype.toString = function() {
          return "(" + this.lhs.toString() + " - " + this.rhs.toString() + ")";
        };
        MultiplyOperation.prototype = new BinaryOperation();
        MultiplyOperation.prototype.constructor = MultiplyOperation;
        MultiplyOperation.superclass = BinaryOperation.prototype;
        function MultiplyOperation(lhs, rhs) {
          if (arguments.length > 0) {
            this.init(lhs, rhs);
          }
        }
        MultiplyOperation.prototype.init = function(lhs, rhs) {
          MultiplyOperation.superclass.init.call(this, lhs, rhs);
        };
        MultiplyOperation.prototype.evaluate = function(c) {
          return this.lhs.evaluate(c).number().multiply(this.rhs.evaluate(c).number());
        };
        MultiplyOperation.prototype.toString = function() {
          return "(" + this.lhs.toString() + " * " + this.rhs.toString() + ")";
        };
        DivOperation.prototype = new BinaryOperation();
        DivOperation.prototype.constructor = DivOperation;
        DivOperation.superclass = BinaryOperation.prototype;
        function DivOperation(lhs, rhs) {
          if (arguments.length > 0) {
            this.init(lhs, rhs);
          }
        }
        DivOperation.prototype.init = function(lhs, rhs) {
          DivOperation.superclass.init.call(this, lhs, rhs);
        };
        DivOperation.prototype.evaluate = function(c) {
          return this.lhs.evaluate(c).number().div(this.rhs.evaluate(c).number());
        };
        DivOperation.prototype.toString = function() {
          return "(" + this.lhs.toString() + " div " + this.rhs.toString() + ")";
        };
        ModOperation.prototype = new BinaryOperation();
        ModOperation.prototype.constructor = ModOperation;
        ModOperation.superclass = BinaryOperation.prototype;
        function ModOperation(lhs, rhs) {
          if (arguments.length > 0) {
            this.init(lhs, rhs);
          }
        }
        ModOperation.prototype.init = function(lhs, rhs) {
          ModOperation.superclass.init.call(this, lhs, rhs);
        };
        ModOperation.prototype.evaluate = function(c) {
          return this.lhs.evaluate(c).number().mod(this.rhs.evaluate(c).number());
        };
        ModOperation.prototype.toString = function() {
          return "(" + this.lhs.toString() + " mod " + this.rhs.toString() + ")";
        };
        BarOperation.prototype = new BinaryOperation();
        BarOperation.prototype.constructor = BarOperation;
        BarOperation.superclass = BinaryOperation.prototype;
        function BarOperation(lhs, rhs) {
          if (arguments.length > 0) {
            this.init(lhs, rhs);
          }
        }
        BarOperation.prototype.init = function(lhs, rhs) {
          BarOperation.superclass.init.call(this, lhs, rhs);
        };
        BarOperation.prototype.evaluate = function(c) {
          return this.lhs.evaluate(c).nodeset().union(this.rhs.evaluate(c).nodeset());
        };
        BarOperation.prototype.toString = function() {
          return map(toString, [this.lhs, this.rhs]).join(" | ");
        };
        PathExpr.prototype = new Expression();
        PathExpr.prototype.constructor = PathExpr;
        PathExpr.superclass = Expression.prototype;
        function PathExpr(filter2, filterPreds, locpath) {
          if (arguments.length > 0) {
            this.init(filter2, filterPreds, locpath);
          }
        }
        PathExpr.prototype.init = function(filter2, filterPreds, locpath) {
          PathExpr.superclass.init.call(this);
          this.filter = filter2;
          this.filterPredicates = filterPreds;
          this.locationPath = locpath;
        };
        function findRoot(node) {
          while (node && node.parentNode) {
            node = node.parentNode;
          }
          return node;
        }
        var applyPredicates = function(predicates, c, nodes, reverse) {
          if (predicates.length === 0) {
            return nodes;
          }
          var ctx = c.extend({});
          return reduce(
            function(inNodes, pred) {
              ctx.contextSize = inNodes.length;
              return filter(
                function(node, i) {
                  ctx.contextNode = node;
                  ctx.contextPosition = i + 1;
                  return PathExpr.predicateMatches(pred, ctx);
                },
                inNodes
              );
            },
            sortNodes(nodes, reverse),
            predicates
          );
        };
        PathExpr.getRoot = function(xpc, nodes) {
          var firstNode = nodes[0];
          if (firstNode && firstNode.nodeType === NodeTypes.DOCUMENT_NODE) {
            return firstNode;
          }
          if (xpc.virtualRoot) {
            return xpc.virtualRoot;
          }
          if (!firstNode) {
            throw new Error("Context node not found when determining document root.");
          }
          var ownerDoc = firstNode.ownerDocument;
          if (ownerDoc) {
            return ownerDoc;
          }
          var n = firstNode;
          while (n.parentNode != null) {
            n = n.parentNode;
          }
          return n;
        };
        var getPrefixForNamespaceNode = function(attrNode) {
          var nm = String(attrNode.name);
          if (nm === "xmlns") {
            return "";
          }
          if (nm.substring(0, 6) === "xmlns:") {
            return nm.substring(6, nm.length);
          }
          return null;
        };
        PathExpr.applyStep = function(step, xpc, node) {
          if (!node) {
            throw new Error("Context node not found when evaluating XPath step: " + step);
          }
          var newNodes = [];
          xpc.contextNode = node;
          switch (step.axis) {
            case Step.ANCESTOR:
              if (xpc.contextNode === xpc.virtualRoot) {
                break;
              }
              var m;
              if (xpc.contextNode.nodeType == NodeTypes.ATTRIBUTE_NODE) {
                m = PathExpr.getOwnerElement(xpc.contextNode);
              } else {
                m = xpc.contextNode.parentNode;
              }
              while (m != null) {
                if (step.nodeTest.matches(m, xpc)) {
                  newNodes.push(m);
                }
                if (m === xpc.virtualRoot) {
                  break;
                }
                m = m.parentNode;
              }
              break;
            case Step.ANCESTORORSELF:
              for (var m = xpc.contextNode; m != null; m = m.nodeType == NodeTypes.ATTRIBUTE_NODE ? PathExpr.getOwnerElement(m) : m.parentNode) {
                if (step.nodeTest.matches(m, xpc)) {
                  newNodes.push(m);
                }
                if (m === xpc.virtualRoot) {
                  break;
                }
              }
              break;
            case Step.ATTRIBUTE:
              var nnm = xpc.contextNode.attributes;
              if (nnm != null) {
                for (var k = 0; k < nnm.length; k++) {
                  var m = nnm.item(k);
                  if (step.nodeTest.matches(m, xpc)) {
                    newNodes.push(m);
                  }
                }
              }
              break;
            case Step.CHILD:
              for (var m = xpc.contextNode.firstChild; m != null; m = m.nextSibling) {
                if (step.nodeTest.matches(m, xpc)) {
                  newNodes.push(m);
                }
              }
              break;
            case Step.DESCENDANT:
              var st = [xpc.contextNode.firstChild];
              while (st.length > 0) {
                for (var m = st.pop(); m != null; ) {
                  if (step.nodeTest.matches(m, xpc)) {
                    newNodes.push(m);
                  }
                  if (m.firstChild != null) {
                    st.push(m.nextSibling);
                    m = m.firstChild;
                  } else {
                    m = m.nextSibling;
                  }
                }
              }
              break;
            case Step.DESCENDANTORSELF:
              if (step.nodeTest.matches(xpc.contextNode, xpc)) {
                newNodes.push(xpc.contextNode);
              }
              var st = [xpc.contextNode.firstChild];
              while (st.length > 0) {
                for (var m = st.pop(); m != null; ) {
                  if (step.nodeTest.matches(m, xpc)) {
                    newNodes.push(m);
                  }
                  if (m.firstChild != null) {
                    st.push(m.nextSibling);
                    m = m.firstChild;
                  } else {
                    m = m.nextSibling;
                  }
                }
              }
              break;
            case Step.FOLLOWING:
              if (xpc.contextNode === xpc.virtualRoot) {
                break;
              }
              var st = [];
              if (xpc.contextNode.firstChild != null) {
                st.unshift(xpc.contextNode.firstChild);
              } else {
                st.unshift(xpc.contextNode.nextSibling);
              }
              for (var m = xpc.contextNode.parentNode; m != null && m.nodeType != NodeTypes.DOCUMENT_NODE && m !== xpc.virtualRoot; m = m.parentNode) {
                st.unshift(m.nextSibling);
              }
              do {
                for (var m = st.pop(); m != null; ) {
                  if (step.nodeTest.matches(m, xpc)) {
                    newNodes.push(m);
                  }
                  if (m.firstChild != null) {
                    st.push(m.nextSibling);
                    m = m.firstChild;
                  } else {
                    m = m.nextSibling;
                  }
                }
              } while (st.length > 0);
              break;
            case Step.FOLLOWINGSIBLING:
              if (xpc.contextNode === xpc.virtualRoot) {
                break;
              }
              for (var m = xpc.contextNode.nextSibling; m != null; m = m.nextSibling) {
                if (step.nodeTest.matches(m, xpc)) {
                  newNodes.push(m);
                }
              }
              break;
            case Step.NAMESPACE:
              var nodes = {};
              if (xpc.contextNode.nodeType == NodeTypes.ELEMENT_NODE) {
                nodes["xml"] = new XPathNamespace("xml", null, XPath.XML_NAMESPACE_URI, xpc.contextNode);
                for (var m = xpc.contextNode; m != null && m.nodeType == NodeTypes.ELEMENT_NODE; m = m.parentNode) {
                  for (var k = 0; k < m.attributes.length; k++) {
                    var attr = m.attributes.item(k);
                    var pre = getPrefixForNamespaceNode(attr);
                    if (pre != null && nodes[pre] == void 0) {
                      nodes[pre] = new XPathNamespace(pre, attr, attr.value, xpc.contextNode);
                    }
                  }
                }
                for (var pre in nodes) {
                  var node = nodes[pre];
                  if (step.nodeTest.matches(node, xpc)) {
                    newNodes.push(node);
                  }
                }
              }
              break;
            case Step.PARENT:
              m = null;
              if (xpc.contextNode !== xpc.virtualRoot) {
                if (xpc.contextNode.nodeType == NodeTypes.ATTRIBUTE_NODE) {
                  m = PathExpr.getOwnerElement(xpc.contextNode);
                } else {
                  m = xpc.contextNode.parentNode;
                }
              }
              if (m != null && step.nodeTest.matches(m, xpc)) {
                newNodes.push(m);
              }
              break;
            case Step.PRECEDING:
              var st;
              if (xpc.virtualRoot != null) {
                st = [xpc.virtualRoot];
              } else {
                st = [findRoot(xpc.contextNode)];
              }
              outer: while (st.length > 0) {
                for (var m = st.pop(); m != null; ) {
                  if (m == xpc.contextNode) {
                    break outer;
                  }
                  if (step.nodeTest.matches(m, xpc)) {
                    newNodes.unshift(m);
                  }
                  if (m.firstChild != null) {
                    st.push(m.nextSibling);
                    m = m.firstChild;
                  } else {
                    m = m.nextSibling;
                  }
                }
              }
              break;
            case Step.PRECEDINGSIBLING:
              if (xpc.contextNode === xpc.virtualRoot) {
                break;
              }
              for (var m = xpc.contextNode.previousSibling; m != null; m = m.previousSibling) {
                if (step.nodeTest.matches(m, xpc)) {
                  newNodes.push(m);
                }
              }
              break;
            case Step.SELF:
              if (step.nodeTest.matches(xpc.contextNode, xpc)) {
                newNodes.push(xpc.contextNode);
              }
              break;
            default:
          }
          return newNodes;
        };
        function applyStepWithPredicates(step, xpc, node) {
          return applyPredicates(
            step.predicates,
            xpc,
            PathExpr.applyStep(step, xpc, node),
            includes(REVERSE_AXES, step.axis)
          );
        }
        function applyStepToNodes(context, nodes, step) {
          return flatten(
            map(
              applyStepWithPredicates.bind(null, step, context),
              nodes
            )
          );
        }
        PathExpr.applySteps = function(steps, xpc, nodes) {
          return reduce(
            applyStepToNodes.bind(null, xpc),
            nodes,
            steps
          );
        };
        PathExpr.prototype.applyFilter = function(c, xpc) {
          if (!this.filter) {
            return { nodes: [c.contextNode] };
          }
          var ns = this.filter.evaluate(c);
          if (!Utilities.instance_of(ns, XNodeSet)) {
            if (this.filterPredicates != null && this.filterPredicates.length > 0 || this.locationPath != null) {
              throw new Error("Path expression filter must evaluate to a nodeset if predicates or location path are used");
            }
            return { nonNodes: ns };
          }
          return {
            nodes: applyPredicates(
              this.filterPredicates || [],
              xpc,
              ns.toUnsortedArray(),
              false
              // reverse
            )
          };
        };
        PathExpr.applyLocationPath = function(locationPath, xpc, nodes) {
          if (!locationPath) {
            return nodes;
          }
          var startNodes = locationPath.absolute ? [PathExpr.getRoot(xpc, nodes)] : nodes;
          return PathExpr.applySteps(locationPath.steps, xpc, startNodes);
        };
        PathExpr.prototype.evaluate = function(c) {
          var xpc = assign(new XPathContext(), c);
          var filterResult = this.applyFilter(c, xpc);
          if ("nonNodes" in filterResult) {
            return filterResult.nonNodes;
          }
          var ns = new XNodeSet();
          ns.addArray(PathExpr.applyLocationPath(this.locationPath, xpc, filterResult.nodes));
          return ns;
        };
        PathExpr.predicateMatches = function(pred, c) {
          var res = pred.evaluate(c);
          return Utilities.instance_of(res, XNumber) ? c.contextPosition === res.numberValue() : res.booleanValue();
        };
        PathExpr.predicateString = function(predicate) {
          return wrap("[", "]", predicate.toString());
        };
        PathExpr.predicatesString = function(predicates) {
          return join(
            "",
            map(PathExpr.predicateString, predicates)
          );
        };
        PathExpr.prototype.toString = function() {
          if (this.filter != void 0) {
            var filterStr = toString(this.filter);
            if (Utilities.instance_of(this.filter, XString)) {
              return wrap("'", "'", filterStr);
            }
            if (this.filterPredicates != void 0 && this.filterPredicates.length) {
              return wrap("(", ")", filterStr) + PathExpr.predicatesString(this.filterPredicates);
            }
            if (this.locationPath != void 0) {
              return filterStr + (this.locationPath.absolute ? "" : "/") + toString(this.locationPath);
            }
            return filterStr;
          }
          return toString(this.locationPath);
        };
        PathExpr.getOwnerElement = function(n) {
          if (n.ownerElement) {
            return n.ownerElement;
          }
          try {
            if (n.selectSingleNode) {
              return n.selectSingleNode("..");
            }
          } catch (e) {
          }
          var doc = n.nodeType == NodeTypes.DOCUMENT_NODE ? n : n.ownerDocument;
          var elts = doc.getElementsByTagName("*");
          for (var i = 0; i < elts.length; i++) {
            var elt = elts.item(i);
            var nnm = elt.attributes;
            for (var j = 0; j < nnm.length; j++) {
              var an = nnm.item(j);
              if (an === n) {
                return elt;
              }
            }
          }
          return null;
        };
        LocationPath.prototype = new Object();
        LocationPath.prototype.constructor = LocationPath;
        LocationPath.superclass = Object.prototype;
        function LocationPath(abs, steps) {
          if (arguments.length > 0) {
            this.init(abs, steps);
          }
        }
        LocationPath.prototype.init = function(abs, steps) {
          this.absolute = abs;
          this.steps = steps;
        };
        LocationPath.prototype.toString = function() {
          return (this.absolute ? "/" : "") + map(toString, this.steps).join("/");
        };
        Step.prototype = new Object();
        Step.prototype.constructor = Step;
        Step.superclass = Object.prototype;
        function Step(axis, nodetest, preds) {
          if (arguments.length > 0) {
            this.init(axis, nodetest, preds);
          }
        }
        Step.prototype.init = function(axis, nodetest, preds) {
          this.axis = axis;
          this.nodeTest = nodetest;
          this.predicates = preds;
        };
        Step.prototype.toString = function() {
          return Step.STEPNAMES[this.axis] + "::" + this.nodeTest.toString() + PathExpr.predicatesString(this.predicates);
        };
        Step.ANCESTOR = 0;
        Step.ANCESTORORSELF = 1;
        Step.ATTRIBUTE = 2;
        Step.CHILD = 3;
        Step.DESCENDANT = 4;
        Step.DESCENDANTORSELF = 5;
        Step.FOLLOWING = 6;
        Step.FOLLOWINGSIBLING = 7;
        Step.NAMESPACE = 8;
        Step.PARENT = 9;
        Step.PRECEDING = 10;
        Step.PRECEDINGSIBLING = 11;
        Step.SELF = 12;
        Step.STEPNAMES = reduce(function(acc, x) {
          return acc[x[0]] = x[1], acc;
        }, {}, [
          [Step.ANCESTOR, "ancestor"],
          [Step.ANCESTORORSELF, "ancestor-or-self"],
          [Step.ATTRIBUTE, "attribute"],
          [Step.CHILD, "child"],
          [Step.DESCENDANT, "descendant"],
          [Step.DESCENDANTORSELF, "descendant-or-self"],
          [Step.FOLLOWING, "following"],
          [Step.FOLLOWINGSIBLING, "following-sibling"],
          [Step.NAMESPACE, "namespace"],
          [Step.PARENT, "parent"],
          [Step.PRECEDING, "preceding"],
          [Step.PRECEDINGSIBLING, "preceding-sibling"],
          [Step.SELF, "self"]
        ]);
        var REVERSE_AXES = [
          Step.ANCESTOR,
          Step.ANCESTORORSELF,
          Step.PARENT,
          Step.PRECEDING,
          Step.PRECEDINGSIBLING
        ];
        NodeTest.prototype = new Object();
        NodeTest.prototype.constructor = NodeTest;
        NodeTest.superclass = Object.prototype;
        function NodeTest(type, value) {
          if (arguments.length > 0) {
            this.init(type, value);
          }
        }
        NodeTest.prototype.init = function(type, value) {
          this.type = type;
          this.value = value;
        };
        NodeTest.prototype.toString = function() {
          return "<unknown nodetest type>";
        };
        NodeTest.prototype.matches = function(n, xpc) {
          console.warn("unknown node test type");
        };
        NodeTest.NAMETESTANY = 0;
        NodeTest.NAMETESTPREFIXANY = 1;
        NodeTest.NAMETESTQNAME = 2;
        NodeTest.COMMENT = 3;
        NodeTest.TEXT = 4;
        NodeTest.PI = 5;
        NodeTest.NODE = 6;
        NodeTest.isNodeType = function(types) {
          return function(node) {
            return includes(types, node.nodeType);
          };
        };
        NodeTest.makeNodeTestType = function(type, members, ctor) {
          var newType = ctor || function() {
          };
          newType.prototype = new NodeTest(type);
          newType.prototype.constructor = newType;
          assign(newType.prototype, members);
          return newType;
        };
        NodeTest.makeNodeTypeTest = function(type, nodeTypes, stringVal) {
          return new (NodeTest.makeNodeTestType(type, {
            matches: NodeTest.isNodeType(nodeTypes),
            toString: always(stringVal)
          }))();
        };
        NodeTest.hasPrefix = function(node) {
          return node.prefix || (node.nodeName || node.tagName).indexOf(":") !== -1;
        };
        NodeTest.isElementOrAttribute = NodeTest.isNodeType([1, 2]);
        NodeTest.nameSpaceMatches = function(prefix, xpc, n) {
          var nNamespace = n.namespaceURI || "";
          if (!prefix) {
            return !nNamespace || xpc.allowAnyNamespaceForNoPrefix && !NodeTest.hasPrefix(n);
          }
          var ns = xpc.namespaceResolver.getNamespace(prefix, xpc.expressionContextNode);
          if (ns == null) {
            throw new Error("Cannot resolve QName " + prefix);
          }
          return ns === nNamespace;
        };
        NodeTest.localNameMatches = function(localName, xpc, n) {
          var nLocalName = n.localName || n.nodeName;
          return xpc.caseInsensitive ? localName.toLowerCase() === nLocalName.toLowerCase() : localName === nLocalName;
        };
        NodeTest.NameTestPrefixAny = NodeTest.makeNodeTestType(
          NodeTest.NAMETESTPREFIXANY,
          {
            matches: function(n, xpc) {
              return NodeTest.isElementOrAttribute(n) && NodeTest.nameSpaceMatches(this.prefix, xpc, n);
            },
            toString: function() {
              return this.prefix + ":*";
            }
          },
          function NameTestPrefixAny(prefix) {
            this.prefix = prefix;
          }
        );
        NodeTest.NameTestQName = NodeTest.makeNodeTestType(
          NodeTest.NAMETESTQNAME,
          {
            matches: function(n, xpc) {
              return NodeTest.isNodeType(
                [
                  NodeTypes.ELEMENT_NODE,
                  NodeTypes.ATTRIBUTE_NODE,
                  NodeTypes.NAMESPACE_NODE
                ]
              )(n) && NodeTest.nameSpaceMatches(this.prefix, xpc, n) && NodeTest.localNameMatches(this.localName, xpc, n);
            },
            toString: function() {
              return this.name;
            }
          },
          function NameTestQName(name2) {
            var nameParts = name2.split(":");
            this.name = name2;
            this.prefix = nameParts.length > 1 ? nameParts[0] : null;
            this.localName = nameParts[nameParts.length > 1 ? 1 : 0];
          }
        );
        NodeTest.PITest = NodeTest.makeNodeTestType(NodeTest.PI, {
          matches: function(n, xpc) {
            return NodeTest.isNodeType(
              [NodeTypes.PROCESSING_INSTRUCTION_NODE]
            )(n) && (n.target || n.nodeName) === this.name;
          },
          toString: function() {
            return wrap('processing-instruction("', '")', this.name);
          }
        }, function(name2) {
          this.name = name2;
        });
        NodeTest.nameTestAny = NodeTest.makeNodeTypeTest(
          NodeTest.NAMETESTANY,
          [
            NodeTypes.ELEMENT_NODE,
            NodeTypes.ATTRIBUTE_NODE,
            NodeTypes.NAMESPACE_NODE
          ],
          "*"
        );
        NodeTest.textTest = NodeTest.makeNodeTypeTest(
          NodeTest.TEXT,
          [
            NodeTypes.TEXT_NODE,
            NodeTypes.CDATA_SECTION_NODE
          ],
          "text()"
        );
        NodeTest.commentTest = NodeTest.makeNodeTypeTest(
          NodeTest.COMMENT,
          [NodeTypes.COMMENT_NODE],
          "comment()"
        );
        NodeTest.nodeTest = NodeTest.makeNodeTypeTest(
          NodeTest.NODE,
          [
            NodeTypes.ELEMENT_NODE,
            NodeTypes.ATTRIBUTE_NODE,
            NodeTypes.TEXT_NODE,
            NodeTypes.CDATA_SECTION_NODE,
            NodeTypes.PROCESSING_INSTRUCTION_NODE,
            NodeTypes.COMMENT_NODE,
            NodeTypes.DOCUMENT_NODE
          ],
          "node()"
        );
        NodeTest.anyPiTest = NodeTest.makeNodeTypeTest(
          NodeTest.PI,
          [NodeTypes.PROCESSING_INSTRUCTION_NODE],
          "processing-instruction()"
        );
        VariableReference.prototype = new Expression();
        VariableReference.prototype.constructor = VariableReference;
        VariableReference.superclass = Expression.prototype;
        function VariableReference(v) {
          if (arguments.length > 0) {
            this.init(v);
          }
        }
        VariableReference.prototype.init = function(v) {
          this.variable = v;
        };
        VariableReference.prototype.toString = function() {
          return "$" + this.variable;
        };
        VariableReference.prototype.evaluate = function(c) {
          var parts = Utilities.resolveQName(this.variable, c.namespaceResolver, c.contextNode, false);
          if (parts[0] == null) {
            throw new Error("Cannot resolve QName " + fn);
          }
          var result = c.variableResolver.getVariable(parts[1], parts[0]);
          if (!result) {
            throw XPathException.fromMessage("Undeclared variable: " + this.toString());
          }
          return result;
        };
        FunctionCall.prototype = new Expression();
        FunctionCall.prototype.constructor = FunctionCall;
        FunctionCall.superclass = Expression.prototype;
        function FunctionCall(fn2, args) {
          if (arguments.length > 0) {
            this.init(fn2, args);
          }
        }
        FunctionCall.prototype.init = function(fn2, args) {
          this.functionName = fn2;
          this.arguments = args;
        };
        FunctionCall.prototype.toString = function() {
          var s = this.functionName + "(";
          for (var i = 0; i < this.arguments.length; i++) {
            if (i > 0) {
              s += ", ";
            }
            s += this.arguments[i].toString();
          }
          return s + ")";
        };
        FunctionCall.prototype.evaluate = function(c) {
          var f = FunctionResolver.getFunctionFromContext(this.functionName, c);
          if (!f) {
            throw new Error("Unknown function " + this.functionName);
          }
          var a = [c].concat(this.arguments);
          return f.apply(c.functionResolver.thisArg, a);
        };
        var Operators = new Object();
        Operators.equals = function(l, r) {
          return l.equals(r);
        };
        Operators.notequal = function(l, r) {
          return l.notequal(r);
        };
        Operators.lessthan = function(l, r) {
          return l.lessthan(r);
        };
        Operators.greaterthan = function(l, r) {
          return l.greaterthan(r);
        };
        Operators.lessthanorequal = function(l, r) {
          return l.lessthanorequal(r);
        };
        Operators.greaterthanorequal = function(l, r) {
          return l.greaterthanorequal(r);
        };
        XString.prototype = new Expression();
        XString.prototype.constructor = XString;
        XString.superclass = Expression.prototype;
        function XString(s) {
          if (arguments.length > 0) {
            this.init(s);
          }
        }
        XString.prototype.init = function(s) {
          this.str = String(s);
        };
        XString.prototype.toString = function() {
          return this.str;
        };
        XString.prototype.evaluate = function(c) {
          return this;
        };
        XString.prototype.string = function() {
          return this;
        };
        XString.prototype.number = function() {
          return new XNumber(this.str);
        };
        XString.prototype.bool = function() {
          return new XBoolean(this.str);
        };
        XString.prototype.nodeset = function() {
          throw new Error("Cannot convert string to nodeset");
        };
        XString.prototype.stringValue = function() {
          return this.str;
        };
        XString.prototype.numberValue = function() {
          return this.number().numberValue();
        };
        XString.prototype.booleanValue = function() {
          return this.bool().booleanValue();
        };
        XString.prototype.equals = function(r) {
          if (Utilities.instance_of(r, XBoolean)) {
            return this.bool().equals(r);
          }
          if (Utilities.instance_of(r, XNumber)) {
            return this.number().equals(r);
          }
          if (Utilities.instance_of(r, XNodeSet)) {
            return r.compareWithString(this, Operators.equals);
          }
          return new XBoolean(this.str == r.str);
        };
        XString.prototype.notequal = function(r) {
          if (Utilities.instance_of(r, XBoolean)) {
            return this.bool().notequal(r);
          }
          if (Utilities.instance_of(r, XNumber)) {
            return this.number().notequal(r);
          }
          if (Utilities.instance_of(r, XNodeSet)) {
            return r.compareWithString(this, Operators.notequal);
          }
          return new XBoolean(this.str != r.str);
        };
        XString.prototype.lessthan = function(r) {
          return this.number().lessthan(r);
        };
        XString.prototype.greaterthan = function(r) {
          return this.number().greaterthan(r);
        };
        XString.prototype.lessthanorequal = function(r) {
          return this.number().lessthanorequal(r);
        };
        XString.prototype.greaterthanorequal = function(r) {
          return this.number().greaterthanorequal(r);
        };
        XNumber.prototype = new Expression();
        XNumber.prototype.constructor = XNumber;
        XNumber.superclass = Expression.prototype;
        function XNumber(n) {
          if (arguments.length > 0) {
            this.init(n);
          }
        }
        XNumber.prototype.init = function(n) {
          this.num = typeof n === "string" ? this.parse(n) : Number(n);
        };
        XNumber.prototype.numberFormat = /^\s*-?[0-9]*\.?[0-9]+\s*$/;
        XNumber.prototype.parse = function(s) {
          return this.numberFormat.test(s) ? parseFloat(s) : Number.NaN;
        };
        function padSmallNumber(numberStr) {
          var parts = numberStr.split("e-");
          var base = parts[0].replace(".", "");
          var exponent = Number(parts[1]);
          for (var i = 0; i < exponent - 1; i += 1) {
            base = "0" + base;
          }
          return "0." + base;
        }
        function padLargeNumber(numberStr) {
          var parts = numberStr.split("e");
          var base = parts[0].replace(".", "");
          var exponent = Number(parts[1]);
          var zerosToAppend = exponent + 1 - base.length;
          for (var i = 0; i < zerosToAppend; i += 1) {
            base += "0";
          }
          return base;
        }
        XNumber.prototype.toString = function() {
          var strValue = this.num.toString();
          if (strValue.indexOf("e-") !== -1) {
            return padSmallNumber(strValue);
          }
          if (strValue.indexOf("e") !== -1) {
            return padLargeNumber(strValue);
          }
          return strValue;
        };
        XNumber.prototype.evaluate = function(c) {
          return this;
        };
        XNumber.prototype.string = function() {
          return new XString(this.toString());
        };
        XNumber.prototype.number = function() {
          return this;
        };
        XNumber.prototype.bool = function() {
          return new XBoolean(this.num);
        };
        XNumber.prototype.nodeset = function() {
          throw new Error("Cannot convert number to nodeset");
        };
        XNumber.prototype.stringValue = function() {
          return this.string().stringValue();
        };
        XNumber.prototype.numberValue = function() {
          return this.num;
        };
        XNumber.prototype.booleanValue = function() {
          return this.bool().booleanValue();
        };
        XNumber.prototype.negate = function() {
          return new XNumber(-this.num);
        };
        XNumber.prototype.equals = function(r) {
          if (Utilities.instance_of(r, XBoolean)) {
            return this.bool().equals(r);
          }
          if (Utilities.instance_of(r, XString)) {
            return this.equals(r.number());
          }
          if (Utilities.instance_of(r, XNodeSet)) {
            return r.compareWithNumber(this, Operators.equals);
          }
          return new XBoolean(this.num == r.num);
        };
        XNumber.prototype.notequal = function(r) {
          if (Utilities.instance_of(r, XBoolean)) {
            return this.bool().notequal(r);
          }
          if (Utilities.instance_of(r, XString)) {
            return this.notequal(r.number());
          }
          if (Utilities.instance_of(r, XNodeSet)) {
            return r.compareWithNumber(this, Operators.notequal);
          }
          return new XBoolean(this.num != r.num);
        };
        XNumber.prototype.lessthan = function(r) {
          if (Utilities.instance_of(r, XNodeSet)) {
            return r.compareWithNumber(this, Operators.greaterthan);
          }
          if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) {
            return this.lessthan(r.number());
          }
          return new XBoolean(this.num < r.num);
        };
        XNumber.prototype.greaterthan = function(r) {
          if (Utilities.instance_of(r, XNodeSet)) {
            return r.compareWithNumber(this, Operators.lessthan);
          }
          if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) {
            return this.greaterthan(r.number());
          }
          return new XBoolean(this.num > r.num);
        };
        XNumber.prototype.lessthanorequal = function(r) {
          if (Utilities.instance_of(r, XNodeSet)) {
            return r.compareWithNumber(this, Operators.greaterthanorequal);
          }
          if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) {
            return this.lessthanorequal(r.number());
          }
          return new XBoolean(this.num <= r.num);
        };
        XNumber.prototype.greaterthanorequal = function(r) {
          if (Utilities.instance_of(r, XNodeSet)) {
            return r.compareWithNumber(this, Operators.lessthanorequal);
          }
          if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) {
            return this.greaterthanorequal(r.number());
          }
          return new XBoolean(this.num >= r.num);
        };
        XNumber.prototype.plus = function(r) {
          return new XNumber(this.num + r.num);
        };
        XNumber.prototype.minus = function(r) {
          return new XNumber(this.num - r.num);
        };
        XNumber.prototype.multiply = function(r) {
          return new XNumber(this.num * r.num);
        };
        XNumber.prototype.div = function(r) {
          return new XNumber(this.num / r.num);
        };
        XNumber.prototype.mod = function(r) {
          return new XNumber(this.num % r.num);
        };
        XBoolean.prototype = new Expression();
        XBoolean.prototype.constructor = XBoolean;
        XBoolean.superclass = Expression.prototype;
        function XBoolean(b) {
          if (arguments.length > 0) {
            this.init(b);
          }
        }
        XBoolean.prototype.init = function(b) {
          this.b = Boolean(b);
        };
        XBoolean.prototype.toString = function() {
          return this.b.toString();
        };
        XBoolean.prototype.evaluate = function(c) {
          return this;
        };
        XBoolean.prototype.string = function() {
          return new XString(this.b);
        };
        XBoolean.prototype.number = function() {
          return new XNumber(this.b);
        };
        XBoolean.prototype.bool = function() {
          return this;
        };
        XBoolean.prototype.nodeset = function() {
          throw new Error("Cannot convert boolean to nodeset");
        };
        XBoolean.prototype.stringValue = function() {
          return this.string().stringValue();
        };
        XBoolean.prototype.numberValue = function() {
          return this.number().numberValue();
        };
        XBoolean.prototype.booleanValue = function() {
          return this.b;
        };
        XBoolean.prototype.not = function() {
          return new XBoolean(!this.b);
        };
        XBoolean.prototype.equals = function(r) {
          if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) {
            return this.equals(r.bool());
          }
          if (Utilities.instance_of(r, XNodeSet)) {
            return r.compareWithBoolean(this, Operators.equals);
          }
          return new XBoolean(this.b == r.b);
        };
        XBoolean.prototype.notequal = function(r) {
          if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) {
            return this.notequal(r.bool());
          }
          if (Utilities.instance_of(r, XNodeSet)) {
            return r.compareWithBoolean(this, Operators.notequal);
          }
          return new XBoolean(this.b != r.b);
        };
        XBoolean.prototype.lessthan = function(r) {
          return this.number().lessthan(r);
        };
        XBoolean.prototype.greaterthan = function(r) {
          return this.number().greaterthan(r);
        };
        XBoolean.prototype.lessthanorequal = function(r) {
          return this.number().lessthanorequal(r);
        };
        XBoolean.prototype.greaterthanorequal = function(r) {
          return this.number().greaterthanorequal(r);
        };
        XBoolean.true_ = new XBoolean(true);
        XBoolean.false_ = new XBoolean(false);
        AVLTree.prototype = new Object();
        AVLTree.prototype.constructor = AVLTree;
        AVLTree.superclass = Object.prototype;
        function AVLTree(n) {
          this.init(n);
        }
        AVLTree.prototype.init = function(n) {
          this.left = null;
          this.right = null;
          this.node = n;
          this.depth = 1;
        };
        AVLTree.prototype.balance = function() {
          var ldepth = this.left == null ? 0 : this.left.depth;
          var rdepth = this.right == null ? 0 : this.right.depth;
          if (ldepth > rdepth + 1) {
            var lldepth = this.left.left == null ? 0 : this.left.left.depth;
            var lrdepth = this.left.right == null ? 0 : this.left.right.depth;
            if (lldepth < lrdepth) {
              this.left.rotateRR();
            }
            this.rotateLL();
          } else if (ldepth + 1 < rdepth) {
            var rrdepth = this.right.right == null ? 0 : this.right.right.depth;
            var rldepth = this.right.left == null ? 0 : this.right.left.depth;
            if (rldepth > rrdepth) {
              this.right.rotateLL();
            }
            this.rotateRR();
          }
        };
        AVLTree.prototype.rotateLL = function() {
          var nodeBefore = this.node;
          var rightBefore = this.right;
          this.node = this.left.node;
          this.right = this.left;
          this.left = this.left.left;
          this.right.left = this.right.right;
          this.right.right = rightBefore;
          this.right.node = nodeBefore;
          this.right.updateInNewLocation();
          this.updateInNewLocation();
        };
        AVLTree.prototype.rotateRR = function() {
          var nodeBefore = this.node;
          var leftBefore = this.left;
          this.node = this.right.node;
          this.left = this.right;
          this.right = this.right.right;
          this.left.right = this.left.left;
          this.left.left = leftBefore;
          this.left.node = nodeBefore;
          this.left.updateInNewLocation();
          this.updateInNewLocation();
        };
        AVLTree.prototype.updateInNewLocation = function() {
          this.getDepthFromChildren();
        };
        AVLTree.prototype.getDepthFromChildren = function() {
          this.depth = this.node == null ? 0 : 1;
          if (this.left != null) {
            this.depth = this.left.depth + 1;
          }
          if (this.right != null && this.depth <= this.right.depth) {
            this.depth = this.right.depth + 1;
          }
        };
        function nodeOrder(n1, n2) {
          if (n1 === n2) {
            return 0;
          }
          if (n1.compareDocumentPosition) {
            var cpos = n1.compareDocumentPosition(n2);
            if (cpos & 1) {
              return 1;
            }
            if (cpos & 10) {
              return 1;
            }
            if (cpos & 20) {
              return -1;
            }
            return 0;
          }
          var d1 = 0, d2 = 0;
          for (var m1 = n1; m1 != null; m1 = m1.parentNode || m1.ownerElement) {
            d1++;
          }
          for (var m2 = n2; m2 != null; m2 = m2.parentNode || m2.ownerElement) {
            d2++;
          }
          if (d1 > d2) {
            while (d1 > d2) {
              n1 = n1.parentNode || n1.ownerElement;
              d1--;
            }
            if (n1 === n2) {
              return 1;
            }
          } else if (d2 > d1) {
            while (d2 > d1) {
              n2 = n2.parentNode || n2.ownerElement;
              d2--;
            }
            if (n1 === n2) {
              return -1;
            }
          }
          var n1Par = n1.parentNode || n1.ownerElement, n2Par = n2.parentNode || n2.ownerElement;
          while (n1Par !== n2Par) {
            n1 = n1Par;
            n2 = n2Par;
            n1Par = n1.parentNode || n1.ownerElement;
            n2Par = n2.parentNode || n2.ownerElement;
          }
          var n1isAttr = isAttributeLike(n1);
          var n2isAttr = isAttributeLike(n2);
          if (n1isAttr && !n2isAttr) {
            return -1;
          }
          if (!n1isAttr && n2isAttr) {
            return 1;
          }
          if (n1.isXPathNamespace) {
            if (n1.nodeValue === XPath.XML_NAMESPACE_URI) {
              return -1;
            }
            if (!n2.isXPathNamespace) {
              return -1;
            }
            if (n2.nodeValue === XPath.XML_NAMESPACE_URI) {
              return 1;
            }
          } else if (n2.isXPathNamespace) {
            return 1;
          }
          if (n1Par) {
            var cn = n1isAttr ? n1Par.attributes : n1Par.childNodes;
            var len = cn.length;
            var n1Compare = n1.baseNode || n1;
            var n2Compare = n2.baseNode || n2;
            for (var i = 0; i < len; i += 1) {
              var n = cn[i];
              if (n === n1Compare) {
                return -1;
              }
              if (n === n2Compare) {
                return 1;
              }
            }
          }
          throw new Error("Unexpected: could not determine node order");
        }
        AVLTree.prototype.add = function(n) {
          if (n === this.node) {
            return false;
          }
          var o = nodeOrder(n, this.node);
          var ret = false;
          if (o == -1) {
            if (this.left == null) {
              this.left = new AVLTree(n);
              ret = true;
            } else {
              ret = this.left.add(n);
              if (ret) {
                this.balance();
              }
            }
          } else if (o == 1) {
            if (this.right == null) {
              this.right = new AVLTree(n);
              ret = true;
            } else {
              ret = this.right.add(n);
              if (ret) {
                this.balance();
              }
            }
          }
          if (ret) {
            this.getDepthFromChildren();
          }
          return ret;
        };
        XNodeSet.prototype = new Expression();
        XNodeSet.prototype.constructor = XNodeSet;
        XNodeSet.superclass = Expression.prototype;
        function XNodeSet() {
          this.init();
        }
        XNodeSet.prototype.init = function() {
          this.tree = null;
          this.nodes = [];
          this.size = 0;
        };
        XNodeSet.prototype.toString = function() {
          var p = this.first();
          if (p == null) {
            return "";
          }
          return this.stringForNode(p);
        };
        XNodeSet.prototype.evaluate = function(c) {
          return this;
        };
        XNodeSet.prototype.string = function() {
          return new XString(this.toString());
        };
        XNodeSet.prototype.stringValue = function() {
          return this.toString();
        };
        XNodeSet.prototype.number = function() {
          return new XNumber(this.string());
        };
        XNodeSet.prototype.numberValue = function() {
          return Number(this.string());
        };
        XNodeSet.prototype.bool = function() {
          return new XBoolean(this.booleanValue());
        };
        XNodeSet.prototype.booleanValue = function() {
          return !!this.size;
        };
        XNodeSet.prototype.nodeset = function() {
          return this;
        };
        XNodeSet.prototype.stringForNode = function(n) {
          if (n.nodeType == NodeTypes.DOCUMENT_NODE || n.nodeType == NodeTypes.ELEMENT_NODE || n.nodeType === NodeTypes.DOCUMENT_FRAGMENT_NODE) {
            return this.stringForContainerNode(n);
          }
          if (n.nodeType === NodeTypes.ATTRIBUTE_NODE) {
            return n.value || n.nodeValue;
          }
          if (n.isNamespaceNode) {
            return n.namespace;
          }
          return n.nodeValue;
        };
        XNodeSet.prototype.stringForContainerNode = function(n) {
          var s = "";
          for (var n2 = n.firstChild; n2 != null; n2 = n2.nextSibling) {
            var nt = n2.nodeType;
            if (nt === 1 || nt === 3 || nt === 4 || nt === 9 || nt === 11) {
              s += this.stringForNode(n2);
            }
          }
          return s;
        };
        XNodeSet.prototype.buildTree = function() {
          if (!this.tree && this.nodes.length) {
            this.tree = new AVLTree(this.nodes[0]);
            for (var i = 1; i < this.nodes.length; i += 1) {
              this.tree.add(this.nodes[i]);
            }
          }
          return this.tree;
        };
        XNodeSet.prototype.first = function() {
          var p = this.buildTree();
          if (p == null) {
            return null;
          }
          while (p.left != null) {
            p = p.left;
          }
          return p.node;
        };
        XNodeSet.prototype.add = function(n) {
          for (var i = 0; i < this.nodes.length; i += 1) {
            if (n === this.nodes[i]) {
              return;
            }
          }
          this.tree = null;
          this.nodes.push(n);
          this.size += 1;
        };
        XNodeSet.prototype.addArray = function(ns) {
          var self = this;
          forEach(function(x) {
            self.add(x);
          }, ns);
        };
        XNodeSet.prototype.toArray = function() {
          var a = [];
          this.toArrayRec(this.buildTree(), a);
          return a;
        };
        XNodeSet.prototype.toArrayRec = function(t, a) {
          if (t != null) {
            this.toArrayRec(t.left, a);
            a.push(t.node);
            this.toArrayRec(t.right, a);
          }
        };
        XNodeSet.prototype.toUnsortedArray = function() {
          return this.nodes.slice();
        };
        XNodeSet.prototype.compareWithString = function(r, o) {
          var a = this.toUnsortedArray();
          for (var i = 0; i < a.length; i++) {
            var n = a[i];
            var l = new XString(this.stringForNode(n));
            var res = o(l, r);
            if (res.booleanValue()) {
              return res;
            }
          }
          return new XBoolean(false);
        };
        XNodeSet.prototype.compareWithNumber = function(r, o) {
          var a = this.toUnsortedArray();
          for (var i = 0; i < a.length; i++) {
            var n = a[i];
            var l = new XNumber(this.stringForNode(n));
            var res = o(l, r);
            if (res.booleanValue()) {
              return res;
            }
          }
          return new XBoolean(false);
        };
        XNodeSet.prototype.compareWithBoolean = function(r, o) {
          return o(this.bool(), r);
        };
        XNodeSet.prototype.compareWithNodeSet = function(r, o) {
          var arr = this.toUnsortedArray();
          var oInvert = function(lop, rop) {
            return o(rop, lop);
          };
          for (var i = 0; i < arr.length; i++) {
            var l = new XString(this.stringForNode(arr[i]));
            var res = r.compareWithString(l, oInvert);
            if (res.booleanValue()) {
              return res;
            }
          }
          return new XBoolean(false);
        };
        XNodeSet.compareWith = curry(function(o, r) {
          if (Utilities.instance_of(r, XString)) {
            return this.compareWithString(r, o);
          }
          if (Utilities.instance_of(r, XNumber)) {
            return this.compareWithNumber(r, o);
          }
          if (Utilities.instance_of(r, XBoolean)) {
            return this.compareWithBoolean(r, o);
          }
          return this.compareWithNodeSet(r, o);
        });
        XNodeSet.prototype.equals = XNodeSet.compareWith(Operators.equals);
        XNodeSet.prototype.notequal = XNodeSet.compareWith(Operators.notequal);
        XNodeSet.prototype.lessthan = XNodeSet.compareWith(Operators.lessthan);
        XNodeSet.prototype.greaterthan = XNodeSet.compareWith(Operators.greaterthan);
        XNodeSet.prototype.lessthanorequal = XNodeSet.compareWith(Operators.lessthanorequal);
        XNodeSet.prototype.greaterthanorequal = XNodeSet.compareWith(Operators.greaterthanorequal);
        XNodeSet.prototype.union = function(r) {
          var ns = new XNodeSet();
          ns.addArray(this.toUnsortedArray());
          ns.addArray(r.toUnsortedArray());
          return ns;
        };
        XPathNamespace.prototype = new Object();
        XPathNamespace.prototype.constructor = XPathNamespace;
        XPathNamespace.superclass = Object.prototype;
        function XPathNamespace(pre, node, uri, p) {
          this.isXPathNamespace = true;
          this.baseNode = node;
          this.ownerDocument = p.ownerDocument;
          this.nodeName = pre;
          this.prefix = pre;
          this.localName = pre;
          this.namespaceURI = null;
          this.nodeValue = uri;
          this.ownerElement = p;
          this.nodeType = NodeTypes.NAMESPACE_NODE;
        }
        XPathNamespace.prototype.toString = function() {
          return '{ "' + this.prefix + '", "' + this.namespaceURI + '" }';
        };
        XPathContext.prototype = new Object();
        XPathContext.prototype.constructor = XPathContext;
        XPathContext.superclass = Object.prototype;
        function XPathContext(vr, nr, fr) {
          this.variableResolver = vr != null ? vr : new VariableResolver();
          this.namespaceResolver = nr != null ? nr : new NamespaceResolver();
          this.functionResolver = fr != null ? fr : new FunctionResolver();
        }
        XPathContext.prototype.extend = function(newProps) {
          return assign(new XPathContext(), this, newProps);
        };
        VariableResolver.prototype = new Object();
        VariableResolver.prototype.constructor = VariableResolver;
        VariableResolver.superclass = Object.prototype;
        function VariableResolver() {
        }
        VariableResolver.prototype.getVariable = function(ln, ns) {
          return null;
        };
        FunctionResolver.prototype = new Object();
        FunctionResolver.prototype.constructor = FunctionResolver;
        FunctionResolver.superclass = Object.prototype;
        function FunctionResolver(thisArg) {
          this.thisArg = thisArg != null ? thisArg : Functions;
          this.functions = new Object();
          this.addStandardFunctions();
        }
        FunctionResolver.prototype.addStandardFunctions = function() {
          this.functions["{}last"] = Functions.last;
          this.functions["{}position"] = Functions.position;
          this.functions["{}count"] = Functions.count;
          this.functions["{}id"] = Functions.id;
          this.functions["{}local-name"] = Functions.localName;
          this.functions["{}namespace-uri"] = Functions.namespaceURI;
          this.functions["{}name"] = Functions.name;
          this.functions["{}string"] = Functions.string;
          this.functions["{}concat"] = Functions.concat;
          this.functions["{}starts-with"] = Functions.startsWith;
          this.functions["{}contains"] = Functions.contains;
          this.functions["{}substring-before"] = Functions.substringBefore;
          this.functions["{}substring-after"] = Functions.substringAfter;
          this.functions["{}substring"] = Functions.substring;
          this.functions["{}string-length"] = Functions.stringLength;
          this.functions["{}normalize-space"] = Functions.normalizeSpace;
          this.functions["{}translate"] = Functions.translate;
          this.functions["{}boolean"] = Functions.boolean_;
          this.functions["{}not"] = Functions.not;
          this.functions["{}true"] = Functions.true_;
          this.functions["{}false"] = Functions.false_;
          this.functions["{}lang"] = Functions.lang;
          this.functions["{}number"] = Functions.number;
          this.functions["{}sum"] = Functions.sum;
          this.functions["{}floor"] = Functions.floor;
          this.functions["{}ceiling"] = Functions.ceiling;
          this.functions["{}round"] = Functions.round;
        };
        FunctionResolver.prototype.addFunction = function(ns, ln, f) {
          this.functions["{" + ns + "}" + ln] = f;
        };
        FunctionResolver.getFunctionFromContext = function(qName, context) {
          var parts = Utilities.resolveQName(qName, context.namespaceResolver, context.contextNode, false);
          if (parts[0] === null) {
            throw new Error("Cannot resolve QName " + name);
          }
          return context.functionResolver.getFunction(parts[1], parts[0]);
        };
        FunctionResolver.prototype.getFunction = function(localName, namespace) {
          return this.functions["{" + namespace + "}" + localName];
        };
        NamespaceResolver.prototype = new Object();
        NamespaceResolver.prototype.constructor = NamespaceResolver;
        NamespaceResolver.superclass = Object.prototype;
        function NamespaceResolver() {
        }
        NamespaceResolver.prototype.getNamespace = function(prefix, n) {
          if (prefix == "xml") {
            return XPath.XML_NAMESPACE_URI;
          } else if (prefix == "xmlns") {
            return XPath.XMLNS_NAMESPACE_URI;
          }
          if (n.nodeType == NodeTypes.DOCUMENT_NODE) {
            n = n.documentElement;
          } else if (n.nodeType == NodeTypes.ATTRIBUTE_NODE) {
            n = PathExpr.getOwnerElement(n);
          } else if (n.nodeType != NodeTypes.ELEMENT_NODE) {
            n = n.parentNode;
          }
          while (n != null && n.nodeType == NodeTypes.ELEMENT_NODE) {
            var nnm = n.attributes;
            for (var i = 0; i < nnm.length; i++) {
              var a = nnm.item(i);
              var aname = a.name || a.nodeName;
              if (aname === "xmlns" && prefix === "" || aname === "xmlns:" + prefix) {
                return String(a.value || a.nodeValue);
              }
            }
            n = n.parentNode;
          }
          return null;
        };
        var Functions = new Object();
        Functions.last = function(c) {
          if (arguments.length != 1) {
            throw new Error("Function last expects ()");
          }
          return new XNumber(c.contextSize);
        };
        Functions.position = function(c) {
          if (arguments.length != 1) {
            throw new Error("Function position expects ()");
          }
          return new XNumber(c.contextPosition);
        };
        Functions.count = function() {
          var c = arguments[0];
          var ns;
          if (arguments.length != 2 || !Utilities.instance_of(ns = arguments[1].evaluate(c), XNodeSet)) {
            throw new Error("Function count expects (node-set)");
          }
          return new XNumber(ns.size);
        };
        Functions.id = function() {
          var c = arguments[0];
          var id;
          if (arguments.length != 2) {
            throw new Error("Function id expects (object)");
          }
          id = arguments[1].evaluate(c);
          if (Utilities.instance_of(id, XNodeSet)) {
            id = id.toArray().join(" ");
          } else {
            id = id.stringValue();
          }
          var ids = id.split(/[\x0d\x0a\x09\x20]+/);
          var count = 0;
          var ns = new XNodeSet();
          var doc = c.contextNode.nodeType == NodeTypes.DOCUMENT_NODE ? c.contextNode : c.contextNode.ownerDocument;
          for (var i = 0; i < ids.length; i++) {
            var n;
            if (doc.getElementById) {
              n = doc.getElementById(ids[i]);
            } else {
              n = Utilities.getElementById(doc, ids[i]);
            }
            if (n != null) {
              ns.add(n);
              count++;
            }
          }
          return ns;
        };
        Functions.localName = function(c, eNode) {
          var n;
          if (arguments.length == 1) {
            n = c.contextNode;
          } else if (arguments.length == 2) {
            n = eNode.evaluate(c).first();
          } else {
            throw new Error("Function local-name expects (node-set?)");
          }
          if (n == null) {
            return new XString("");
          }
          return new XString(
            n.localName || //  standard elements and attributes
            n.baseName || //  IE
            n.target || //  processing instructions
            n.nodeName || //  DOM1 elements
            ""
            //  fallback
          );
        };
        Functions.namespaceURI = function() {
          var c = arguments[0];
          var n;
          if (arguments.length == 1) {
            n = c.contextNode;
          } else if (arguments.length == 2) {
            n = arguments[1].evaluate(c).first();
          } else {
            throw new Error("Function namespace-uri expects (node-set?)");
          }
          if (n == null) {
            return new XString("");
          }
          return new XString(n.namespaceURI || "");
        };
        Functions.name = function() {
          var c = arguments[0];
          var n;
          if (arguments.length == 1) {
            n = c.contextNode;
          } else if (arguments.length == 2) {
            n = arguments[1].evaluate(c).first();
          } else {
            throw new Error("Function name expects (node-set?)");
          }
          if (n == null) {
            return new XString("");
          }
          if (n.nodeType == NodeTypes.ELEMENT_NODE) {
            return new XString(n.nodeName);
          } else if (n.nodeType == NodeTypes.ATTRIBUTE_NODE) {
            return new XString(n.name || n.nodeName);
          } else if (n.nodeType === NodeTypes.PROCESSING_INSTRUCTION_NODE) {
            return new XString(n.target || n.nodeName);
          } else if (n.localName == null) {
            return new XString("");
          } else {
            return new XString(n.localName);
          }
        };
        Functions.string = function() {
          var c = arguments[0];
          if (arguments.length == 1) {
            return new XString(XNodeSet.prototype.stringForNode(c.contextNode));
          } else if (arguments.length == 2) {
            return arguments[1].evaluate(c).string();
          }
          throw new Error("Function string expects (object?)");
        };
        Functions.concat = function(c) {
          if (arguments.length < 3) {
            throw new Error("Function concat expects (string, string[, string]*)");
          }
          var s = "";
          for (var i = 1; i < arguments.length; i++) {
            s += arguments[i].evaluate(c).stringValue();
          }
          return new XString(s);
        };
        Functions.startsWith = function() {
          var c = arguments[0];
          if (arguments.length != 3) {
            throw new Error("Function startsWith expects (string, string)");
          }
          var s1 = arguments[1].evaluate(c).stringValue();
          var s2 = arguments[2].evaluate(c).stringValue();
          return new XBoolean(s1.substring(0, s2.length) == s2);
        };
        Functions.contains = function() {
          var c = arguments[0];
          if (arguments.length != 3) {
            throw new Error("Function contains expects (string, string)");
          }
          var s1 = arguments[1].evaluate(c).stringValue();
          var s2 = arguments[2].evaluate(c).stringValue();
          return new XBoolean(s1.indexOf(s2) !== -1);
        };
        Functions.substringBefore = function() {
          var c = arguments[0];
          if (arguments.length != 3) {
            throw new Error("Function substring-before expects (string, string)");
          }
          var s1 = arguments[1].evaluate(c).stringValue();
          var s2 = arguments[2].evaluate(c).stringValue();
          return new XString(s1.substring(0, s1.indexOf(s2)));
        };
        Functions.substringAfter = function() {
          var c = arguments[0];
          if (arguments.length != 3) {
            throw new Error("Function substring-after expects (string, string)");
          }
          var s1 = arguments[1].evaluate(c).stringValue();
          var s2 = arguments[2].evaluate(c).stringValue();
          if (s2.length == 0) {
            return new XString(s1);
          }
          var i = s1.indexOf(s2);
          if (i == -1) {
            return new XString("");
          }
          return new XString(s1.substring(i + s2.length));
        };
        Functions.substring = function() {
          var c = arguments[0];
          if (!(arguments.length == 3 || arguments.length == 4)) {
            throw new Error("Function substring expects (string, number, number?)");
          }
          var s = arguments[1].evaluate(c).stringValue();
          var n1 = Math.round(arguments[2].evaluate(c).numberValue()) - 1;
          var n2 = arguments.length == 4 ? n1 + Math.round(arguments[3].evaluate(c).numberValue()) : void 0;
          return new XString(s.substring(n1, n2));
        };
        Functions.stringLength = function() {
          var c = arguments[0];
          var s;
          if (arguments.length == 1) {
            s = XNodeSet.prototype.stringForNode(c.contextNode);
          } else if (arguments.length == 2) {
            s = arguments[1].evaluate(c).stringValue();
          } else {
            throw new Error("Function string-length expects (string?)");
          }
          return new XNumber(s.length);
        };
        Functions.normalizeSpace = function() {
          var c = arguments[0];
          var s;
          if (arguments.length == 1) {
            s = XNodeSet.prototype.stringForNode(c.contextNode);
          } else if (arguments.length == 2) {
            s = arguments[1].evaluate(c).stringValue();
          } else {
            throw new Error("Function normalize-space expects (string?)");
          }
          var i = 0;
          var j = s.length - 1;
          while (Utilities.isSpace(s.charCodeAt(j))) {
            j--;
          }
          var t = "";
          while (i <= j && Utilities.isSpace(s.charCodeAt(i))) {
            i++;
          }
          while (i <= j) {
            if (Utilities.isSpace(s.charCodeAt(i))) {
              t += " ";
              while (i <= j && Utilities.isSpace(s.charCodeAt(i))) {
                i++;
              }
            } else {
              t += s.charAt(i);
              i++;
            }
          }
          return new XString(t);
        };
        Functions.translate = function(c, eValue, eFrom, eTo) {
          if (arguments.length != 4) {
            throw new Error("Function translate expects (string, string, string)");
          }
          var value = eValue.evaluate(c).stringValue();
          var from = eFrom.evaluate(c).stringValue();
          var to = eTo.evaluate(c).stringValue();
          var cMap = reduce(function(acc, ch, i) {
            if (!(ch in acc)) {
              acc[ch] = i > to.length ? "" : to[i];
            }
            return acc;
          }, {}, from);
          var t = join(
            "",
            map(function(ch) {
              return ch in cMap ? cMap[ch] : ch;
            }, value)
          );
          return new XString(t);
        };
        Functions.boolean_ = function() {
          var c = arguments[0];
          if (arguments.length != 2) {
            throw new Error("Function boolean expects (object)");
          }
          return arguments[1].evaluate(c).bool();
        };
        Functions.not = function(c, eValue) {
          if (arguments.length != 2) {
            throw new Error("Function not expects (object)");
          }
          return eValue.evaluate(c).bool().not();
        };
        Functions.true_ = function() {
          if (arguments.length != 1) {
            throw new Error("Function true expects ()");
          }
          return XBoolean.true_;
        };
        Functions.false_ = function() {
          if (arguments.length != 1) {
            throw new Error("Function false expects ()");
          }
          return XBoolean.false_;
        };
        Functions.lang = function() {
          var c = arguments[0];
          if (arguments.length != 2) {
            throw new Error("Function lang expects (string)");
          }
          var lang;
          for (var n = c.contextNode; n != null && n.nodeType != NodeTypes.DOCUMENT_NODE; n = n.parentNode) {
            var a = n.getAttributeNS(XPath.XML_NAMESPACE_URI, "lang");
            if (a != null) {
              lang = String(a);
              break;
            }
          }
          if (lang == null) {
            return XBoolean.false_;
          }
          var s = arguments[1].evaluate(c).stringValue();
          return new XBoolean(lang.substring(0, s.length) == s && (lang.length == s.length || lang.charAt(s.length) == "-"));
        };
        Functions.number = function() {
          var c = arguments[0];
          if (!(arguments.length == 1 || arguments.length == 2)) {
            throw new Error("Function number expects (object?)");
          }
          if (arguments.length == 1) {
            return new XNumber(XNodeSet.prototype.stringForNode(c.contextNode));
          }
          return arguments[1].evaluate(c).number();
        };
        Functions.sum = function() {
          var c = arguments[0];
          var ns;
          if (arguments.length != 2 || !Utilities.instance_of(ns = arguments[1].evaluate(c), XNodeSet)) {
            throw new Error("Function sum expects (node-set)");
          }
          ns = ns.toUnsortedArray();
          var n = 0;
          for (var i = 0; i < ns.length; i++) {
            n += new XNumber(XNodeSet.prototype.stringForNode(ns[i])).numberValue();
          }
          return new XNumber(n);
        };
        Functions.floor = function() {
          var c = arguments[0];
          if (arguments.length != 2) {
            throw new Error("Function floor expects (number)");
          }
          return new XNumber(Math.floor(arguments[1].evaluate(c).numberValue()));
        };
        Functions.ceiling = function() {
          var c = arguments[0];
          if (arguments.length != 2) {
            throw new Error("Function ceiling expects (number)");
          }
          return new XNumber(Math.ceil(arguments[1].evaluate(c).numberValue()));
        };
        Functions.round = function() {
          var c = arguments[0];
          if (arguments.length != 2) {
            throw new Error("Function round expects (number)");
          }
          return new XNumber(Math.round(arguments[1].evaluate(c).numberValue()));
        };
        var Utilities = new Object();
        var isAttributeLike = function(val) {
          return val && (val.nodeType === NodeTypes.ATTRIBUTE_NODE || val.ownerElement || val.isXPathNamespace);
        };
        Utilities.splitQName = function(qn) {
          var i = qn.indexOf(":");
          if (i == -1) {
            return [null, qn];
          }
          return [qn.substring(0, i), qn.substring(i + 1)];
        };
        Utilities.resolveQName = function(qn, nr, n, useDefault) {
          var parts = Utilities.splitQName(qn);
          if (parts[0] != null) {
            parts[0] = nr.getNamespace(parts[0], n);
          } else {
            if (useDefault) {
              parts[0] = nr.getNamespace("", n);
              if (parts[0] == null) {
                parts[0] = "";
              }
            } else {
              parts[0] = "";
            }
          }
          return parts;
        };
        Utilities.isSpace = function(c) {
          return c == 9 || c == 13 || c == 10 || c == 32;
        };
        Utilities.isLetter = function(c) {
          return c >= 65 && c <= 90 || c >= 97 && c <= 122 || c >= 192 && c <= 214 || c >= 216 && c <= 246 || c >= 248 && c <= 255 || c >= 256 && c <= 305 || c >= 308 && c <= 318 || c >= 321 && c <= 328 || c >= 330 && c <= 382 || c >= 384 && c <= 451 || c >= 461 && c <= 496 || c >= 500 && c <= 501 || c >= 506 && c <= 535 || c >= 592 && c <= 680 || c >= 699 && c <= 705 || c == 902 || c >= 904 && c <= 906 || c == 908 || c >= 910 && c <= 929 || c >= 931 && c <= 974 || c >= 976 && c <= 982 || c == 986 || c == 988 || c == 990 || c == 992 || c >= 994 && c <= 1011 || c >= 1025 && c <= 1036 || c >= 1038 && c <= 1103 || c >= 1105 && c <= 1116 || c >= 1118 && c <= 1153 || c >= 1168 && c <= 1220 || c >= 1223 && c <= 1224 || c >= 1227 && c <= 1228 || c >= 1232 && c <= 1259 || c >= 1262 && c <= 1269 || c >= 1272 && c <= 1273 || c >= 1329 && c <= 1366 || c == 1369 || c >= 1377 && c <= 1414 || c >= 1488 && c <= 1514 || c >= 1520 && c <= 1522 || c >= 1569 && c <= 1594 || c >= 1601 && c <= 1610 || c >= 1649 && c <= 1719 || c >= 1722 && c <= 1726 || c >= 1728 && c <= 1742 || c >= 1744 && c <= 1747 || c == 1749 || c >= 1765 && c <= 1766 || c >= 2309 && c <= 2361 || c == 2365 || c >= 2392 && c <= 2401 || c >= 2437 && c <= 2444 || c >= 2447 && c <= 2448 || c >= 2451 && c <= 2472 || c >= 2474 && c <= 2480 || c == 2482 || c >= 2486 && c <= 2489 || c >= 2524 && c <= 2525 || c >= 2527 && c <= 2529 || c >= 2544 && c <= 2545 || c >= 2565 && c <= 2570 || c >= 2575 && c <= 2576 || c >= 2579 && c <= 2600 || c >= 2602 && c <= 2608 || c >= 2610 && c <= 2611 || c >= 2613 && c <= 2614 || c >= 2616 && c <= 2617 || c >= 2649 && c <= 2652 || c == 2654 || c >= 2674 && c <= 2676 || c >= 2693 && c <= 2699 || c == 2701 || c >= 2703 && c <= 2705 || c >= 2707 && c <= 2728 || c >= 2730 && c <= 2736 || c >= 2738 && c <= 2739 || c >= 2741 && c <= 2745 || c == 2749 || c == 2784 || c >= 2821 && c <= 2828 || c >= 2831 && c <= 2832 || c >= 2835 && c <= 2856 || c >= 2858 && c <= 2864 || c >= 2866 && c <= 2867 || c >= 2870 && c <= 2873 || c == 2877 || c >= 2908 && c <= 2909 || c >= 2911 && c <= 2913 || c >= 2949 && c <= 2954 || c >= 2958 && c <= 2960 || c >= 2962 && c <= 2965 || c >= 2969 && c <= 2970 || c == 2972 || c >= 2974 && c <= 2975 || c >= 2979 && c <= 2980 || c >= 2984 && c <= 2986 || c >= 2990 && c <= 2997 || c >= 2999 && c <= 3001 || c >= 3077 && c <= 3084 || c >= 3086 && c <= 3088 || c >= 3090 && c <= 3112 || c >= 3114 && c <= 3123 || c >= 3125 && c <= 3129 || c >= 3168 && c <= 3169 || c >= 3205 && c <= 3212 || c >= 3214 && c <= 3216 || c >= 3218 && c <= 3240 || c >= 3242 && c <= 3251 || c >= 3253 && c <= 3257 || c == 3294 || c >= 3296 && c <= 3297 || c >= 3333 && c <= 3340 || c >= 3342 && c <= 3344 || c >= 3346 && c <= 3368 || c >= 3370 && c <= 3385 || c >= 3424 && c <= 3425 || c >= 3585 && c <= 3630 || c == 3632 || c >= 3634 && c <= 3635 || c >= 3648 && c <= 3653 || c >= 3713 && c <= 3714 || c == 3716 || c >= 3719 && c <= 3720 || c == 3722 || c == 3725 || c >= 3732 && c <= 3735 || c >= 3737 && c <= 3743 || c >= 3745 && c <= 3747 || c == 3749 || c == 3751 || c >= 3754 && c <= 3755 || c >= 3757 && c <= 3758 || c == 3760 || c >= 3762 && c <= 3763 || c == 3773 || c >= 3776 && c <= 3780 || c >= 3904 && c <= 3911 || c >= 3913 && c <= 3945 || c >= 4256 && c <= 4293 || c >= 4304 && c <= 4342 || c == 4352 || c >= 4354 && c <= 4355 || c >= 4357 && c <= 4359 || c == 4361 || c >= 4363 && c <= 4364 || c >= 4366 && c <= 4370 || c == 4412 || c == 4414 || c == 4416 || c == 4428 || c == 4430 || c == 4432 || c >= 4436 && c <= 4437 || c == 4441 || c >= 4447 && c <= 4449 || c == 4451 || c == 4453 || c == 4455 || c == 4457 || c >= 4461 && c <= 4462 || c >= 4466 && c <= 4467 || c == 4469 || c == 4510 || c == 4520 || c == 4523 || c >= 4526 && c <= 4527 || c >= 4535 && c <= 4536 || c == 4538 || c >= 4540 && c <= 4546 || c == 4587 || c == 4592 || c == 4601 || c >= 7680 && c <= 7835 || c >= 7840 && c <= 7929 || c >= 7936 && c <= 7957 || c >= 7960 && c <= 7965 || c >= 7968 && c <= 8005 || c >= 8008 && c <= 8013 || c >= 8016 && c <= 8023 || c == 8025 || c == 8027 || c == 8029 || c >= 8031 && c <= 8061 || c >= 8064 && c <= 8116 || c >= 8118 && c <= 8124 || c == 8126 || c >= 8130 && c <= 8132 || c >= 8134 && c <= 8140 || c >= 8144 && c <= 8147 || c >= 8150 && c <= 8155 || c >= 8160 && c <= 8172 || c >= 8178 && c <= 8180 || c >= 8182 && c <= 8188 || c == 8486 || c >= 8490 && c <= 8491 || c == 8494 || c >= 8576 && c <= 8578 || c >= 12353 && c <= 12436 || c >= 12449 && c <= 12538 || c >= 12549 && c <= 12588 || c >= 44032 && c <= 55203 || c >= 19968 && c <= 40869 || c == 12295 || c >= 12321 && c <= 12329;
        };
        Utilities.isNCNameChar = function(c) {
          return c >= 48 && c <= 57 || c >= 1632 && c <= 1641 || c >= 1776 && c <= 1785 || c >= 2406 && c <= 2415 || c >= 2534 && c <= 2543 || c >= 2662 && c <= 2671 || c >= 2790 && c <= 2799 || c >= 2918 && c <= 2927 || c >= 3047 && c <= 3055 || c >= 3174 && c <= 3183 || c >= 3302 && c <= 3311 || c >= 3430 && c <= 3439 || c >= 3664 && c <= 3673 || c >= 3792 && c <= 3801 || c >= 3872 && c <= 3881 || c == 46 || c == 45 || c == 95 || Utilities.isLetter(c) || c >= 768 && c <= 837 || c >= 864 && c <= 865 || c >= 1155 && c <= 1158 || c >= 1425 && c <= 1441 || c >= 1443 && c <= 1465 || c >= 1467 && c <= 1469 || c == 1471 || c >= 1473 && c <= 1474 || c == 1476 || c >= 1611 && c <= 1618 || c == 1648 || c >= 1750 && c <= 1756 || c >= 1757 && c <= 1759 || c >= 1760 && c <= 1764 || c >= 1767 && c <= 1768 || c >= 1770 && c <= 1773 || c >= 2305 && c <= 2307 || c == 2364 || c >= 2366 && c <= 2380 || c == 2381 || c >= 2385 && c <= 2388 || c >= 2402 && c <= 2403 || c >= 2433 && c <= 2435 || c == 2492 || c == 2494 || c == 2495 || c >= 2496 && c <= 2500 || c >= 2503 && c <= 2504 || c >= 2507 && c <= 2509 || c == 2519 || c >= 2530 && c <= 2531 || c == 2562 || c == 2620 || c == 2622 || c == 2623 || c >= 2624 && c <= 2626 || c >= 2631 && c <= 2632 || c >= 2635 && c <= 2637 || c >= 2672 && c <= 2673 || c >= 2689 && c <= 2691 || c == 2748 || c >= 2750 && c <= 2757 || c >= 2759 && c <= 2761 || c >= 2763 && c <= 2765 || c >= 2817 && c <= 2819 || c == 2876 || c >= 2878 && c <= 2883 || c >= 2887 && c <= 2888 || c >= 2891 && c <= 2893 || c >= 2902 && c <= 2903 || c >= 2946 && c <= 2947 || c >= 3006 && c <= 3010 || c >= 3014 && c <= 3016 || c >= 3018 && c <= 3021 || c == 3031 || c >= 3073 && c <= 3075 || c >= 3134 && c <= 3140 || c >= 3142 && c <= 3144 || c >= 3146 && c <= 3149 || c >= 3157 && c <= 3158 || c >= 3202 && c <= 3203 || c >= 3262 && c <= 3268 || c >= 3270 && c <= 3272 || c >= 3274 && c <= 3277 || c >= 3285 && c <= 3286 || c >= 3330 && c <= 3331 || c >= 3390 && c <= 3395 || c >= 3398 && c <= 3400 || c >= 3402 && c <= 3405 || c == 3415 || c == 3633 || c >= 3636 && c <= 3642 || c >= 3655 && c <= 3662 || c == 3761 || c >= 3764 && c <= 3769 || c >= 3771 && c <= 3772 || c >= 3784 && c <= 3789 || c >= 3864 && c <= 3865 || c == 3893 || c == 3895 || c == 3897 || c == 3902 || c == 3903 || c >= 3953 && c <= 3972 || c >= 3974 && c <= 3979 || c >= 3984 && c <= 3989 || c == 3991 || c >= 3993 && c <= 4013 || c >= 4017 && c <= 4023 || c == 4025 || c >= 8400 && c <= 8412 || c == 8417 || c >= 12330 && c <= 12335 || c == 12441 || c == 12442 || c == 183 || c == 720 || c == 721 || c == 903 || c == 1600 || c == 3654 || c == 3782 || c == 12293 || c >= 12337 && c <= 12341 || c >= 12445 && c <= 12446 || c >= 12540 && c <= 12542;
        };
        Utilities.coalesceText = function(n) {
          for (var m = n.firstChild; m != null; m = m.nextSibling) {
            if (m.nodeType == NodeTypes.TEXT_NODE || m.nodeType == NodeTypes.CDATA_SECTION_NODE) {
              var s = m.nodeValue;
              var first = m;
              m = m.nextSibling;
              while (m != null && (m.nodeType == NodeTypes.TEXT_NODE || m.nodeType == NodeTypes.CDATA_SECTION_NODE)) {
                s += m.nodeValue;
                var del = m;
                m = m.nextSibling;
                del.parentNode.removeChild(del);
              }
              if (first.nodeType == NodeTypes.CDATA_SECTION_NODE) {
                var p = first.parentNode;
                if (first.nextSibling == null) {
                  p.removeChild(first);
                  p.appendChild(p.ownerDocument.createTextNode(s));
                } else {
                  var next = first.nextSibling;
                  p.removeChild(first);
                  p.insertBefore(p.ownerDocument.createTextNode(s), next);
                }
              } else {
                first.nodeValue = s;
              }
              if (m == null) {
                break;
              }
            } else if (m.nodeType == NodeTypes.ELEMENT_NODE) {
              Utilities.coalesceText(m);
            }
          }
        };
        Utilities.instance_of = function(o, c) {
          while (o != null) {
            if (o.constructor === c) {
              return true;
            }
            if (o === Object) {
              return false;
            }
            o = o.constructor.superclass;
          }
          return false;
        };
        Utilities.getElementById = function(n, id) {
          if (n.nodeType == NodeTypes.ELEMENT_NODE) {
            if (n.getAttribute("id") == id || n.getAttributeNS(null, "id") == id) {
              return n;
            }
          }
          for (var m = n.firstChild; m != null; m = m.nextSibling) {
            var res = Utilities.getElementById(m, id);
            if (res != null) {
              return res;
            }
          }
          return null;
        };
        var XPathException = (function() {
          function getMessage(code, exception) {
            var msg = exception ? ": " + exception.toString() : "";
            switch (code) {
              case XPathException2.INVALID_EXPRESSION_ERR:
                return "Invalid expression" + msg;
              case XPathException2.TYPE_ERR:
                return "Type error" + msg;
            }
            return null;
          }
          function XPathException2(code, error, message) {
            var err = Error.call(this, getMessage(code, error) || message);
            err.code = code;
            err.exception = error;
            return err;
          }
          XPathException2.prototype = Object.create(Error.prototype);
          XPathException2.prototype.constructor = XPathException2;
          XPathException2.superclass = Error;
          XPathException2.prototype.toString = function() {
            return this.message;
          };
          XPathException2.fromMessage = function(message, error) {
            return new XPathException2(null, error, message);
          };
          XPathException2.INVALID_EXPRESSION_ERR = 51;
          XPathException2.TYPE_ERR = 52;
          return XPathException2;
        })();
        XPathExpression.prototype = {};
        XPathExpression.prototype.constructor = XPathExpression;
        XPathExpression.superclass = Object.prototype;
        function XPathExpression(e, r, p) {
          this.xpath = p.parse(e);
          this.context = new XPathContext();
          this.context.namespaceResolver = new XPathNSResolverWrapper(r);
        }
        XPathExpression.getOwnerDocument = function(n) {
          return n.nodeType === NodeTypes.DOCUMENT_NODE ? n : n.ownerDocument;
        };
        XPathExpression.detectHtmlDom = function(n) {
          if (!n) {
            return false;
          }
          var doc = XPathExpression.getOwnerDocument(n);
          try {
            return doc.implementation.hasFeature("HTML", "2.0");
          } catch (e) {
            return true;
          }
        };
        XPathExpression.prototype.evaluate = function(n, t, res) {
          this.context.expressionContextNode = n;
          this.context.caseInsensitive = XPathExpression.detectHtmlDom(n);
          var result = this.xpath.evaluate(this.context);
          return new XPathResult2(result, t);
        };
        XPathNSResolverWrapper.prototype = {};
        XPathNSResolverWrapper.prototype.constructor = XPathNSResolverWrapper;
        XPathNSResolverWrapper.superclass = Object.prototype;
        function XPathNSResolverWrapper(r) {
          this.xpathNSResolver = r;
        }
        XPathNSResolverWrapper.prototype.getNamespace = function(prefix, n) {
          if (this.xpathNSResolver == null) {
            return null;
          }
          return this.xpathNSResolver.lookupNamespaceURI(prefix);
        };
        NodeXPathNSResolver.prototype = {};
        NodeXPathNSResolver.prototype.constructor = NodeXPathNSResolver;
        NodeXPathNSResolver.superclass = Object.prototype;
        function NodeXPathNSResolver(n) {
          this.node = n;
          this.namespaceResolver = new NamespaceResolver();
        }
        NodeXPathNSResolver.prototype.lookupNamespaceURI = function(prefix) {
          return this.namespaceResolver.getNamespace(prefix, this.node);
        };
        XPathResult2.prototype = {};
        XPathResult2.prototype.constructor = XPathResult2;
        XPathResult2.superclass = Object.prototype;
        function XPathResult2(v, t) {
          if (t == XPathResult2.ANY_TYPE) {
            if (v.constructor === XString) {
              t = XPathResult2.STRING_TYPE;
            } else if (v.constructor === XNumber) {
              t = XPathResult2.NUMBER_TYPE;
            } else if (v.constructor === XBoolean) {
              t = XPathResult2.BOOLEAN_TYPE;
            } else if (v.constructor === XNodeSet) {
              t = XPathResult2.UNORDERED_NODE_ITERATOR_TYPE;
            }
          }
          this.resultType = t;
          switch (t) {
            case XPathResult2.NUMBER_TYPE:
              this.numberValue = v.numberValue();
              return;
            case XPathResult2.STRING_TYPE:
              this.stringValue = v.stringValue();
              return;
            case XPathResult2.BOOLEAN_TYPE:
              this.booleanValue = v.booleanValue();
              return;
            case XPathResult2.ANY_UNORDERED_NODE_TYPE:
            case XPathResult2.FIRST_ORDERED_NODE_TYPE:
              if (v.constructor === XNodeSet) {
                this.singleNodeValue = v.first();
                return;
              }
              break;
            case XPathResult2.UNORDERED_NODE_ITERATOR_TYPE:
            case XPathResult2.ORDERED_NODE_ITERATOR_TYPE:
              if (v.constructor === XNodeSet) {
                this.invalidIteratorState = false;
                this.nodes = v.toArray();
                this.iteratorIndex = 0;
                return;
              }
              break;
            case XPathResult2.UNORDERED_NODE_SNAPSHOT_TYPE:
            case XPathResult2.ORDERED_NODE_SNAPSHOT_TYPE:
              if (v.constructor === XNodeSet) {
                this.nodes = v.toArray();
                this.snapshotLength = this.nodes.length;
                return;
              }
              break;
          }
          throw new XPathException(XPathException.TYPE_ERR);
        }
        ;
        XPathResult2.prototype.iterateNext = function() {
          if (this.resultType != XPathResult2.UNORDERED_NODE_ITERATOR_TYPE && this.resultType != XPathResult2.ORDERED_NODE_ITERATOR_TYPE) {
            throw new XPathException(XPathException.TYPE_ERR);
          }
          return this.nodes[this.iteratorIndex++];
        };
        XPathResult2.prototype.snapshotItem = function(i) {
          if (this.resultType != XPathResult2.UNORDERED_NODE_SNAPSHOT_TYPE && this.resultType != XPathResult2.ORDERED_NODE_SNAPSHOT_TYPE) {
            throw new XPathException(XPathException.TYPE_ERR);
          }
          return this.nodes[i];
        };
        XPathResult2.ANY_TYPE = 0;
        XPathResult2.NUMBER_TYPE = 1;
        XPathResult2.STRING_TYPE = 2;
        XPathResult2.BOOLEAN_TYPE = 3;
        XPathResult2.UNORDERED_NODE_ITERATOR_TYPE = 4;
        XPathResult2.ORDERED_NODE_ITERATOR_TYPE = 5;
        XPathResult2.UNORDERED_NODE_SNAPSHOT_TYPE = 6;
        XPathResult2.ORDERED_NODE_SNAPSHOT_TYPE = 7;
        XPathResult2.ANY_UNORDERED_NODE_TYPE = 8;
        XPathResult2.FIRST_ORDERED_NODE_TYPE = 9;
        function installDOM3XPathSupport(doc, p) {
          doc.createExpression = function(e, r) {
            try {
              return new XPathExpression(e, r, p);
            } catch (e2) {
              throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, e2);
            }
          };
          doc.createNSResolver = function(n) {
            return new NodeXPathNSResolver(n);
          };
          doc.evaluate = function(e, cn, r, t, res) {
            if (t < 0 || t > 9) {
              throw { code: 0, toString: function() {
                return "Request type not supported";
              } };
            }
            return doc.createExpression(e, r, p).evaluate(cn, t, res);
          };
        }
        ;
        try {
          var shouldInstall = true;
          try {
            if (document.implementation && document.implementation.hasFeature && document.implementation.hasFeature("XPath", null)) {
              shouldInstall = false;
            }
          } catch (e) {
          }
          if (shouldInstall) {
            installDOM3XPathSupport(document, new XPathParser());
          }
        } catch (e) {
        }
        installDOM3XPathSupport(exports3, new XPathParser());
        (function() {
          var parser = new XPathParser();
          var defaultNSResolver = new NamespaceResolver();
          var defaultFunctionResolver = new FunctionResolver();
          var defaultVariableResolver = new VariableResolver();
          function makeNSResolverFromFunction(func) {
            return {
              getNamespace: function(prefix, node) {
                var ns = func(prefix, node);
                return ns || defaultNSResolver.getNamespace(prefix, node);
              }
            };
          }
          function makeNSResolverFromObject(obj) {
            return makeNSResolverFromFunction(obj.getNamespace.bind(obj));
          }
          function makeNSResolverFromMap(map2) {
            return makeNSResolverFromFunction(function(prefix) {
              return map2[prefix];
            });
          }
          function makeNSResolver(resolver) {
            if (resolver && typeof resolver.getNamespace === "function") {
              return makeNSResolverFromObject(resolver);
            }
            if (typeof resolver === "function") {
              return makeNSResolverFromFunction(resolver);
            }
            if (typeof resolver === "object") {
              return makeNSResolverFromMap(resolver);
            }
            return defaultNSResolver;
          }
          function convertValue(value) {
            if (value === null || typeof value === "undefined" || value instanceof XString || value instanceof XBoolean || value instanceof XNumber || value instanceof XNodeSet) {
              return value;
            }
            switch (typeof value) {
              case "string":
                return new XString(value);
              case "boolean":
                return new XBoolean(value);
              case "number":
                return new XNumber(value);
            }
            var ns = new XNodeSet();
            ns.addArray([].concat(value));
            return ns;
          }
          function makeEvaluator(func) {
            return function(context) {
              var args = Array.prototype.slice.call(arguments, 1).map(function(arg) {
                return arg.evaluate(context);
              });
              var result = func.apply(this, [].concat(context, args));
              return convertValue(result);
            };
          }
          function makeFunctionResolverFromFunction(func) {
            return {
              getFunction: function(name2, namespace) {
                var found = func(name2, namespace);
                if (found) {
                  return makeEvaluator(found);
                }
                return defaultFunctionResolver.getFunction(name2, namespace);
              }
            };
          }
          function makeFunctionResolverFromObject(obj) {
            return makeFunctionResolverFromFunction(obj.getFunction.bind(obj));
          }
          function makeFunctionResolverFromMap(map2) {
            return makeFunctionResolverFromFunction(function(name2) {
              return map2[name2];
            });
          }
          function makeFunctionResolver(resolver) {
            if (resolver && typeof resolver.getFunction === "function") {
              return makeFunctionResolverFromObject(resolver);
            }
            if (typeof resolver === "function") {
              return makeFunctionResolverFromFunction(resolver);
            }
            if (typeof resolver === "object") {
              return makeFunctionResolverFromMap(resolver);
            }
            return defaultFunctionResolver;
          }
          function makeVariableResolverFromFunction(func) {
            return {
              getVariable: function(name2, namespace) {
                var value = func(name2, namespace);
                return convertValue(value);
              }
            };
          }
          function makeVariableResolver(resolver) {
            if (resolver) {
              if (typeof resolver.getVariable === "function") {
                return makeVariableResolverFromFunction(resolver.getVariable.bind(resolver));
              }
              if (typeof resolver === "function") {
                return makeVariableResolverFromFunction(resolver);
              }
              if (typeof resolver === "object") {
                return makeVariableResolverFromFunction(function(name2) {
                  return resolver[name2];
                });
              }
            }
            return defaultVariableResolver;
          }
          function copyIfPresent(prop, dest, source) {
            if (prop in source) {
              dest[prop] = source[prop];
            }
          }
          function makeContext(options) {
            var context = new XPathContext();
            if (options) {
              context.namespaceResolver = makeNSResolver(options.namespaces);
              context.functionResolver = makeFunctionResolver(options.functions);
              context.variableResolver = makeVariableResolver(options.variables);
              context.expressionContextNode = options.node;
              copyIfPresent("allowAnyNamespaceForNoPrefix", context, options);
              copyIfPresent("isHtml", context, options);
            } else {
              context.namespaceResolver = defaultNSResolver;
            }
            return context;
          }
          function evaluate(parsedExpression, options) {
            var context = makeContext(options);
            return parsedExpression.evaluate(context);
          }
          var evaluatorPrototype = {
            evaluate: function(options) {
              return evaluate(this.expression, options);
            },
            evaluateNumber: function(options) {
              return this.evaluate(options).numberValue();
            },
            evaluateString: function(options) {
              return this.evaluate(options).stringValue();
            },
            evaluateBoolean: function(options) {
              return this.evaluate(options).booleanValue();
            },
            evaluateNodeSet: function(options) {
              return this.evaluate(options).nodeset();
            },
            select: function(options) {
              return this.evaluateNodeSet(options).toArray();
            },
            select1: function(options) {
              return this.select(options)[0];
            }
          };
          function parse(xpath2) {
            var parsed = parser.parse(xpath2);
            return Object.create(evaluatorPrototype, {
              expression: {
                value: parsed
              }
            });
          }
          exports3.parse = parse;
        })();
        assign(
          exports3,
          {
            XPath,
            XPathParser,
            XPathResult: XPathResult2,
            Step,
            PathExpr,
            NodeTest,
            LocationPath,
            OrOperation,
            AndOperation,
            BarOperation,
            EqualsOperation,
            NotEqualOperation,
            LessThanOperation,
            GreaterThanOperation,
            LessThanOrEqualOperation,
            GreaterThanOrEqualOperation,
            PlusOperation,
            MinusOperation,
            MultiplyOperation,
            DivOperation,
            ModOperation,
            UnaryMinusOperation,
            FunctionCall,
            VariableReference,
            XPathContext,
            XNodeSet,
            XBoolean,
            XString,
            XNumber,
            NamespaceResolver,
            FunctionResolver,
            VariableResolver,
            Utilities
          }
        );
        exports3.select = function(e, doc, single) {
          return exports3.selectWithResolver(e, doc, null, single);
        };
        exports3.useNamespaces = function(mappings) {
          var resolver = {
            mappings: mappings || {},
            lookupNamespaceURI: function(prefix) {
              return this.mappings[prefix];
            }
          };
          return function(e, doc, single) {
            return exports3.selectWithResolver(e, doc, resolver, single);
          };
        };
        exports3.selectWithResolver = function(e, doc, resolver, single) {
          var expression = new XPathExpression(e, resolver, new XPathParser());
          var type = XPathResult2.ANY_TYPE;
          var result = expression.evaluate(doc, type, null);
          if (result.resultType == XPathResult2.STRING_TYPE) {
            result = result.stringValue;
          } else if (result.resultType == XPathResult2.NUMBER_TYPE) {
            result = result.numberValue;
          } else if (result.resultType == XPathResult2.BOOLEAN_TYPE) {
            result = result.booleanValue;
          } else {
            result = result.nodes;
            if (single) {
              result = result[0];
            }
          }
          return result;
        };
        exports3.select1 = function(e, doc) {
          return exports3.select(e, doc, true);
        };
        var isArrayOfNodes = function(value) {
          return Array.isArray(value) && value.every(isNodeLike);
        };
        var isNodeOfType = function(type) {
          return function(value) {
            return isNodeLike(value) && value.nodeType === type;
          };
        };
        assign(
          exports3,
          {
            isNodeLike,
            isArrayOfNodes,
            isElement: isNodeOfType(NodeTypes.ELEMENT_NODE),
            isAttribute: isNodeOfType(NodeTypes.ATTRIBUTE_NODE),
            isTextNode: isNodeOfType(NodeTypes.TEXT_NODE),
            isCDATASection: isNodeOfType(NodeTypes.CDATA_SECTION_NODE),
            isProcessingInstruction: isNodeOfType(NodeTypes.PROCESSING_INSTRUCTION_NODE),
            isComment: isNodeOfType(NodeTypes.COMMENT_NODE),
            isDocumentNode: isNodeOfType(NodeTypes.DOCUMENT_NODE),
            isDocumentTypeNode: isNodeOfType(NodeTypes.DOCUMENT_TYPE_NODE),
            isDocumentFragment: isNodeOfType(NodeTypes.DOCUMENT_FRAGMENT_NODE)
          }
        );
      })(xpath);
    }
  });

  // modules/std/data/xml.js
  var require_xml = __commonJS({
    "modules/std/data/xml.js"(exports2, module2) {
      "use strict";
      var nextId = 1;
      var nodeIds = /* @__PURE__ */ new WeakMap();
      var wrappers = /* @__PURE__ */ new WeakMap();
      function withSafeObjectPrototype(fn2) {
        const hidden = [];
        for (const name2 of ["get", "set"]) {
          const desc = Object.prototype.hasOwnProperty.call(Object.prototype, name2) ? Object.getOwnPropertyDescriptor(Object.prototype, name2) : null;
          if (desc && desc.configurable) {
            hidden.push([name2, desc]);
            delete Object.prototype[name2];
          }
        }
        try {
          return fn2();
        } finally {
          for (const [name2, desc] of hidden) {
            Object.defineProperty(Object.prototype, name2, desc);
          }
        }
      }
      function domClasses() {
        if (typeof DOMParser !== "undefined" && typeof XMLSerializer !== "undefined") {
          return { DOMParser, XMLSerializer };
        }
        return withSafeObjectPrototype(() => require_lib());
      }
      function xpathEngine() {
        if (typeof document !== "undefined" && document.evaluate) {
          return null;
        }
        return withSafeObjectPrototype(() => require_xpath());
      }
      function isPath(value) {
        return value && value.constructor && value.constructor.name === "Path" && typeof value.slurp_utf8 === "function" && typeof value.spew_utf8 === "function";
      }
      function nodeKey(node) {
        if (!nodeIds.has(node)) {
          nodeIds.set(node, nextId++);
        }
        return String(nodeIds.get(node));
      }
      function wrap(node) {
        if (!node) {
          return null;
        }
        if (wrappers.has(node)) {
          return wrappers.get(node);
        }
        let wrapped;
        if (node.nodeType === 9) {
          wrapped = new XMLDocument(node);
        } else if (node.nodeType === 1) {
          wrapped = new XMLElement(node);
        } else if (node.nodeType === 2) {
          wrapped = new DOMAttr(node);
        } else if (node.nodeType === 3 || node.nodeType === 4) {
          wrapped = new DOMText(node);
        } else if (node.nodeType === 8) {
          wrapped = new DOMComment(node);
        } else {
          wrapped = new XMLNode(node);
        }
        wrappers.set(node, wrapped);
        return wrapped;
      }
      function unwrap(value) {
        return value instanceof XMLNode ? value._node : null;
      }
      function nodeArray(list) {
        return Array.from(list || []).map(wrap).filter(Boolean);
      }
      function elementChildren(node) {
        return Array.from(node.childNodes || []).filter((child) => child.nodeType === 1);
      }
      function descendants(node, includeSelf = false) {
        const out = [];
        const visit = (current) => {
          out.push(current);
          for (const child of Array.from(current.childNodes || [])) {
            visit(child);
          }
        };
        if (includeSelf) {
          visit(node);
        } else {
          for (const child of Array.from(node.childNodes || [])) {
            visit(child);
          }
        }
        return out;
      }
      function simpleSelectorAll(node, selector) {
        const text = String(selector || "").trim();
        if (text === "") {
          return [];
        }
        if (typeof node.querySelectorAll === "function") {
          try {
            return nodeArray(node.querySelectorAll(text));
          } catch (_err) {
          }
        }
        if (text.startsWith(".")) {
          const klass = text.slice(1);
          return descendants(node, false).filter((child) => child.nodeType === 1).filter((child) => {
            const className = child.getAttribute("class");
            return className && className.split(/\s+/u).includes(klass);
          }).map(wrap);
        }
        if (typeof node.getElementsByTagName === "function") {
          return nodeArray(node.getElementsByTagName(text));
        }
        return descendants(node, false).filter((child) => child.nodeType === 1 && child.nodeName === text).map(wrap);
      }
      function evaluateBrowserXPath(node, expr, type) {
        if (typeof XPathResult === "undefined") {
          return null;
        }
        const doc = node.nodeType === 9 ? node : node.ownerDocument;
        if (!doc || typeof doc.evaluate !== "function") {
          return null;
        }
        return doc.evaluate(expr, node, null, type, null);
      }
      function findNodes(node, expr) {
        const text = String(expr || "").trim();
        if (text === "") {
          return [];
        }
        const snapshotType = typeof XPathResult !== "undefined" ? XPathResult.ORDERED_NODE_SNAPSHOT_TYPE : 0;
        const browserResult = evaluateBrowserXPath(node, text, snapshotType);
        if (browserResult) {
          const out = [];
          for (let i = 0; i < browserResult.snapshotLength; i++) {
            out.push(wrap(browserResult.snapshotItem(i)));
          }
          return out;
        }
        const xpath = xpathEngine();
        const result = xpath.select(text, node);
        return Array.isArray(result) ? nodeArray(result) : [];
      }
      function findValue(node, expr) {
        const text = String(expr || "").trim();
        if (text === "") {
          return "";
        }
        const anyType = typeof XPathResult !== "undefined" ? XPathResult.ANY_TYPE : 0;
        const browserResult = evaluateBrowserXPath(node, text, anyType);
        if (browserResult) {
          switch (browserResult.resultType) {
            case XPathResult.NUMBER_TYPE:
              return String(browserResult.numberValue);
            case XPathResult.STRING_TYPE:
              return browserResult.stringValue;
            case XPathResult.BOOLEAN_TYPE:
              return browserResult.booleanValue ? "true" : "false";
            default: {
              const found = browserResult.iterateNext();
              return found ? nodeStringValue(found) : "";
            }
          }
        }
        const xpath = xpathEngine();
        const result = xpath.select1(text, node);
        if (result == null) {
          return "";
        }
        if (typeof result === "number" || typeof result === "boolean") {
          return String(result);
        }
        if (typeof result === "string") {
          return result;
        }
        return nodeStringValue(result);
      }
      function nodeStringValue(node) {
        if (node.nodeType === 2) {
          return node.value || node.nodeValue || "";
        }
        return node.textContent || node.nodeValue || "";
      }
      function serialize(node) {
        const { XMLSerializer: XMLSerializer2 } = domClasses();
        return new XMLSerializer2().serializeToString(node);
      }
      function parseXml(text) {
        const { DOMParser: DOMParser2 } = domClasses();
        const parser = new DOMParser2();
        const doc = parser.parseFromString(String(text ?? ""), "application/xml");
        const parserError = doc.getElementsByTagName ? doc.getElementsByTagName("parsererror")[0] : null;
        if (parserError) {
          throw new Error(
            `Exception: XML.parse failed: ${nodeStringValue(parserError)}`
          );
        }
        return wrap(doc);
      }
      var XMLNode = class {
        constructor(node) {
          this._node = node;
        }
        nodeType() {
          return String(this._node.nodeType);
        }
        nodeName() {
          return this._node.nodeName || "";
        }
        nodeValue() {
          return this._node.nodeValue;
        }
        setNodeValue(value) {
          this._node.nodeValue = String(value ?? "");
          return this;
        }
        data() {
          return this._node.data ?? this.nodeValue();
        }
        setData(value) {
          this._node.data = String(value ?? "");
          return this;
        }
        nodeKind() {
          switch (this._node.nodeType) {
            case 1:
              return "element";
            case 2:
              return "attr";
            case 3:
            case 4:
              return "text";
            case 8:
              return "comment";
            case 9:
              return "document";
            default:
              return "node";
          }
        }
        localName() {
          return this._node.localName || null;
        }
        namespaceURI() {
          return this._node.namespaceURI || null;
        }
        parentNode() {
          return wrap(this._node.parentNode || this._node.ownerElement || null);
        }
        ownerDocument() {
          return wrap(this._node.nodeType === 9 ? this._node : this._node.ownerDocument);
        }
        childNodes() {
          return nodeArray(this._node.childNodes);
        }
        children() {
          return elementChildren(this._node).map(wrap);
        }
        hasChildNodes() {
          return this._node.hasChildNodes && this._node.hasChildNodes() ? 1 : 0;
        }
        firstChild() {
          return wrap(this._node.firstChild);
        }
        lastChild() {
          return wrap(this._node.lastChild);
        }
        nextSibling() {
          return wrap(this._node.nextSibling);
        }
        previousSibling() {
          return wrap(this._node.previousSibling);
        }
        textContent() {
          return this._node.textContent || "";
        }
        setTextContent(value) {
          this._node.textContent = String(value ?? "");
          return this;
        }
        appendChild(node) {
          return wrap(this._node.appendChild(unwrap(node)));
        }
        prependChild(node) {
          const raw = unwrap(node);
          if (this._node.firstChild) {
            this._node.insertBefore(raw, this._node.firstChild);
          } else {
            this._node.appendChild(raw);
          }
          return node;
        }
        insertBefore(newNode, refNode) {
          this._node.insertBefore(unwrap(newNode), unwrap(refNode));
          return newNode;
        }
        replaceChild(newNode, oldNode) {
          return wrap(this._node.replaceChild(unwrap(newNode), unwrap(oldNode)));
        }
        removeChild(childNode) {
          return wrap(this._node.removeChild(unwrap(childNode)));
        }
        remove() {
          if (this._node.parentNode) {
            this._node.parentNode.removeChild(this._node);
          }
          return this;
        }
        cloneNode(deep = false) {
          return wrap(this._node.cloneNode(Boolean(deep)));
        }
        normalize() {
          this._node.normalize();
          return this;
        }
        isSameNode(other) {
          return unwrap(other) === this._node ? 1 : 0;
        }
        isEqualNode(other) {
          const raw = unwrap(other);
          if (this._node.isEqualNode) {
            return this._node.isEqualNode(raw) ? 1 : 0;
          }
          return raw && serialize(this._node) === serialize(raw) ? 1 : 0;
        }
        contains(other) {
          let cur = unwrap(other);
          while (cur) {
            if (cur === this._node) {
              return 1;
            }
            cur = cur.parentNode || cur.ownerElement || null;
          }
          return 0;
        }
        visitEach(fn2) {
          for (const node of descendants(this._node, true)) {
            fn2(wrap(node));
          }
          return this;
        }
        findFirst(fn2) {
          for (const node of descendants(this._node, false)) {
            const wrapped = wrap(node);
            if (fn2(wrapped)) {
              return wrapped;
            }
          }
          return null;
        }
        findnodes(xpath) {
          return findNodes(this._node, xpath);
        }
        findvalue(xpath) {
          return findValue(this._node, xpath);
        }
        querySelectorAll(selector) {
          return simpleSelectorAll(this._node, selector);
        }
        querySelector(selector) {
          return this.querySelectorAll(selector)[0] || null;
        }
        getElementsByTagName(name2) {
          return this._node.getElementsByTagName ? nodeArray(this._node.getElementsByTagName(String(name2 || ""))) : [];
        }
        toXML(_pretty = false) {
          return serialize(this._node);
        }
        to_String() {
          return this.toXML(false);
        }
        uniqueKey() {
          return nodeKey(this._node);
        }
        unique_id() {
          return this.uniqueKey();
        }
      };
      var XMLElement = class extends XMLNode {
        tagName() {
          return this.nodeName();
        }
        id() {
          return this.getAttribute("id");
        }
        setId(value) {
          return this.setAttribute("id", value);
        }
        getAttribute(name2) {
          const value = this._node.getAttribute(String(name2 || ""));
          return value == null ? null : value;
        }
        setAttribute(name2, value) {
          this._node.setAttribute(String(name2 || ""), String(value ?? ""));
          return this;
        }
        hasAttribute(name2) {
          return this._node.hasAttribute(String(name2 || "")) ? 1 : 0;
        }
        removeAttribute(name2) {
          this._node.removeAttribute(String(name2 || ""));
          return this;
        }
        attributeNames() {
          return Array.from(this._node.attributes || []).map((attr) => attr.name);
        }
        attributes() {
          return nodeArray(this._node.attributes);
        }
      };
      var DOMAttr = class extends XMLNode {
      };
      var DOMText = class extends XMLNode {
      };
      var DOMComment = class extends XMLNode {
      };
      var XMLDocument = class extends XMLNode {
        documentElement() {
          return wrap(this._node.documentElement);
        }
        createElement(name2) {
          return wrap(this._node.createElement(String(name2 || "")));
        }
        createTextNode(text) {
          return wrap(this._node.createTextNode(String(text ?? "")));
        }
        createComment(text) {
          return wrap(this._node.createComment(String(text ?? "")));
        }
        createCDATASection(text) {
          return wrap(this._node.createCDATASection(String(text ?? "")));
        }
        getElementById(id) {
          if (typeof this._node.getElementById === "function") {
            return wrap(this._node.getElementById(String(id || "")));
          }
          return this.findFirst(
            (node) => node instanceof XMLElement && node.getAttribute("id") === String(id || "")
          );
        }
      };
      var XML = {
        parse(text) {
          return parseXml(text);
        },
        load(pathValue) {
          if (!isPath(pathValue)) {
            throw new Error("TypeException: XML.load expects Path as first argument");
          }
          return parseXml(pathValue.slurp_utf8());
        },
        dump(pathValue, value, pretty = false) {
          if (!isPath(pathValue)) {
            throw new Error("TypeException: XML.dump expects Path as first argument");
          }
          const xml = value && typeof value.toXML === "function" ? value.toXML(pretty) : String(value ?? "");
          pathValue.spew_utf8(xml);
          return pathValue;
        }
      };
      module2.exports = {
        XML,
        XMLDocument,
        XMLNode,
        DOMNode: XMLNode,
        DOMElement: XMLElement,
        DOMAttr,
        DOMText,
        DOMComment,
        DOMDocument: XMLDocument
      };
    }
  });

  // modules/std/digest/md5.js
  var require_md5 = __commonJS({
    "modules/std/digest/md5.js"(exports2, module2) {
      "use strict";
      var {
        bytesToBase64,
        bytesToHex,
        digestBytes: digestBytes2,
        toBinary
      } = require_hash();
      function md5(value) {
        return toBinary(digestBytes2("md5", value, "md5"));
      }
      function md5_hex(value) {
        return bytesToHex(digestBytes2("md5", value, "md5_hex"));
      }
      function md5_b64(value) {
        return bytesToBase64(digestBytes2("md5", value, "md5_b64"));
      }
      module2.exports = {
        md5,
        md5_hex,
        md5_b64
      };
    }
  });

  // modules/std/digest/sha.js
  var require_sha = __commonJS({
    "modules/std/digest/sha.js"(exports2, module2) {
      "use strict";
      var {
        bytesToBase64,
        bytesToHex,
        digestBytes: digestBytes2,
        hmacBytes: hmacBytes2,
        toBinary
      } = require_hash();
      function digestFn(algorithm, fnName) {
        return (value) => {
          return toBinary(digestBytes2(algorithm, value, fnName));
        };
      }
      function digestHexFn(algorithm, fnName) {
        return (value) => {
          return bytesToHex(digestBytes2(algorithm, value, fnName));
        };
      }
      function digestB64Fn(algorithm, fnName) {
        return (value) => {
          return bytesToBase64(digestBytes2(algorithm, value, fnName));
        };
      }
      function hmacFn(algorithm, fnName) {
        return (value, key) => {
          return toBinary(hmacBytes2(algorithm, value, key, fnName));
        };
      }
      function hmacHexFn(algorithm, fnName) {
        return (value, key) => {
          return bytesToHex(hmacBytes2(algorithm, value, key, fnName));
        };
      }
      function hmacB64Fn(algorithm, fnName) {
        return (value, key) => {
          return bytesToBase64(hmacBytes2(algorithm, value, key, fnName));
        };
      }
      module2.exports = {
        sha1: digestFn("sha1", "sha1"),
        sha224: digestFn("sha224", "sha224"),
        sha256: digestFn("sha256", "sha256"),
        sha384: digestFn("sha384", "sha384"),
        sha512: digestFn("sha512", "sha512"),
        sha1_hex: digestHexFn("sha1", "sha1_hex"),
        sha224_hex: digestHexFn("sha224", "sha224_hex"),
        sha256_hex: digestHexFn("sha256", "sha256_hex"),
        sha384_hex: digestHexFn("sha384", "sha384_hex"),
        sha512_hex: digestHexFn("sha512", "sha512_hex"),
        sha1_b64: digestB64Fn("sha1", "sha1_b64"),
        sha256_b64: digestB64Fn("sha256", "sha256_b64"),
        sha512_b64: digestB64Fn("sha512", "sha512_b64"),
        hmac_sha1: hmacFn("sha1", "hmac_sha1"),
        hmac_sha224: hmacFn("sha224", "hmac_sha224"),
        hmac_sha256: hmacFn("sha256", "hmac_sha256"),
        hmac_sha384: hmacFn("sha384", "hmac_sha384"),
        hmac_sha512: hmacFn("sha512", "hmac_sha512"),
        hmac_sha1_hex: hmacHexFn("sha1", "hmac_sha1_hex"),
        hmac_sha224_hex: hmacHexFn("sha224", "hmac_sha224_hex"),
        hmac_sha256_hex: hmacHexFn("sha256", "hmac_sha256_hex"),
        hmac_sha384_hex: hmacHexFn("sha384", "hmac_sha384_hex"),
        hmac_sha512_hex: hmacHexFn("sha512", "hmac_sha512_hex"),
        hmac_sha256_b64: hmacB64Fn("sha256", "hmac_sha256_b64")
      };
    }
  });

  // modules/std/net/http.js
  var require_http = __commonJS({
    "modules/std/net/http.js"(exports2, module2) {
      "use strict";
      var nodeSpawnSync;
      var nodeSpawnLoaded = false;
      var nodeFs;
      var nodeHttps;
      var nodeOs;
      var nodePath;
      var hostName2 = null;
      var { Task, traceBlockingOperation } = require_task();
      function _nodeSpawnSync() {
        if (nodeSpawnLoaded) {
          return nodeSpawnSync;
        }
        nodeSpawnLoaded = true;
        if (typeof __require !== "function") {
          nodeSpawnSync = null;
          return nodeSpawnSync;
        }
        try {
          nodeSpawnSync = __require("node:child_process").spawnSync;
        } catch (_err) {
          nodeSpawnSync = null;
        }
        return nodeSpawnSync;
      }
      function _nodeModule(name2) {
        if (typeof __require !== "function") {
          return null;
        }
        try {
          return __require(name2);
        } catch (_err) {
          return null;
        }
      }
      function _nodeFs() {
        nodeFs = nodeFs || _nodeModule("node:fs");
        return nodeFs;
      }
      function _nodeHttps() {
        nodeHttps = nodeHttps || _nodeModule("node:https");
        return nodeHttps;
      }
      function _nodeOs() {
        nodeOs = nodeOs || _nodeModule("node:os");
        return nodeOs;
      }
      function _nodePath() {
        nodePath = nodePath || _nodeModule("node:path");
        return nodePath;
      }
      function _toDict(value) {
        if (value == null) {
          return {};
        }
        if (value && Array.isArray(value.list)) {
          const out = {};
          for (const pair of value.list) {
            if (Array.isArray(pair) && pair.length >= 2) {
              out[String(pair[0])] = pair[1];
            }
          }
          return out;
        }
        if (typeof value !== "object" || Array.isArray(value)) {
          return {};
        }
        return { ...value };
      }
      function _decorateDict(value) {
        if (value == null || typeof value !== "object" || Array.isArray(value)) {
          return value;
        }
        if (!Object.prototype.hasOwnProperty.call(value, "get")) {
          Object.defineProperty(value, "get", {
            value(key, fallback = null) {
              return Object.prototype.hasOwnProperty.call(this, String(key)) ? this[String(key)] : fallback;
            },
            enumerable: false,
            configurable: true,
            writable: true
          });
        }
        return value;
      }
      function _syncUnsupportedResponse(spec) {
        return new Response({
          status: 599,
          reason: "Synchronous HTTP is unsupported on JS/Browser",
          url: _urlWithQuery(spec.url, spec.query),
          content: "",
          headers: {},
          success: false
        });
      }
      function _urlWithQuery(url, query) {
        const queryMap = _toDict(query);
        const keys = Object.keys(queryMap);
        if (keys.length === 0) {
          return String(url);
        }
        const usp = new URLSearchParams();
        for (const key of keys.sort()) {
          usp.set(key, queryMap[key] == null ? "" : String(queryMap[key]));
        }
        const base = String(url);
        return `${base}${base.includes("?") ? "&" : "?"}${usp.toString()}`;
      }
      function _maxRedirect(spec, uaConfig) {
        const value = spec.max_redirect ?? uaConfig.max_redirect ?? 10;
        const number = Number(value);
        return Number.isFinite(number) && number >= 0 ? Math.floor(number) : 10;
      }
      function _writeDownload(spec, content) {
        if (spec.download_to === void 0) {
          return;
        }
        const fs = _nodeFs();
        if (!fs) {
          throw new Error("Exception: download_to filesystem support is unavailable");
        }
        fs.writeFileSync(String(spec.download_to), content, "utf8");
      }
      var CookieJar = class {
        constructor() {
          this._cookies = /* @__PURE__ */ new Map();
        }
        add(url, setCookie) {
          this._cookies.set(String(url ?? ""), String(setCookie ?? ""));
          return this;
        }
        cookie_header(url) {
          return this._cookies.get(String(url ?? "")) ?? null;
        }
        clear() {
          this._cookies.clear();
          return this;
        }
      };
      var Response = class {
        constructor(payload) {
          this._payload = payload;
        }
        status() {
          return this._payload.status;
        }
        reason() {
          return this._payload.reason;
        }
        url() {
          return this._payload.url;
        }
        content() {
          return this._payload.content;
        }
        headers() {
          return { ...this._payload.headers };
        }
        header(name2) {
          return this._payload.headers[String(name2).toLowerCase()] ?? null;
        }
        success() {
          return this._payload.success ? 1 : 0;
        }
        json() {
          return JSON.parse(this._payload.content || "");
        }
        expect_success() {
          if (this.success()) {
            return this;
          }
          throw new Error(`HTTP request failed with status ${this.status()}`);
        }
        to_Dict() {
          return _decorateDict({
            status: this.status(),
            reason: this.reason(),
            url: this.url(),
            content: this.content(),
            headers: _decorateDict(this.headers()),
            success: this.success()
          });
        }
      };
      var Request = class {
        constructor(method, url) {
          this._spec = {
            method: String(method || "GET").toUpperCase(),
            url: String(url || ""),
            headers: {}
          };
        }
        method(value) {
          this._spec.method = String(value).toUpperCase();
          return this;
        }
        url(value) {
          this._spec.url = String(value);
          return this;
        }
        header(name2, value) {
          this._spec.headers[String(name2).toLowerCase()] = String(value);
          return this;
        }
        headers(value) {
          for (const [key, item] of Object.entries(_toDict(value))) {
            this.header(key, item);
          }
          return this;
        }
        query(value) {
          this._spec.query = _toDict(value);
          return this;
        }
        body(value) {
          this._spec.body = value == null ? "" : String(value);
          return this;
        }
        json(value) {
          this._spec.json = value;
          this._spec.headers["content-type"] = this._spec.headers["content-type"] || "application/json";
          return this;
        }
        auth_bearer(token) {
          return this.header("authorization", `Bearer ${token}`);
        }
        timeout(value) {
          this._spec.timeout = Number(value);
          return this;
        }
        retries(value) {
          this._spec.retries = Number(value);
          return this;
        }
        max_redirect(value) {
          this._spec.max_redirect = Number(value);
          return this;
        }
        download_to(value) {
          this._spec.download_to = String(value);
          return this;
        }
        upload_from(value) {
          this._spec.upload_from = String(value);
          return this;
        }
        tls_identity(value) {
          this._spec.tls_identity = value ?? null;
          return this;
        }
        multipart(value) {
          this._spec.multipart = _toDict(value);
          return this;
        }
        send(ua) {
          if (!(ua instanceof UserAgent)) {
            throw new Error("Request.send expects a UserAgent");
          }
          return ua.send(this);
        }
        send_async(ua) {
          if (!(ua instanceof UserAgent)) {
            throw new Error("Request.send_async expects a UserAgent");
          }
          return ua.send_async(this);
        }
      };
      function _derToPem(label, der) {
        const bytes = der instanceof Uint8Array ? der : der && der.bytes instanceof Uint8Array ? der.bytes : Uint8Array.from(der || []);
        const base642 = Buffer.from(bytes).toString("base64");
        const lines = base642.match(/.{1,64}/gu) || [];
        return `-----BEGIN ${label}-----
${lines.join("\n")}
-----END ${label}-----
`;
      }
      function _certificatePem(value, label) {
        if (value == null) {
          return "";
        }
        if (typeof value === "string") {
          if (!value.includes("-----BEGIN CERTIFICATE-----")) {
            throw new Error(`${label} expects PEM certificate text`);
          }
          return value;
        }
        if (value && value.__secureCertificate) {
          return _derToPem("CERTIFICATE", value.__secureCertificate.der);
        }
        throw new Error(`TypeException: ${label} expects Certificate, String PEM, or Array`);
      }
      function _caPem(value, label) {
        if (value == null) {
          return null;
        }
        if (Array.isArray(value)) {
          return value.map((item) => _certificatePem(item, label)).join("");
        }
        return _certificatePem(value, label);
      }
      function _tlsPolicy(spec, uaConfig) {
        const config = _toDict(uaConfig);
        const policy = {
          tls_identity: Object.prototype.hasOwnProperty.call(spec, "tls_identity") ? spec.tls_identity : config.tls_identity ?? null,
          tls_ca: config.tls_ca ?? null,
          tls_verify: Object.prototype.hasOwnProperty.call(config, "tls_verify") ? Boolean(config.tls_verify) : true,
          tls_server_name: config.tls_server_name ?? null,
          tls_min_version: config.tls_min_version ?? null,
          tls_ciphers: config.tls_ciphers ?? null
        };
        policy.active = Boolean(
          policy.tls_identity || policy.tls_ca || policy.tls_verify === false || policy.tls_server_name || policy.tls_min_version || policy.tls_ciphers
        );
        return policy;
      }
      function _assertBrowserTlsSupported(policy) {
        if (hostName2 === "browser" && policy.active) {
          throw new Error(
            "std/net/http TLS client configuration is not supported on JS/Browser"
          );
        }
      }
      function _identityState(identity, label) {
        if (!identity || !identity.__secureTlsIdentity) {
          throw new Error(`TypeException: ${label} expects TlsIdentity`);
        }
        return identity.__secureTlsIdentity;
      }
      function _tlsMinVersion(value) {
        if (value == null) {
          return void 0;
        }
        const text = String(value).toLowerCase();
        if (text === "tls1.2") {
          return "TLSv1.2";
        }
        if (text === "tls1.3") {
          return "TLSv1.3";
        }
        throw new Error("std/net/http tls_min_version must be 'tls1.2' or 'tls1.3'");
      }
      function _writeTempFile(content, files) {
        const fs = _nodeFs();
        const os = _nodeOs();
        const path = _nodePath();
        if (!fs || !os || !path) {
          throw new Error("Exception: temporary TLS file support is unavailable");
        }
        const dir = fs.mkdtempSync(path.join(os.tmpdir(), "zuzu-http-tls-"));
        const file = path.join(dir, "material.pem");
        fs.writeFileSync(file, content);
        files.push(file, dir);
        return file;
      }
      function _cleanupTempFiles(files) {
        const fs = _nodeFs();
        if (!fs) {
          return;
        }
        for (const file of files) {
          try {
            if (fs.statSync(file).isDirectory()) {
              fs.rmdirSync(file);
            } else {
              fs.unlinkSync(file);
            }
          } catch (_err) {
          }
        }
      }
      function _curlRequest(spec, uaConfig) {
        const spawnSync = _nodeSpawnSync();
        if (!spawnSync) {
          throw new Error("Exception: curl transport is unavailable");
        }
        const policy = _tlsPolicy(spec, uaConfig);
        if (policy.tls_server_name) {
          throw new Error(
            "std/net/http tls_server_name is not supported by the synchronous JS/Node HTTP backend"
          );
        }
        const method = String(spec.method || "GET").toUpperCase();
        const target = _urlWithQuery(spec.url, spec.query);
        const args = [
          "-sS",
          "-i",
          "-L",
          "--max-redirs",
          String(_maxRedirect(spec, uaConfig)),
          "-w",
          "\n\n__ZUZU_EFFECTIVE_URL:%{url_effective}",
          "-X",
          method,
          target
        ];
        const tempFiles = [];
        const headers = { ..._toDict(uaConfig.default_headers), ..._toDict(spec.headers) };
        if (uaConfig.agent) {
          headers["user-agent"] = String(uaConfig.agent);
        }
        if (uaConfig.cookie_jar && typeof uaConfig.cookie_jar.cookie_header === "function") {
          const cookie = uaConfig.cookie_jar.cookie_header(target);
          if (cookie) {
            headers.cookie = cookie;
          }
        }
        for (const [name2, value] of Object.entries(headers)) {
          args.push("-H", `${name2}: ${String(value)}`);
        }
        if (spec.json !== void 0) {
          args.push("--data", JSON.stringify(spec.json));
        } else if (spec.upload_from !== void 0) {
          args.push("--data-binary", `@${String(spec.upload_from)}`);
        } else if (spec.body !== void 0) {
          args.push("--data", String(spec.body));
        }
        if (policy.tls_identity) {
          const identity = _identityState(
            policy.tls_identity,
            "std/net/http tls_identity"
          );
          args.push("--cert", _writeTempFile(
            identity.certPem,
            tempFiles
          ));
          args.push("--key", _writeTempFile(identity.keyPem, tempFiles));
        }
        if (policy.tls_ca) {
          args.push("--cacert", _writeTempFile(
            _caPem(policy.tls_ca, "std/net/http tls_ca"),
            tempFiles
          ));
        }
        if (policy.tls_verify === false) {
          args.push("--insecure");
        }
        if (policy.tls_min_version) {
          args.push(
            String(policy.tls_min_version).toLowerCase() === "tls1.3" ? "--tlsv1.3" : "--tlsv1.2"
          );
        }
        if (policy.tls_ciphers) {
          args.push("--ciphers", String(policy.tls_ciphers));
        }
        let spawned;
        try {
          spawned = spawnSync("curl", args, { encoding: "utf8" });
        } finally {
          _cleanupTempFiles(tempFiles);
        }
        if (spawned.error) {
          throw spawned.error;
        }
        let raw = String(spawned.stdout || "");
        let effectiveUrl = target;
        const effectiveMatch = raw.match(/\n\n__ZUZU_EFFECTIVE_URL:([^\n\r]*)\s*$/u);
        if (effectiveMatch) {
          effectiveUrl = effectiveMatch[1] || target;
          raw = raw.slice(0, effectiveMatch.index);
        }
        const split = raw.split(/\r?\n\r?\n/u);
        let headerIndex = 0;
        for (let i = 0; i < split.length; i++) {
          if (/^HTTP\/\d(?:\.\d)?\s+\d+/u.test(split[i] || "")) {
            headerIndex = i;
          }
        }
        const headerText = split[headerIndex] || "";
        const body = split.slice(headerIndex + 1).join("\n\n");
        const headerLines = headerText.split(/\r?\n/u);
        const statusLine = headerLines.shift() || "HTTP/1.1 599 Request Failed";
        const statusMatch = statusLine.match(/^HTTP\/\d(?:\.\d)?\s+(\d+)(?:\s+(.*))?$/u);
        const status = statusMatch ? Number(statusMatch[1]) : 599;
        const reason = statusMatch ? statusMatch[2] || "" : "Request Failed";
        const outHeaders = {};
        for (const line of headerLines) {
          const idx = line.indexOf(":");
          if (idx < 0) {
            continue;
          }
          outHeaders[line.slice(0, idx).trim().toLowerCase()] = line.slice(idx + 1).trim();
        }
        if (outHeaders["set-cookie"] && uaConfig.cookie_jar && typeof uaConfig.cookie_jar.add === "function") {
          uaConfig.cookie_jar.add(effectiveUrl, outHeaders["set-cookie"]);
        }
        _writeDownload(spec, body);
        return new Response({
          status,
          reason,
          url: effectiveUrl,
          content: body,
          headers: outHeaders,
          success: status >= 200 && status < 300
        });
      }
      function _nodeHttpsRequest(spec, uaConfig, signal = null) {
        const https = _nodeHttps();
        if (!https) {
          throw new Error("Exception: https transport is unavailable");
        }
        const policy = _tlsPolicy(spec, uaConfig);
        const method = String(spec.method || "GET").toUpperCase();
        const target = _urlWithQuery(spec.url, spec.query);
        const url = new URL(target);
        if (url.protocol !== "https:") {
          throw new Error("std/net/http TLS configuration requires an https URL");
        }
        const headers = { ..._toDict(uaConfig.default_headers), ..._toDict(spec.headers) };
        if (uaConfig.agent) {
          headers["user-agent"] = String(uaConfig.agent);
        }
        if (uaConfig.cookie_jar && typeof uaConfig.cookie_jar.cookie_header === "function") {
          const cookie = uaConfig.cookie_jar.cookie_header(target);
          if (cookie) {
            headers.cookie = cookie;
          }
        }
        const body = spec.json !== void 0 ? JSON.stringify(spec.json) : spec.body !== void 0 ? String(spec.body) : null;
        if (spec.json !== void 0) {
          headers["content-type"] = headers["content-type"] || "application/json";
        }
        const options = {
          method,
          headers,
          rejectUnauthorized: policy.tls_verify !== false
        };
        if (policy.tls_identity) {
          const identity = _identityState(
            policy.tls_identity,
            "std/net/http tls_identity"
          );
          options.cert = identity.chainPem || identity.certPem;
          options.key = identity.keyPem;
          if (identity.password) {
            options.passphrase = identity.password;
          }
        }
        if (policy.tls_ca) {
          options.ca = _caPem(policy.tls_ca, "std/net/http tls_ca");
        }
        if (policy.tls_server_name) {
          options.servername = String(policy.tls_server_name);
        }
        if (policy.tls_min_version) {
          options.minVersion = _tlsMinVersion(policy.tls_min_version);
        }
        if (policy.tls_ciphers) {
          options.ciphers = String(policy.tls_ciphers);
        }
        return new Promise((resolve, reject) => {
          const req = https.request(url, options, (response) => {
            const chunks = [];
            response.on("data", (chunk) => chunks.push(chunk));
            response.on("end", () => {
              const outHeaders = {};
              for (const [name2, value] of Object.entries(response.headers)) {
                outHeaders[String(name2).toLowerCase()] = Array.isArray(value) ? value.join(", ") : String(value ?? "");
              }
              if (outHeaders["set-cookie"] && uaConfig.cookie_jar && typeof uaConfig.cookie_jar.add === "function") {
                uaConfig.cookie_jar.add(target, outHeaders["set-cookie"]);
              }
              const content = Buffer.concat(chunks).toString("utf8");
              _writeDownload(spec, content);
              resolve(new Response({
                status: response.statusCode || 599,
                reason: response.statusMessage || "",
                url: target,
                content,
                headers: outHeaders,
                success: (response.statusCode || 0) >= 200 && (response.statusCode || 0) < 300
              }));
            });
          });
          req.on("error", reject);
          if (signal) {
            signal.addEventListener("abort", () => req.destroy(
              new Error("HTTP request cancelled")
            ));
          }
          if (body != null) {
            req.write(body);
          }
          req.end();
        });
      }
      async function _fetchRequest(spec, uaConfig, signal = null) {
        if (typeof fetch !== "function") {
          throw new Error("Exception: fetch transport is unavailable");
        }
        const method = String(spec.method || "GET").toUpperCase();
        const target = _urlWithQuery(spec.url, spec.query);
        const headers = { ..._toDict(uaConfig.default_headers), ..._toDict(spec.headers) };
        if (uaConfig.agent) {
          headers["user-agent"] = String(uaConfig.agent);
        }
        if (uaConfig.cookie_jar && typeof uaConfig.cookie_jar.cookie_header === "function") {
          const cookie = uaConfig.cookie_jar.cookie_header(target);
          if (cookie) {
            headers.cookie = cookie;
          }
        }
        const fetchOptions = {
          method,
          headers
        };
        if (signal) {
          fetchOptions.signal = signal;
        }
        if (spec.json !== void 0) {
          headers["content-type"] = headers["content-type"] || "application/json";
          fetchOptions.body = JSON.stringify(spec.json);
        } else if (spec.body !== void 0) {
          fetchOptions.body = String(spec.body);
        }
        const response = await fetch(target, {
          ...fetchOptions,
          redirect: _maxRedirect(spec, uaConfig) === 0 ? "manual" : "follow"
        });
        const outHeaders = {};
        if (response.headers && typeof response.headers.forEach === "function") {
          response.headers.forEach((value, key) => {
            outHeaders[String(key).toLowerCase()] = String(value);
          });
        }
        if (outHeaders["set-cookie"] && uaConfig.cookie_jar && typeof uaConfig.cookie_jar.add === "function") {
          uaConfig.cookie_jar.add(target, outHeaders["set-cookie"]);
        }
        const content = await response.text();
        _writeDownload(spec, content);
        return new Response({
          status: response.status,
          reason: response.statusText || "",
          url: response.url || target,
          content,
          headers: outHeaders,
          success: response.ok
        });
      }
      async function _asyncRequest(spec, uaConfig, signal = null) {
        try {
          const policy = _tlsPolicy(spec, uaConfig);
          _assertBrowserTlsSupported(policy);
          if (hostName2 !== "browser" && policy.active) {
            return await _nodeHttpsRequest(spec, uaConfig, signal);
          }
          if (typeof fetch === "function") {
            return await _fetchRequest(spec, uaConfig, signal);
          }
          if (hostName2 !== "browser" && String(_urlWithQuery(spec.url, spec.query)).startsWith("https:") && _nodeHttps()) {
            return await _nodeHttpsRequest(spec, uaConfig, signal);
          }
          return _curlRequest(spec, uaConfig);
        } catch (err) {
          return new Response({
            status: 599,
            reason: err && err.message ? err.message : String(err || "Request Failed"),
            url: _urlWithQuery(spec.url, spec.query),
            content: "",
            headers: {},
            success: false
          });
        }
      }
      var UserAgent = class {
        constructor(options = {}, named = {}) {
          this._config = { ..._toDict(options), ..._toDict(named) };
        }
        build_request(method, url) {
          return new Request(method, url);
        }
        send(request) {
          if (!(request instanceof Request)) {
            throw new Error("UserAgent.send expects a Request");
          }
          traceBlockingOperation("std/net/http UserAgent.send");
          const policy = _tlsPolicy(request._spec, this._config);
          _assertBrowserTlsSupported(policy);
          if (hostName2 === "browser") {
            return _syncUnsupportedResponse(request._spec);
          }
          if (!_nodeSpawnSync() && typeof fetch === "function") {
            return _fetchRequest(request._spec, this._config);
          }
          return _curlRequest(request._spec, this._config);
        }
        send_async(request) {
          if (!(request instanceof Request)) {
            throw new Error("UserAgent.send_async expects a Request");
          }
          const timeoutSeconds = Number(
            request._spec.timeout || this._config.timeout || 0
          );
          const controller = typeof AbortController === "function" ? new AbortController() : null;
          let timer = null;
          const task = new Task(
            () => _asyncRequest(
              request._spec,
              this._config,
              controller ? controller.signal : null
            ),
            {
              name: "http.request",
              cancel() {
                if (timer != null) {
                  clearTimeout(timer);
                  timer = null;
                }
                if (controller) {
                  controller.abort();
                }
              }
            }
          );
          if (timeoutSeconds > 0 && controller) {
            timer = setTimeout(() => {
              controller.abort();
            }, Math.floor(timeoutSeconds * 1e3));
            task.finally(() => {
              if (timer != null) {
                clearTimeout(timer);
                timer = null;
              }
            });
          }
          return task;
        }
        request(method, url, data, headers) {
          const req = this.build_request(method, url);
          if (method === "POST" || method === "PUT" || method === "PATCH") {
            if (data !== void 0) {
              req.body(data);
            }
            if (headers !== void 0) {
              req.headers(headers);
            }
          } else {
            if (data !== void 0) {
              req.headers(data);
            }
          }
          return this.send(req);
        }
        request_async(method, url, data, headers) {
          const req = this.build_request(method, url);
          if (method === "POST" || method === "PUT" || method === "PATCH") {
            if (data !== void 0) {
              req.body(data);
            }
            if (headers !== void 0) {
              req.headers(headers);
            }
          } else if (data !== void 0) {
            req.headers(data);
          }
          return this.send_async(req);
        }
        get(url, headers) {
          return this.request("GET", url, headers);
        }
        get_async(url, headers) {
          return this.request_async("GET", url, headers);
        }
        head(url, headers) {
          return this.request("HEAD", url, headers);
        }
        head_async(url, headers) {
          return this.request_async("HEAD", url, headers);
        }
        delete(url, headers) {
          return this.request("DELETE", url, headers);
        }
        delete_async(url, headers) {
          return this.request_async("DELETE", url, headers);
        }
        options(url, headers) {
          return this.request("OPTIONS", url, headers);
        }
        options_async(url, headers) {
          return this.request_async("OPTIONS", url, headers);
        }
        post(url, data, headers) {
          return this.request("POST", url, data, headers);
        }
        post_async(url, data, headers) {
          return this.request_async("POST", url, data, headers);
        }
        put(url, data, headers) {
          return this.request("PUT", url, data, headers);
        }
        put_async(url, data, headers) {
          return this.request_async("PUT", url, data, headers);
        }
        patch(url, data, headers) {
          return this.request("PATCH", url, data, headers);
        }
        patch_async(url, data, headers) {
          return this.request_async("PATCH", url, data, headers);
        }
      };
      var api = {
        CookieJar,
        Request,
        Response,
        UserAgent
      };
      Object.defineProperty(api, "__zuzu_set_runtime_policy", {
        value(policy = {}) {
          hostName2 = policy.host_name || null;
        },
        enumerable: false
      });
      module2.exports = api;
    }
  });

  // modules/std/math.js
  var require_math = __commonJS({
    "modules/std/math.js"(exports2, module2) {
      "use strict";
      var PI = Math.PI;
      function normalizeNumberArgs(values) {
        if (values.length === 1 && Array.isArray(values[0])) {
          return values[0];
        }
        return values;
      }
      var ZMath = {
        pi() {
          return PI;
        },
        sin(value) {
          return Math.sin(Number(value ?? 0));
        },
        cos(value) {
          return Math.cos(Number(value ?? 0));
        },
        tan(value) {
          return Math.tan(Number(value ?? 0));
        },
        asin(value) {
          return Math.asin(Number(value ?? 0));
        },
        acos(value) {
          return Math.acos(Number(value ?? 0));
        },
        atan(value) {
          return Math.atan(Number(value ?? 0));
        },
        atan2(y, x) {
          return Math.atan2(Number(y ?? 0), Number(x ?? 0));
        },
        pow(base, exp) {
          return Math.pow(Number(base ?? 0), Number(exp ?? 0));
        },
        exp(value) {
          return Math.exp(Number(value ?? 0));
        },
        log(value) {
          return Math.log(Number(value ?? 0));
        },
        log10(value) {
          return Math.log10(Number(value ?? 0));
        },
        min(...values) {
          return Math.min(...normalizeNumberArgs(values).map(Number));
        },
        max(...values) {
          return Math.max(...normalizeNumberArgs(values).map(Number));
        },
        sum(...values) {
          return normalizeNumberArgs(values).map(Number).reduce((acc, v) => acc + v, 0);
        },
        clamp(value, low, high) {
          return Math.min(Number(high ?? 0), Math.max(Number(low ?? 0), Number(value ?? 0)));
        },
        hypot(...values) {
          return Math.hypot(...values.map(Number));
        },
        deg2rad(degrees) {
          return Number(degrees ?? 0) * (PI / 180);
        },
        rad2deg(radians) {
          return Number(radians ?? 0) * (180 / PI);
        },
        rand() {
          return Math.random();
        },
        hex2dec(value) {
          return convertBase(value, 16, 10);
        },
        hex2oct(value) {
          return convertBase(value, 16, 8);
        },
        hex2bin(value) {
          return convertBase(value, 16, 2);
        },
        dec2hex(value) {
          return convertBase(value, 10, 16);
        },
        dec2oct(value) {
          return convertBase(value, 10, 8);
        },
        dec2bin(value) {
          return convertBase(value, 10, 2);
        },
        oct2hex(value) {
          return convertBase(value, 8, 16);
        },
        oct2dec(value) {
          return convertBase(value, 8, 10);
        },
        oct2bin(value) {
          return convertBase(value, 8, 2);
        },
        bin2hex(value) {
          return convertBase(value, 2, 16);
        },
        bin2dec(value) {
          return convertBase(value, 2, 10);
        },
        bin2oct(value) {
          return convertBase(value, 2, 8);
        }
      };
      function normalizeDigits(value, base) {
        let text = String(value ?? "").trim().toLowerCase();
        if (base === 16) {
          text = text.replace(/^0x/u, "");
        } else if (base === 8) {
          text = text.replace(/^0o/u, "");
        } else if (base === 2) {
          text = text.replace(/^0b/u, "");
        }
        return text;
      }
      function convertBase(value, fromBase, toBase) {
        const text = normalizeDigits(value, fromBase);
        if (text === "") {
          return "0";
        }
        const num = Number.parseInt(text, fromBase);
        if (Number.isNaN(num)) {
          return "0";
        }
        return num.toString(toBase);
      }
      module2.exports = {
        Math: ZMath,
        pi: PI,
        \u03C0: PI
      };
    }
  });

  // modules/std/math/bignum.js
  var require_bignum = __commonJS({
    "modules/std/math/bignum.js"(exports2, module2) {
      "use strict";
      var BigNum = class _BigNum {
        constructor(value, text = null, isInt = null) {
          if (typeof value === "bigint") {
            this._value = value;
            this._text = text == null ? String(value) : String(text);
            this._isInt = isInt == null ? true : Boolean(isInt);
            return;
          }
          this._value = Number(value ?? 0);
          this._text = text == null ? String(this._value) : String(text);
          this._isInt = isInt == null ? Number.isInteger(this._value) : Boolean(isInt);
        }
        static _coerce(value) {
          if (value instanceof _BigNum) {
            return value;
          }
          if (typeof value === "string") {
            return _BigNum.from_dec(value);
          }
          return new _BigNum(Number(value ?? 0));
        }
        static from_dec(value) {
          const text = String(value ?? "0").trim();
          const safeText = text || "0";
          if (_BigNum._isIntegerText(safeText)) {
            return new _BigNum(BigInt(safeText), safeText, true);
          }
          return new _BigNum(Number(safeText), safeText, !/[.eE]/.test(safeText));
        }
        static from_hex(value) {
          const text = String(value ?? "0").trim().replace(/^0x/u, "").toLowerCase() || "0";
          const negative = text.startsWith("-");
          const digits = text.replace(/^[+-]/u, "");
          const parsed = BigInt(`0x${digits}`) * (negative ? -1n : 1n);
          return new _BigNum(parsed, String(parsed), true);
        }
        is_int() {
          return this._isInt;
        }
        _toBigInt() {
          if (!this._isInt) {
            return null;
          }
          if (typeof this._value === "bigint") {
            return this._value;
          }
          try {
            return BigInt(this._text);
          } catch {
            return null;
          }
        }
        _toNumber() {
          return typeof this._value === "bigint" ? Number(this._value) : this._value;
        }
        bcmp(other) {
          const rhs = _BigNum._coerce(other);
          const lhsBigInt = this._toBigInt();
          const rhsBigInt = rhs._toBigInt();
          if (lhsBigInt !== null && rhsBigInt !== null) {
            return lhsBigInt < rhsBigInt ? -1 : lhsBigInt > rhsBigInt ? 1 : 0;
          }
          return this._toNumber() < rhs._toNumber() ? -1 : this._toNumber() > rhs._toNumber() ? 1 : 0;
        }
        beq(other) {
          return this.bcmp(other) === 0;
        }
        bne(other) {
          return this.bcmp(other) !== 0;
        }
        blt(other) {
          return this.bcmp(other) < 0;
        }
        ble(other) {
          return this.bcmp(other) <= 0;
        }
        bgt(other) {
          return this.bcmp(other) > 0;
        }
        bge(other) {
          return this.bcmp(other) >= 0;
        }
        babs() {
          const value = this._toBigInt();
          if (value !== null) {
            return new _BigNum(value < 0n ? -value : value, String(value < 0n ? -value : value), this._isInt);
          }
          return new _BigNum(Math.abs(this._toNumber()), String(Math.abs(this._toNumber())), this._isInt);
        }
        bneg() {
          const value = this._toBigInt();
          if (value !== null) {
            return new _BigNum(-value, String(-value), this._isInt);
          }
          return new _BigNum(-this._toNumber(), String(-this._toNumber()), this._isInt);
        }
        binv() {
          return new _BigNum(1 / this._toNumber());
        }
        bsin() {
          return new _BigNum(Math.sin(this._toNumber()), String(Math.sin(this._toNumber())), false);
        }
        bcos() {
          return new _BigNum(Math.cos(this._toNumber()));
        }
        btan() {
          return new _BigNum(Math.tan(this._toNumber()), String(Math.tan(this._toNumber())), false);
        }
        bsqrt() {
          return new _BigNum(Math.sqrt(this._toNumber()));
        }
        bround() {
          return new _BigNum(Math.round(this._toNumber()));
        }
        bfloor() {
          return new _BigNum(Math.floor(this._toNumber()));
        }
        bceil() {
          return new _BigNum(Math.ceil(this._toNumber()));
        }
        badd(other) {
          const rhs = _BigNum._coerce(other);
          const lhsInt = this._toBigInt();
          const rhsInt = rhs._toBigInt();
          if (lhsInt !== null && rhsInt !== null) {
            return new _BigNum(lhsInt + rhsInt, String(lhsInt + rhsInt), false);
          }
          return new _BigNum(this._toNumber() + rhs._toNumber(), String(this._toNumber() + rhs._toNumber()), false);
        }
        bsub(other) {
          const rhs = _BigNum._coerce(other);
          const lhsInt = this._toBigInt();
          const rhsInt = rhs._toBigInt();
          if (lhsInt !== null && rhsInt !== null) {
            return new _BigNum(lhsInt - rhsInt, String(lhsInt - rhsInt), false);
          }
          return new _BigNum(this._toNumber() - rhs._toNumber(), String(this._toNumber() - rhs._toNumber()), false);
        }
        bmul(other) {
          const rhs = _BigNum._coerce(other);
          const lhsInt = this._toBigInt();
          const rhsInt = rhs._toBigInt();
          if (lhsInt !== null && rhsInt !== null) {
            return new _BigNum(lhsInt * rhsInt, String(lhsInt * rhsInt), false);
          }
          return new _BigNum(this._toNumber() * rhs._toNumber(), String(this._toNumber() * rhs._toNumber()), false);
        }
        bdiv(other) {
          const rhs = _BigNum._coerce(other);
          return new _BigNum(this._toNumber() / rhs._toNumber());
        }
        bmod(other) {
          const rhs = _BigNum._coerce(other);
          const lhsInt = this._toBigInt();
          const rhsInt = rhs._toBigInt();
          if (lhsInt !== null && rhsInt !== null && rhsInt !== 0n) {
            return new _BigNum(lhsInt % rhsInt, String(lhsInt % rhsInt), true);
          }
          return new _BigNum(this._toNumber() % rhs._toNumber());
        }
        bpow(other) {
          const rhs = _BigNum._coerce(other);
          const lhsInt = this._toBigInt();
          const rhsInt = rhs._toBigInt();
          if (lhsInt !== null && rhsInt !== null && rhsInt >= 0n) {
            let base = lhsInt;
            let power = rhsInt;
            let result = 1n;
            while (power > 0n) {
              if (power & 1n) {
                result *= base;
              }
              power >>= 1n;
              if (power > 0n) {
                base *= base;
              }
            }
            return new _BigNum(result, String(result), true);
          }
          return new _BigNum(this._toNumber() ** rhs._toNumber());
        }
        to_hex() {
          const value = this._toBigInt();
          if (value === null) {
            return `0x${Math.trunc(this._toNumber()).toString(16)}`;
          }
          if (value === 0n) {
            return "0x0";
          }
          const absolute = value < 0n ? -value : value;
          return value < 0n ? `-0x${absolute.toString(16)}` : `0x${absolute.toString(16)}`;
        }
        to_dec() {
          return this._textify();
        }
        to_String() {
          return this.to_dec();
        }
        toString() {
          return String(this.to_String());
        }
        to_Number() {
          return this._toNumber();
        }
        static _isIntegerText(text) {
          return /^[+-]?(?:\d+)$/u.test(text);
        }
        _textify() {
          if (this._text != null && /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/u.test(this._text)) {
            return this._text.replace(/\.0+$/u, "").replace(/(\.\d*?)0+$/u, "$1").replace(/\.$/u, "");
          }
          return this._toBigInt() !== null ? this._toBigInt().toString() : String(this._value);
        }
      };
      module2.exports = {
        BigNum
      };
    }
  });

  // modules/std/eval.js
  var require_eval = __commonJS({
    "modules/std/eval.js"(exports2, module2) {
      "use strict";
      function evalZuzu(code) {
        const src = String(code ?? "");
        return (0, eval)(src);
      }
      module2.exports = {
        eval: evalZuzu
      };
    }
  });

  // modules/std/gui/objects.js
  var require_objects = __commonJS({
    "modules/std/gui/objects.js"(exports2, module2) {
      "use strict";
      var {
        makeWeakValue,
        retainValue,
        releaseValue,
        resolveWeakValue
      } = require_runtime_helpers();
      var runtimePolicy2 = {
        deny_gui: true,
        gui: null,
        host_name: "node"
      };
      var meta = {
        backend: "electron-dom",
        font_size_pixels: 16,
        font_name: "system-ui",
        font_point_size: 12
      };
      var nextWidgetId = 1;
      function _getProp(props, key, fallback = null) {
        if (props && typeof props.get === "function") {
          return props.get(key, fallback);
        }
        if (props && Object.prototype.hasOwnProperty.call(props, key)) {
          return props[key];
        }
        return fallback;
      }
      function _setProp(props, key, value) {
        if (props && typeof props.set === "function") {
          if (typeof props.remove === "function") {
            props.remove(key);
          }
          props.set(key, value);
          return;
        }
        props[key] = value;
      }
      function _getChildren(props) {
        const children = _getProp(props, "children", []);
        return Array.isArray(children) ? children : [];
      }
      function _asBool(value) {
        return value ? true : false;
      }
      function _asArray(value) {
        return Array.isArray(value) ? value : [];
      }
      function _itemChildren(item) {
        if (item && typeof item === "object") {
          if (typeof item.get === "function") {
            return _asArray(item.get("children", []));
          }
          if (Array.isArray(item.children)) {
            return item.children;
          }
        }
        return [];
      }
      function _isMenuKind(value) {
        return value instanceof Menu || value instanceof MenuItem;
      }
      function _weak(value) {
        return makeWeakValue(value);
      }
      function _resolve(value) {
        return resolveWeakValue(value);
      }
      function _retainDispatchPath(path) {
        for (const widget of path) {
          retainValue(widget);
        }
      }
      function _releaseDispatchPath(path) {
        for (const widget of path) {
          releaseValue(widget);
        }
      }
      var ListenerToken = class {
        constructor(widget, type, id) {
          this.widget = _weak(widget);
          this.type = String(type);
          this.id = id;
        }
      };
      var Event = class {
        constructor(props = {}) {
          this.__zuzu_name = String(props.name || props.type || "");
          this.__zuzu_target = _weak(props.target || null);
          this.__zuzu_current_target = _weak(props.current_target || null);
          this.__zuzu_timestamp = Date.now() / 1e3;
          this.__zuzu_data = Object.prototype.hasOwnProperty.call(props, "data") ? props.data : null;
          this.__zuzu_value = Object.prototype.hasOwnProperty.call(props, "value") ? props.value : null;
          this.__zuzu_cancelled = false;
          this.__zuzu_propagation_stopped = false;
          this.__zuzu_default_prevented = false;
          this.__zuzu_phase = "";
        }
        name() {
          return this.__zuzu_name;
        }
        type() {
          return this.__zuzu_name;
        }
        target() {
          return _resolve(this.__zuzu_target);
        }
        current_target() {
          return _resolve(this.__zuzu_current_target);
        }
        currentTarget() {
          return _resolve(this.__zuzu_current_target);
        }
        phase() {
          return this.__zuzu_phase;
        }
        timestamp() {
          return this.__zuzu_timestamp;
        }
        data() {
          return this.__zuzu_data;
        }
        value() {
          return this.__zuzu_value;
        }
        cancelled() {
          return this.__zuzu_cancelled;
        }
        propagation_stopped() {
          return this.__zuzu_propagation_stopped;
        }
        default_prevented() {
          return this.__zuzu_default_prevented;
        }
        window() {
          const target = _resolve(this.__zuzu_target);
          return target instanceof Widget ? target.__zuzu_owner_window_live() : null;
        }
        stop_propagation() {
          this.__zuzu_propagation_stopped = true;
          this.__zuzu_cancelled = true;
          return this;
        }
        prevent_default() {
          this.__zuzu_default_prevented = true;
          this.__zuzu_cancelled = true;
          return this;
        }
      };
      var Widget = class _Widget {
        constructor(props = {}) {
          this.__zuzu_gui_id = `w${nextWidgetId++}`;
          this.__zuzu_gui_type = this.__zuzu_gui_type_name || this.constructor.name;
          this.__zuzu_props = props || {};
          this.__zuzu_parent = _weak(null);
          this.__zuzu_event_parent = null;
          this.__zuzu_children = [];
          this.__zuzu_listeners = /* @__PURE__ */ new Map();
          this.__zuzu_listener_seq = 0;
          this.__zuzu_meta = /* @__PURE__ */ Object.create(null);
          this.__zuzu_style = /* @__PURE__ */ Object.create(null);
          this.__zuzu_classes = [];
          for (const child of _getChildren(this.__zuzu_props)) {
            this.add_child(child);
          }
        }
        id(value) {
          if (arguments.length === 0) {
            return _getProp(this.__zuzu_props, "id", null);
          }
          _setProp(this.__zuzu_props, "id", value == null ? null : String(value));
          this.__zuzu_update_native();
          return this;
        }
        set_id(value) {
          return this.id(value);
        }
        parent() {
          return _resolve(this.__zuzu_parent);
        }
        children() {
          return this.__zuzu_children.slice();
        }
        add_child(child) {
          if (child == null) {
            return this;
          }
          if (!(child instanceof _Widget)) {
            throw new Error("GUI_PROP_TYPE: add_child expects a Widget");
          }
          if (this instanceof MenuItem) {
            throw new Error("GUI_PROP_TYPE: MenuItem widgets cannot have children");
          }
          if (child instanceof Menu && !(this instanceof Window)) {
            throw new Error("GUI_PROP_TYPE: Menu widgets can only be Window children");
          }
          if (child instanceof MenuItem && !(this instanceof Menu)) {
            throw new Error("GUI_PROP_TYPE: MenuItem widgets can only be Menu children");
          }
          if (this instanceof Menu && !(child instanceof MenuItem)) {
            throw new Error("GUI_PROP_TYPE: Menu widgets can only contain MenuItem children");
          }
          const oldParent = child.parent();
          if (oldParent && oldParent !== this) {
            oldParent.remove_child(child);
          }
          if (this.__zuzu_children.includes(child)) {
            return this;
          }
          child.__zuzu_parent = _weak(this);
          child.__zuzu_event_parent = this;
          this.__zuzu_children.push(child);
          this.__zuzu_child_added(child);
          if (this instanceof Window && !_isMenuKind(child) && this.__zuzu_content == null) {
            this.__zuzu_content = child;
          }
          this.__zuzu_create_native_child(child);
          return this;
        }
        __zuzu_child_added(_child) {
        }
        remove_child(child) {
          if (!(child instanceof _Widget)) {
            return this;
          }
          const before = this.__zuzu_children.length;
          this.__zuzu_children = this.__zuzu_children.filter((item) => item !== child);
          if (this.__zuzu_children.length === before) {
            return this;
          }
          this.__zuzu_destroy_native_child(child);
          this.__zuzu_child_removed(child);
          if (child.parent() === this) {
            child.__zuzu_parent = _weak(null);
          }
          if (child.__zuzu_event_parent === this) {
            child.__zuzu_event_parent = null;
          }
          if (this instanceof Window && this.__zuzu_content === child) {
            this.__zuzu_content = this.__zuzu_children.find(
              (item) => !_isMenuKind(item)
            ) || null;
          }
          return this;
        }
        __zuzu_child_removed(_child) {
        }
        find_by_id(id) {
          if (this.id() != null && this.id() === String(id)) {
            return this;
          }
          for (const child of this.__zuzu_children) {
            const found = child.find_by_id(id);
            if (found) {
              return found;
            }
          }
          return null;
        }
        enabled(value) {
          if (arguments.length === 0) {
            return _getProp(this.__zuzu_props, "disabled", false) ? false : Boolean(_getProp(this.__zuzu_props, "enabled", true));
          }
          _setProp(this.__zuzu_props, "enabled", value ? true : false);
          _setProp(this.__zuzu_props, "disabled", value ? false : true);
          this.__zuzu_update_native();
          return this;
        }
        set_enabled(value) {
          return this.enabled(value);
        }
        disabled(value) {
          if (arguments.length === 0) {
            return this.enabled() ? false : true;
          }
          return this.enabled(value ? false : true);
        }
        visible(value) {
          if (arguments.length === 0) {
            return Boolean(_getProp(this.__zuzu_props, "visible", true));
          }
          _setProp(this.__zuzu_props, "visible", value ? true : false);
          this.__zuzu_update_native();
          return this;
        }
        set_visible(value) {
          return this.visible(value);
        }
        classes() {
          return this.__zuzu_classes.slice();
        }
        add_class(name2) {
          const key = String(name2);
          if (!this.__zuzu_classes.includes(key)) {
            this.__zuzu_classes.push(key);
            this.__zuzu_update_native();
          }
          return this;
        }
        remove_class(name2) {
          const key = String(name2);
          const before = this.__zuzu_classes.length;
          this.__zuzu_classes = this.__zuzu_classes.filter((item) => item !== key);
          if (before !== this.__zuzu_classes.length) {
            this.__zuzu_update_native();
          }
          return this;
        }
        style(key, value) {
          if (arguments.length === 0) {
            return { ...this.__zuzu_style };
          }
          const name2 = String(key);
          if (arguments.length === 1) {
            return this.__zuzu_style[name2] ?? null;
          }
          this.__zuzu_style[name2] = value;
          this.__zuzu_update_native();
          return this;
        }
        meta(key, value) {
          if (arguments.length === 0) {
            return { ...this.__zuzu_meta };
          }
          const name2 = String(key);
          if (arguments.length === 1) {
            return this.__zuzu_meta[name2] ?? null;
          }
          this.__zuzu_meta[name2] = value;
          return this;
        }
        on(type, handler) {
          if (typeof handler !== "function") {
            throw new Error("GUI_EVENT_HANDLER: on expects a Function handler");
          }
          const name2 = String(type);
          const id = ++this.__zuzu_listener_seq;
          if (!this.__zuzu_listeners.has(name2)) {
            this.__zuzu_listeners.set(name2, []);
          }
          this.__zuzu_listeners.get(name2).push({
            id,
            handler,
            once: false
          });
          return new ListenerToken(this, name2, id);
        }
        once(type, handler) {
          if (typeof handler !== "function") {
            throw new Error("GUI_EVENT_HANDLER: once expects a Function handler");
          }
          const name2 = String(type);
          const id = ++this.__zuzu_listener_seq;
          if (!this.__zuzu_listeners.has(name2)) {
            this.__zuzu_listeners.set(name2, []);
          }
          this.__zuzu_listeners.get(name2).push({
            id,
            handler,
            once: true
          });
          return new ListenerToken(this, name2, id);
        }
        off(token) {
          if (!(token instanceof ListenerToken) || _resolve(token.widget) !== this) {
            return false;
          }
          const listeners = this.__zuzu_listeners.get(token.type);
          if (!listeners) {
            return false;
          }
          const before = listeners.length;
          const kept = listeners.filter((listener) => listener.id !== token.id);
          this.__zuzu_listeners.set(token.type, kept);
          return kept.length !== before;
        }
        emit(type, payload = null) {
          const name2 = String(type);
          const event = payload instanceof Event ? payload : new Event({
            name: name2,
            target: this,
            data: payload,
            value: payload
          });
          event.__zuzu_name = name2;
          if (_resolve(event.__zuzu_target) == null) {
            event.__zuzu_target = _weak(this);
          }
          this.__zuzu_dispatch_event(event);
          return event;
        }
        __zuzu_dispatch_event(event) {
          const path = [];
          let current = this;
          while (current) {
            path.push(current);
            current = current.__zuzu_event_parent;
          }
          _retainDispatchPath(path);
          try {
            this.__zuzu_dispatch_at(event, "target");
            for (let i = 1; i < path.length; i++) {
              if (event.__zuzu_propagation_stopped) {
                break;
              }
              path[i].__zuzu_dispatch_at(event, "bubble");
            }
          } finally {
            _releaseDispatchPath(path);
          }
        }
        __zuzu_dispatch_at(event, phase) {
          const listeners = (this.__zuzu_listeners.get(event.__zuzu_name) || []).slice();
          if (listeners.length === 0) {
            return;
          }
          event.__zuzu_current_target = _weak(this);
          event.__zuzu_phase = phase;
          for (const listener of listeners) {
            listener.handler(event);
            if (listener.once) {
              this.off(new ListenerToken(this, event.__zuzu_name, listener.id));
            }
            if (event.__zuzu_propagation_stopped) {
              break;
            }
          }
        }
        __zuzu_owner_window() {
          let current = this;
          while (current) {
            if (current instanceof Window) {
              return current;
            }
            current = current.parent();
          }
          return null;
        }
        __zuzu_owner_window_live() {
          let current = this;
          while (current) {
            if (current instanceof Window) {
              return current;
            }
            current = current.__zuzu_event_parent;
          }
          return null;
        }
        __zuzu_create_native_child(child) {
          const window2 = this.__zuzu_owner_window_live();
          if (!window2 || window2.__zuzu_electron_window_id == null || !runtimePolicy2.gui || typeof runtimePolicy2.gui.createWidget !== "function") {
            return;
          }
          runtimePolicy2.gui.createWidget(
            window2.__zuzu_electron_window_id,
            this.__zuzu_gui_id,
            child.__zuzu_gui_snapshot(),
            this.__zuzu_children.indexOf(child)
          );
        }
        __zuzu_destroy_native_child(child) {
          const window2 = this.__zuzu_owner_window_live();
          if (!window2 || window2.__zuzu_electron_window_id == null || !runtimePolicy2.gui || typeof runtimePolicy2.gui.destroyWidget !== "function") {
            return;
          }
          runtimePolicy2.gui.destroyWidget(
            window2.__zuzu_electron_window_id,
            child.__zuzu_gui_id
          );
        }
        __zuzu_update_native() {
          const window2 = this.__zuzu_owner_window_live();
          if (!window2 || window2.__zuzu_electron_window_id == null || !runtimePolicy2.gui || typeof runtimePolicy2.gui.updateWidget !== "function") {
            return;
          }
          runtimePolicy2.gui.updateWidget(
            window2.__zuzu_electron_window_id,
            this.__zuzu_gui_snapshot()
          );
        }
        __zuzu_set_prop_silent(key, value) {
          _setProp(this.__zuzu_props, key, value);
        }
        __zuzu_find_by_guid(guid) {
          if (this.__zuzu_gui_id === guid) {
            return this;
          }
          for (const child of this.__zuzu_children) {
            const found = child.__zuzu_find_by_guid(guid);
            if (found) {
              return found;
            }
          }
          return null;
        }
        __zuzu_gui_snapshot() {
          return {
            guid: this.__zuzu_gui_id,
            type: this.__zuzu_gui_type,
            id: this.id(),
            classes: this.classes(),
            props: {
              disabled: this.disabled(),
              enabled: this.enabled(),
              visible: this.visible(),
              align: _getProp(this.__zuzu_props, "align", null),
              alt: _getProp(this.__zuzu_props, "alt", null),
              checked: _getProp(this.__zuzu_props, "checked", null),
              closable: _getProp(this.__zuzu_props, "closable", null),
              collapsible: _getProp(this.__zuzu_props, "collapsible", null),
              collapsed: _getProp(this.__zuzu_props, "collapsed", null),
              first_day_of_week: _getProp(this.__zuzu_props, "first_day_of_week", null),
              fit: _getProp(this.__zuzu_props, "fit", null),
              for_id: this.for_id ? this.for_id() : null,
              group: _getProp(this.__zuzu_props, "group", null),
              icon: _getProp(this.__zuzu_props, "icon", null),
              indeterminate: _getProp(this.__zuzu_props, "indeterminate", null),
              items: _getProp(this.__zuzu_props, "items", null),
              label: _getProp(this.__zuzu_props, "label", null),
              max: _getProp(this.__zuzu_props, "max", null),
              min: _getProp(this.__zuzu_props, "min", null),
              modal: _getProp(this.__zuzu_props, "modal", null),
              multiline: _getProp(this.__zuzu_props, "multiline", null),
              multiple: _getProp(this.__zuzu_props, "multiple", null),
              name: _getProp(this.__zuzu_props, "name", null),
              options: _getProp(this.__zuzu_props, "options", null),
              orientation: _getProp(this.__zuzu_props, "orientation", null),
              password: _getProp(this.__zuzu_props, "password", null),
              title: _getProp(this.__zuzu_props, "title", null),
              placement: _getProp(this.__zuzu_props, "placement", null),
              text: _getProp(this.__zuzu_props, "text", null),
              readonly: _getProp(this.__zuzu_props, "readonly", null),
              required: _getProp(this.__zuzu_props, "required", null),
              resizable: _getProp(this.__zuzu_props, "resizable", null),
              selected: _getProp(this.__zuzu_props, "selected", null),
              selected_index: _getProp(this.__zuzu_props, "selected_index", null),
              selected_path: _getProp(this.__zuzu_props, "selected_path", null),
              show_text: _getProp(this.__zuzu_props, "show_text", null),
              src: _getProp(this.__zuzu_props, "src", null),
              step: _getProp(this.__zuzu_props, "step", null),
              value: _getProp(this.__zuzu_props, "value", null),
              placeholder: _getProp(this.__zuzu_props, "placeholder", null),
              variant: _getProp(this.__zuzu_props, "variant", null),
              wrap: _getProp(this.__zuzu_props, "wrap", null),
              width: _getProp(this.__zuzu_props, "width", null),
              height: _getProp(this.__zuzu_props, "height", null),
              minwidth: _getProp(this.__zuzu_props, "minwidth", null),
              minheight: _getProp(this.__zuzu_props, "minheight", null),
              maxwidth: _getProp(this.__zuzu_props, "maxwidth", null),
              maxheight: _getProp(this.__zuzu_props, "maxheight", null),
              gap: _getProp(this.__zuzu_props, "gap", null),
              padding: _getProp(this.__zuzu_props, "padding", null)
            },
            children: this.__zuzu_children.map(
              (child) => child.__zuzu_gui_snapshot()
            )
          };
        }
      };
      for (const name2 of [
        "width",
        "height",
        "minwidth",
        "minheight",
        "maxwidth",
        "maxheight",
        "align",
        "alt",
        "closable",
        "collapsible",
        "collapsed",
        "first_day_of_week",
        "fit",
        "gap",
        "group",
        "icon",
        "indeterminate",
        "label",
        "max",
        "min",
        "modal",
        "multiline",
        "multiple",
        "name",
        "orientation",
        "padding",
        "password",
        "placement",
        "readonly",
        "required",
        "resizable",
        "selected",
        "show_text",
        "src",
        "step",
        "title",
        "text",
        "value",
        "placeholder",
        "variant",
        "wrap"
      ]) {
        Widget.prototype[name2] = function propAccessor(value) {
          if (arguments.length === 0) {
            return _getProp(this.__zuzu_props, name2, null);
          }
          _setProp(this.__zuzu_props, name2, value == null ? "" : value);
          this.__zuzu_update_native();
          return this;
        };
      }
      Widget.prototype.for_id = function forId(value) {
        if (arguments.length === 0) {
          return _getProp(this.__zuzu_props, "for", null);
        }
        _setProp(this.__zuzu_props, "for", value == null ? null : String(value));
        this.__zuzu_update_native();
        return this;
      };
      Widget.prototype.set_for_id = function setForId(value) {
        return this.for_id(value);
      };
      Widget.prototype.set_value = function setValue(value) {
        return this.value(value);
      };
      Widget.prototype.set_text = function setText(value) {
        return this.text(value);
      };
      Widget.prototype.set_title = function setTitle(value) {
        return this.title(value);
      };
      for (const eventName of [
        "activate",
        "blur",
        "change",
        "click",
        "close_request",
        "closed",
        "collapse",
        "enter",
        "expand",
        "focus",
        "input",
        "open",
        "resize",
        "select",
        "submit"
      ]) {
        Widget.prototype[eventName] = function eventShortcut(handler = null) {
          if (handler == null) {
            return this.emit(eventName);
          }
          return this.on(eventName, handler);
        };
      }
      var Window = class extends Widget {
        constructor(props = {}) {
          super(props);
          this.__zuzu_close_result = null;
          this.__zuzu_electron_window_id = null;
          this.__zuzu_closed = false;
          this.__zuzu_shown = false;
          this.__zuzu_native_close_allowed = false;
          this.__zuzu_close_waiters = [];
          this.__zuzu_content = _getProp(props, "content", null);
          if (this.__zuzu_content != null && (!(this.__zuzu_content instanceof Widget) || _isMenuKind(this.__zuzu_content))) {
            throw new Error("GUI_PROP_TYPE: Window content expects a non-menu Widget or null");
          }
          if (this.__zuzu_content != null && !this.__zuzu_children.includes(this.__zuzu_content)) {
            this.add_child(this.__zuzu_content);
          }
          if (this.__zuzu_content == null) {
            this.__zuzu_content = this.__zuzu_children.find(
              (child) => !_isMenuKind(child)
            ) || null;
          }
        }
        content() {
          return this.__zuzu_content;
        }
        menus() {
          return this.__zuzu_children.filter((child) => child instanceof Menu);
        }
        set_content(child = null) {
          if (child != null && (!(child instanceof Widget) || _isMenuKind(child))) {
            throw new Error("GUI_PROP_TYPE: set_content expects a non-menu Widget or null");
          }
          for (const old of this.__zuzu_children.slice()) {
            if (!_isMenuKind(old)) {
              this.remove_child(old);
            }
          }
          this.__zuzu_content = child;
          if (child != null) {
            this.add_child(child);
          }
          return this;
        }
        show() {
          if (runtimePolicy2.deny_gui || !runtimePolicy2.gui) {
            throw new Error(
              `GUI is not available on host '${runtimePolicy2.host_name}'`
            );
          }
          if (this.__zuzu_electron_window_id != null) {
            return this;
          }
          const result = runtimePolicy2.gui.openWindow(
            this.__zuzu_gui_snapshot(),
            {
              onEvent: (event) => this.__zuzu_receive_gui_event(event),
              onCloseRequest: () => this.__zuzu_native_close_request(),
              onClosed: () => this.__zuzu_native_closed()
            }
          );
          const markShown = (windowId) => {
            this.__zuzu_electron_window_id = windowId;
            this.__zuzu_shown = true;
            this.emit("open");
            return this;
          };
          if (result && typeof result.then === "function") {
            return result.then(markShown);
          }
          return markShown(result);
        }
        call(options = null) {
          const asyncCall = _getProp(options, "async", false) ? true : false;
          if (this.__zuzu_closed) {
            if (asyncCall) {
              return Promise.resolve(this.__zuzu_close_result);
            }
            return this.__zuzu_close_result;
          }
          if (runtimePolicy2.host_name === "browser" && !asyncCall) {
            throw new Error(
              "GUI_CALL_SYNC_UNSUPPORTED: Window.call requires async: true on host 'browser'"
            );
          }
          const shown = this.show();
          if (shown && typeof shown.then === "function") {
            return shown.then(() => this.__zuzu_wait_for_close());
          }
          return this.__zuzu_wait_for_close();
        }
        close(result = null) {
          return this.__zuzu_close(result, false);
        }
        __zuzu_close(result = null, nativeClose = false) {
          if (this.__zuzu_closed) {
            return this;
          }
          const request = this.emit("close_request", result);
          if (request.cancelled() || request.default_prevented()) {
            return this;
          }
          this.__zuzu_closed = true;
          this.__zuzu_close_result = result;
          if (!nativeClose && runtimePolicy2.gui && typeof runtimePolicy2.gui.closeWindow === "function" && this.__zuzu_electron_window_id != null) {
            runtimePolicy2.gui.closeWindow(this.__zuzu_electron_window_id);
          }
          this.emit("closed", result);
          this.__zuzu_resolve_close_waiters();
          return this;
        }
        __zuzu_wait_for_close() {
          if (this.__zuzu_closed) {
            return this.__zuzu_close_result;
          }
          return new Promise((resolve) => {
            this.__zuzu_close_waiters.push(resolve);
          });
        }
        __zuzu_resolve_close_waiters() {
          const waiters = this.__zuzu_close_waiters.splice(0);
          for (const resolve of waiters) {
            resolve(this.__zuzu_close_result);
          }
        }
        __zuzu_native_close_request() {
          if (this.__zuzu_closed) {
            return false;
          }
          const request = this.emit("close_request", null);
          if (request.cancelled() || request.default_prevented()) {
            return true;
          }
          this.__zuzu_native_close_allowed = true;
          return false;
        }
        __zuzu_native_closed() {
          if (this.__zuzu_closed) {
            return;
          }
          this.__zuzu_closed = true;
          this.__zuzu_close_result = null;
          this.emit("closed", null);
          this.__zuzu_resolve_close_waiters();
        }
        __zuzu_receive_gui_event(raw = {}) {
          const target = raw.widgetGuid ? this.__zuzu_find_by_guid(raw.widgetGuid) : this;
          if (!target) {
            return;
          }
          if (Object.prototype.hasOwnProperty.call(raw, "value")) {
            target.__zuzu_set_prop_silent("value", raw.value);
          }
          if (Object.prototype.hasOwnProperty.call(raw, "checked") && typeof target.checked === "function") {
            target.__zuzu_set_prop_silent("checked", raw.checked ? true : false);
          }
          if (Object.prototype.hasOwnProperty.call(raw, "selected_index") && typeof target.selected_index === "function") {
            target.__zuzu_set_prop_silent(
              "selected_index",
              raw.selected_index == null ? null : Number(raw.selected_index)
            );
          }
          if (Object.prototype.hasOwnProperty.call(raw, "selected") && typeof target.selected === "function") {
            target.__zuzu_set_prop_silent(
              "selected",
              raw.selected == null ? null : String(raw.selected)
            );
            if (target instanceof Tabs) {
              target.__zuzu_sync_tabs();
            }
          }
          if (Object.prototype.hasOwnProperty.call(raw, "selected_path") && typeof target.selected_path === "function") {
            target.__zuzu_set_prop_silent(
              "selected_path",
              _asArray(raw.selected_path).map(Number)
            );
          }
          if (target instanceof TreeView && Object.prototype.hasOwnProperty.call(raw, "selected_path") && raw.type === "expand") {
            target.__zuzu_set_expanded_silent(raw.selected_path, true);
            target.emit(raw.type, new Event({
              name: raw.type,
              target,
              data: raw,
              value: raw.selected_path
            }));
            return;
          }
          if (target instanceof TreeView && Object.prototype.hasOwnProperty.call(raw, "selected_path") && raw.type === "collapse") {
            target.__zuzu_set_expanded_silent(raw.selected_path, false);
            target.emit(raw.type, new Event({
              name: raw.type,
              target,
              data: raw,
              value: raw.selected_path
            }));
            return;
          }
          target.emit(raw.type, new Event({
            name: raw.type,
            target,
            data: raw,
            value: Object.prototype.hasOwnProperty.call(raw, "value") ? raw.value : null
          }));
        }
      };
      var VBox = class extends Widget {
      };
      var HBox = class extends Widget {
      };
      var Frame = class extends Widget {
      };
      var Label = class extends Widget {
      };
      var Text = class extends Widget {
      };
      var RichText = class extends Widget {
      };
      var Image = class extends Widget {
      };
      var Input = class extends Widget {
        constructor(props = {}) {
          if (props && typeof props.get === "function") {
            if (typeof props.has === "function" && props.has("value")) {
              const value = props.get("value");
              props.set("value", value == null ? "" : String(value));
            }
            super(props);
            return;
          }
          const cooked = { ...props };
          if (Object.prototype.hasOwnProperty.call(cooked, "value")) {
            cooked.value = cooked.value == null ? "" : String(cooked.value);
          }
          super(cooked);
        }
        value(value) {
          if (arguments.length === 0) {
            return _getProp(this.__zuzu_props, "value", null);
          }
          _setProp(this.__zuzu_props, "value", value == null ? "" : String(value));
          this.__zuzu_update_native();
          return this;
        }
        select_all() {
          this.emit("select_all");
          return this;
        }
      };
      var DatePicker = class extends Widget {
      };
      var Checkbox = class extends Widget {
        checked(value) {
          if (arguments.length === 0) {
            return _asBool(_getProp(this.__zuzu_props, "checked", false));
          }
          _setProp(this.__zuzu_props, "checked", _asBool(value));
          this.__zuzu_update_native();
          return this;
        }
      };
      var Radio = class extends Checkbox {
        checked(value) {
          if (arguments.length === 0) {
            return super.checked();
          }
          super.checked(value);
          const parent = this.parent();
          if (value && parent instanceof RadioGroup) {
            parent.value(this.value());
          }
          return this;
        }
      };
      var RadioGroup = class extends Widget {
        constructor(props = {}) {
          super(props);
          this.__zuzu_sync_radios();
        }
        options() {
          return this.children().filter((child) => child instanceof Radio);
        }
        value(value) {
          if (arguments.length === 0) {
            return _getProp(this.__zuzu_props, "value", null);
          }
          _setProp(this.__zuzu_props, "value", value == null ? null : String(value));
          this.__zuzu_sync_radios();
          this.__zuzu_update_native();
          return this;
        }
        __zuzu_child_added(child) {
          if (child instanceof Radio) {
            this.__zuzu_sync_radios();
          }
        }
        __zuzu_sync_radios() {
          const selected = this.value();
          for (const radio of this.options()) {
            _setProp(
              radio.__zuzu_props,
              "checked",
              selected != null && String(radio.value()) === String(selected)
            );
          }
        }
        __zuzu_set_prop_silent(key, value) {
          super.__zuzu_set_prop_silent(key, value);
          if (key === "value") {
            this.__zuzu_sync_radios();
          }
        }
      };
      var Select = class extends Widget {
        options() {
          return _asArray(_getProp(this.__zuzu_props, "options", [])).slice();
        }
        add_option(option) {
          const options = this.options();
          options.push(option);
          _setProp(this.__zuzu_props, "options", options);
          this.__zuzu_update_native();
          return this;
        }
        clear_options() {
          _setProp(this.__zuzu_props, "options", []);
          this.__zuzu_update_native();
          return this;
        }
      };
      var Menu = class extends Widget {
        items() {
          return this.children();
        }
      };
      var MenuItem = class extends Widget {
      };
      var Button = class extends Widget {
      };
      var Separator = class extends Widget {
      };
      var Slider = class extends Widget {
      };
      var Progress = class extends Widget {
      };
      var Tabs = class extends Widget {
        constructor(props = {}) {
          super(props);
          this.__zuzu_sync_tabs();
        }
        tabs() {
          return this.children().filter((child) => child instanceof Tab);
        }
        selected(value) {
          if (arguments.length === 0) {
            return _getProp(this.__zuzu_props, "selected", null);
          }
          _setProp(this.__zuzu_props, "selected", value == null ? null : String(value));
          this.__zuzu_sync_tabs();
          this.__zuzu_update_native();
          return this;
        }
        selected_tab() {
          const selected = this.selected();
          return this.tabs().find((tab) => String(tab.value()) === String(selected)) || null;
        }
        __zuzu_child_added(child) {
          if (child instanceof Tab) {
            this.__zuzu_sync_tabs();
          }
        }
        __zuzu_sync_tabs() {
          const selected = this.selected();
          for (const tab of this.tabs()) {
            _setProp(
              tab.__zuzu_props,
              "selected",
              selected != null && String(tab.value()) === String(selected)
            );
          }
        }
      };
      var Tab = class extends Widget {
        selected(value) {
          if (arguments.length === 0) {
            return _asBool(_getProp(this.__zuzu_props, "selected", false));
          }
          _setProp(this.__zuzu_props, "selected", _asBool(value));
          const parent = this.parent();
          if (value && parent instanceof Tabs) {
            parent.selected(this.value());
          } else {
            this.__zuzu_update_native();
          }
          return this;
        }
      };
      var ListView = class extends Widget {
        items() {
          return _asArray(_getProp(this.__zuzu_props, "items", [])).slice();
        }
        selected_index(value) {
          if (arguments.length === 0) {
            return _getProp(this.__zuzu_props, "selected_index", null);
          }
          _setProp(
            this.__zuzu_props,
            "selected_index",
            value == null ? null : Number(value)
          );
          this.__zuzu_update_native();
          return this;
        }
        selected_item() {
          const index = this.selected_index();
          const items = this.items();
          return index == null ? null : items[Number(index)] ?? null;
        }
        add_item(item) {
          const items = this.items();
          items.push(item);
          _setProp(this.__zuzu_props, "items", items);
          this.__zuzu_update_native();
          return this;
        }
        clear_items() {
          _setProp(this.__zuzu_props, "items", []);
          _setProp(this.__zuzu_props, "selected_index", null);
          this.__zuzu_update_native();
          return this;
        }
        activate_index(index) {
          this.selected_index(index);
          this.emit("activate", index);
          return this;
        }
      };
      var TreeView = class extends Widget {
        constructor(props = {}) {
          super(props);
          this.__zuzu_expanded = /* @__PURE__ */ new Set();
          this.__zuzu_mark_initial_expanded(this.items(), []);
        }
        items() {
          return _asArray(_getProp(this.__zuzu_props, "items", [])).slice();
        }
        selected_path(value) {
          if (arguments.length === 0) {
            return _asArray(_getProp(this.__zuzu_props, "selected_path", [])).slice();
          }
          _setProp(this.__zuzu_props, "selected_path", _asArray(value).map(Number));
          this.__zuzu_update_native();
          return this;
        }
        selected_item() {
          return this.__zuzu_item_at_path(this.selected_path());
        }
        add_item(item) {
          const items = this.items();
          items.push(item);
          _setProp(this.__zuzu_props, "items", items);
          this.__zuzu_update_native();
          return this;
        }
        clear_items() {
          _setProp(this.__zuzu_props, "items", []);
          _setProp(this.__zuzu_props, "selected_path", []);
          this.__zuzu_expanded.clear();
          this.__zuzu_update_native();
          return this;
        }
        activate_path(path) {
          this.selected_path(path);
          this.emit("activate", path);
          return this;
        }
        expand_path(path) {
          this.__zuzu_expanded.add(this.__zuzu_path_key(path));
          this.__zuzu_update_native();
          this.emit("expand", path);
          return this;
        }
        collapse_path(path) {
          this.__zuzu_expanded.delete(this.__zuzu_path_key(path));
          this.__zuzu_update_native();
          this.emit("collapse", path);
          return this;
        }
        is_expanded(path) {
          return this.__zuzu_expanded.has(this.__zuzu_path_key(path));
        }
        __zuzu_gui_snapshot() {
          const snapshot = super.__zuzu_gui_snapshot();
          snapshot.props.expanded_paths = [...this.__zuzu_expanded].map(
            (key) => key.split(",").filter(Boolean).map(Number)
          );
          return snapshot;
        }
        __zuzu_item_at_path(path) {
          let items = this.items();
          let current = null;
          for (const rawIndex of _asArray(path)) {
            const index = Number(rawIndex);
            current = items[index] ?? null;
            if (current == null) {
              return null;
            }
            items = _itemChildren(current);
          }
          return current;
        }
        __zuzu_path_key(path) {
          return _asArray(path).map((part) => Number(part)).join(",");
        }
        __zuzu_mark_initial_expanded(items, prefix) {
          for (let i = 0; i < items.length; i++) {
            const path = [...prefix, i];
            const children = _itemChildren(items[i]);
            if (children.length > 0) {
              this.__zuzu_expanded.add(this.__zuzu_path_key(path));
              this.__zuzu_mark_initial_expanded(children, path);
            }
          }
        }
        __zuzu_set_expanded_silent(path, expanded) {
          const key = this.__zuzu_path_key(path);
          if (expanded) {
            this.__zuzu_expanded.add(key);
          } else {
            this.__zuzu_expanded.delete(key);
          }
        }
      };
      function _nativeDialogue(name2) {
        return function nativeDialogue(first, ...rest) {
          if (runtimePolicy2.gui && typeof runtimePolicy2.gui[name2] === "function") {
            return runtimePolicy2.gui[name2](first, ...rest);
          }
          return null;
        };
      }
      function _tagGuiType(klass, names) {
        Object.defineProperty(klass.prototype, "__zuzu_gui_type_name", {
          value: names[0],
          enumerable: false,
          configurable: false
        });
        Object.defineProperty(klass.prototype, "__zuzu_type_names", {
          value: names,
          enumerable: false,
          configurable: false
        });
      }
      for (const [klass, names] of [
        [Widget, ["Widget"]],
        [Window, ["Window", "Widget"]],
        [VBox, ["VBox", "Widget"]],
        [HBox, ["HBox", "Widget"]],
        [Frame, ["Frame", "Widget"]],
        [Label, ["Label", "Widget"]],
        [Text, ["Text", "Widget"]],
        [RichText, ["RichText", "Widget"]],
        [Image, ["Image", "Widget"]],
        [Input, ["Input", "Widget"]],
        [DatePicker, ["DatePicker", "Widget"]],
        [Checkbox, ["Checkbox", "Widget"]],
        [Radio, ["Radio", "Checkbox", "Widget"]],
        [RadioGroup, ["RadioGroup", "Widget"]],
        [Select, ["Select", "Widget"]],
        [Menu, ["Menu", "Widget"]],
        [MenuItem, ["MenuItem", "Widget"]],
        [Button, ["Button", "Widget"]],
        [Separator, ["Separator", "Widget"]],
        [Slider, ["Slider", "Widget"]],
        [Progress, ["Progress", "Widget"]],
        [Tabs, ["Tabs", "Widget"]],
        [Tab, ["Tab", "Widget"]],
        [ListView, ["ListView", "Widget"]],
        [TreeView, ["TreeView", "Widget"]]
      ]) {
        _tagGuiType(klass, names);
      }
      module2.exports = {
        Widget,
        Window,
        VBox,
        HBox,
        Frame,
        Label,
        Text,
        RichText,
        Image,
        Input,
        DatePicker,
        Checkbox,
        Radio,
        RadioGroup,
        Select,
        Menu,
        MenuItem,
        Button,
        Separator,
        Slider,
        Progress,
        Tabs,
        Tab,
        ListView,
        TreeView,
        Event,
        ListenerToken,
        meta,
        native_file_open: _nativeDialogue("fileOpen"),
        native_file_save: _nativeDialogue("fileSave"),
        native_directory_open: _nativeDialogue("directoryOpen"),
        native_directory_save: _nativeDialogue("directorySave"),
        native_alert: _nativeDialogue("alert"),
        native_confirm: _nativeDialogue("confirm"),
        native_prompt: _nativeDialogue("prompt"),
        native_colour_picker: _nativeDialogue("colourPicker"),
        __zuzu_set_runtime_policy(policy = {}) {
          runtimePolicy2 = {
            ...runtimePolicy2,
            ...policy
          };
          meta.backend = runtimePolicy2.host_name === "browser" ? "browser-dom" : "electron-dom";
        }
      };
    }
  });

  // modules/std/tui.js
  var require_tui = __commonJS({
    "modules/std/tui.js"(exports2, module2) {
      "use strict";
      var stdinBuffer = null;
      var denyFs = false;
      function hasProcess() {
        return typeof process !== "undefined" && process;
      }
      function nodeRequire2(name2) {
        if (typeof __require !== "function") {
          return null;
        }
        try {
          return __require(name2);
        } catch (_err) {
          return null;
        }
      }
      function ansi_esc() {
        return "\x1B";
      }
      function supports_ansi() {
        if (!hasProcess() || process.env.NO_COLOR) {
          return 0;
        }
        if (!process.stdout || !process.stdout.isTTY) {
          return 0;
        }
        if (process.platform === "win32") {
          return process.env.ANSICON || process.env.WT_SESSION || process.env.ConEmuANSI || process.env.TERM_PROGRAM ? 1 : 0;
        }
        const term = process.env.TERM || "";
        return term && term !== "dumb" ? 1 : 0;
      }
      function ansiCode(colour) {
        switch (String(colour || "").toLowerCase()) {
          case "black":
            return 30;
          case "red":
            return 31;
          case "green":
            return 32;
          case "yellow":
            return 33;
          case "blue":
            return 34;
          case "magenta":
            return 35;
          case "cyan":
            return 36;
          case "white":
            return 37;
          default:
            return null;
        }
      }
      function colour_text(text, colour) {
        const value = text == null ? "" : String(text);
        const code = ansiCode(colour);
        if (!code || !supports_ansi()) {
          return value;
        }
        return `${ansi_esc()}[${code}m${value}${ansi_esc()}[0m`;
      }
      function output(text) {
        if (hasProcess() && process.stdout && typeof process.stdout.write === "function") {
          process.stdout.write(String(text));
          return;
        }
        if (typeof console !== "undefined" && typeof console.log === "function") {
          console.log(String(text));
        }
      }
      function write(text, colour) {
        output(colour_text(text, colour));
        return null;
      }
      function write_line(text, colour) {
        output(`${colour_text(text, colour)}
`);
        return null;
      }
      function readStdinLine() {
        const fs = nodeRequire2("node:fs") || nodeRequire2("fs");
        if (!fs) {
          return null;
        }
        if (stdinBuffer == null) {
          try {
            stdinBuffer = fs.readFileSync(0, "utf8");
          } catch (_err) {
            stdinBuffer = "";
          }
        }
        if (stdinBuffer.length === 0) {
          return null;
        }
        const match = /^([^\n\r]*)(?:\r?\n|\r)?/.exec(stdinBuffer);
        const line = match ? match[1] : stdinBuffer;
        stdinBuffer = stdinBuffer.slice(match ? match[0].length : stdinBuffer.length);
        return line;
      }
      function readline(prompt = "", defaultValue = "", _completionCallback = null) {
        if (_completionCallback != null && typeof _completionCallback !== "function") {
          throw new Error("readline completion must be Function or null");
        }
        output(prompt == null ? "" : String(prompt));
        const line = readStdinLine();
        if (line == null || line === "") {
          return defaultValue == null ? "" : String(defaultValue);
        }
        return line;
      }
      function readline_supports_completion() {
        return 0;
      }
      function pathCompletions(text, directoryOnly) {
        if (denyFs) {
          return [];
        }
        const fs = nodeRequire2("node:fs") || nodeRequire2("fs");
        const path = nodeRequire2("node:path") || nodeRequire2("path");
        if (!fs || !path) {
          return [];
        }
        const raw = text == null ? "" : String(text);
        const sepMatch = /[/\\]$/u.test(raw);
        const dir = sepMatch ? raw : path.dirname(raw || ".");
        const base = sepMatch ? "" : path.basename(raw);
        const searchDir = dir && dir !== "." ? dir : ".";
        const visibleDir = dir && dir !== "." ? dir : "";
        let entries;
        try {
          entries = fs.readdirSync(searchDir, { withFileTypes: true });
        } catch (_err) {
          return [];
        }
        return entries.filter((entry) => entry.name.startsWith(base)).filter((entry) => !directoryOnly || entry.isDirectory()).map((entry) => {
          const prefix = visibleDir ? `${visibleDir}${path.sep}` : "";
          return `${prefix}${entry.name}${entry.isDirectory() ? path.sep : ""}`;
        }).sort();
      }
      function filename_completions(text) {
        return pathCompletions(text, false);
      }
      function directory_completions(text) {
        return pathCompletions(text, true);
      }
      var api = {
        ansi_esc,
        colour_text,
        directory_completions,
        filename_completions,
        readline,
        readline_supports_completion,
        supports_ansi,
        write,
        write_line
      };
      Object.defineProperty(api, "__zuzu_set_runtime_policy", {
        value(policy = {}) {
          denyFs = !!policy.deny_fs;
        },
        enumerable: false
      });
      module2.exports = api;
    }
  });

  // modules/std/internals.js
  var require_internals = __commonJS({
    "modules/std/internals.js"(exports2, module2) {
      "use strict";
      var { getCompiledSource } = require_execution_metadata();
      var taskRuntime2 = require_task();
      var frameProps = /* @__PURE__ */ new Map();
      var refIds = /* @__PURE__ */ new WeakMap();
      var scopeTrees = /* @__PURE__ */ new Map();
      var ZUZU_SKIP_BUILD = /* @__PURE__ */ Symbol.for("zuzu.skip_build");
      var refSeq = 1;
      var nodeFs;
      var nodeFsLoaded = false;
      var runtimePolicy2 = {
        load_module: null,
        builtin_class: null,
        to_String: null,
        to_Number: null,
        to_Boolean: null,
        to_Regexp: null,
        to_Regexp_with_flags: null
      };
      function setRuntimePolicy2(policy = {}) {
        runtimePolicy2 = {
          ...runtimePolicy2,
          ...policy
        };
      }
      function _thisModuleFilename() {
        return typeof __filename === "string" ? __filename : null;
      }
      function _nodeFs() {
        if (nodeFsLoaded) {
          return nodeFs;
        }
        nodeFsLoaded = true;
        if (typeof __require !== "function") {
          nodeFs = null;
          return nodeFs;
        }
        try {
          nodeFs = __require("node:fs");
        } catch (_err) {
          nodeFs = null;
        }
        return nodeFs;
      }
      function parseUserFrames() {
        const lines = String(new Error().stack || "").split("\n").slice(1);
        const frames = [];
        for (const line of lines) {
          const trimmed = line.trim();
          let match = trimmed.match(/^at\s+(.*?)\s+\((.+):(\d+):(\d+)\)$/);
          if (!match) {
            match = trimmed.match(/^at\s+(.+):(\d+):(\d+)$/);
            if (match) {
              match = [match[0], "", match[1], match[2], match[3]];
            }
          }
          if (!match) {
            continue;
          }
          const file = match[2];
          if (file.includes("<anonymous>") || file.startsWith("eval at ")) {
            continue;
          }
          const thisFile = _thisModuleFilename();
          if (thisFile != null && file === thisFile || /[\\/]extras[\\/]zuzu-js[\\/]lib[\\/]runtime\.js$/.test(file) || /[\\/]zuzu-js[\\/]lib[\\/]runtime\.js$/.test(file) || /[\\/]zuzu-browser\.js$/.test(file) || file.startsWith("node:") || file === "[stdin]") {
            continue;
          }
          frames.push({
            func: match[1] || "",
            file,
            line: Number(match[3]),
            col: Number(match[4])
          });
        }
        return frames;
      }
      function loadScopeTree(file) {
        if (scopeTrees.has(file)) {
          return scopeTrees.get(file);
        }
        let source = "";
        const compiled = getCompiledSource(file);
        if (compiled != null) {
          source = compiled;
        } else try {
          const fs = _nodeFs();
          if (!fs) {
            throw new Error("fs unavailable");
          }
          source = fs.readFileSync(file, "utf8");
        } catch (_err) {
          const fallback = {
            nodes: [{ id: 0, parent: null, startLine: 1, endLine: Number.MAX_SAFE_INTEGER }]
          };
          scopeTrees.set(file, fallback);
          return fallback;
        }
        const nodes = [
          { id: 0, parent: null, startLine: 1, endLine: Number.MAX_SAFE_INTEGER }
        ];
        const stack = [0];
        let line = 1;
        let mode = "code";
        let quote = "";
        let escaped = false;
        let atLineStart = true;
        let inPod = false;
        for (let i = 0; i < source.length; i++) {
          const ch = source[i];
          const next = source[i + 1] || "";
          if (ch === "\n") {
            line++;
            atLineStart = true;
            if (mode === "line-comment") {
              mode = "code";
            }
            continue;
          }
          if (inPod) {
            if (atLineStart && ch === "=") {
              const end = source.indexOf("\n", i);
              const rest = source.slice(i, end === -1 ? source.length : end);
              if (/^=cut\b/.test(rest)) {
                inPod = false;
              }
            }
            atLineStart = false;
            continue;
          }
          if (atLineStart && ch === "=") {
            const end = source.indexOf("\n", i);
            const rest = source.slice(i, end === -1 ? source.length : end);
            if (/^=\w+/.test(rest) && !/^=cut\b/.test(rest)) {
              inPod = true;
              atLineStart = false;
              continue;
            }
          }
          atLineStart = false;
          if (mode === "line-comment") {
            continue;
          }
          if (mode === "block-comment") {
            if (ch === "*" && next === "/") {
              mode = "code";
              i++;
            }
            continue;
          }
          if (mode === "string") {
            if (escaped) {
              escaped = false;
              continue;
            }
            if (ch === "\\") {
              escaped = true;
              continue;
            }
            if (ch === quote) {
              mode = "code";
            }
            continue;
          }
          if (ch === "/" && next === "/") {
            mode = "line-comment";
            i++;
            continue;
          }
          if (ch === "/" && next === "*") {
            mode = "block-comment";
            i++;
            continue;
          }
          if (ch === '"' || ch === "'" || ch === "`") {
            mode = "string";
            quote = ch;
            escaped = false;
            continue;
          }
          if (ch === "{") {
            const id = nodes.length;
            nodes.push({
              id,
              parent: stack[stack.length - 1],
              startLine: line,
              endLine: Number.MAX_SAFE_INTEGER
            });
            stack.push(id);
            continue;
          }
          if (ch === "}" && stack.length > 1) {
            const id = stack.pop();
            nodes[id].endLine = line;
          }
        }
        const tree = { nodes };
        scopeTrees.set(file, tree);
        return tree;
      }
      function scopePathForLocation(file, line) {
        const tree = loadScopeTree(file);
        let current = 0;
        let found = true;
        while (found) {
          found = false;
          for (let i = tree.nodes.length - 1; i >= 1; i--) {
            const node = tree.nodes[i];
            if (node.parent !== current) {
              continue;
            }
            if (node.startLine <= line && line <= node.endLine) {
              current = node.id;
              found = true;
              break;
            }
          }
        }
        const path = [];
        let nodeId = current;
        while (nodeId != null) {
          path.push(nodeId);
          nodeId = tree.nodes[nodeId].parent;
        }
        return path;
      }
      function contextAtDepth(depth = 0) {
        const frames = parseUserFrames();
        const frame = frames[depth];
        if (!frame) {
          return null;
        }
        const isVirtualBrowserPath = runtimePolicy2.host_name === "browser";
        const line = isVirtualBrowserPath ? frame.line - 2 : frame.line;
        return {
          activationKey: `file:${frame.file}`,
          scopePath: scopePathForLocation(frame.file, Math.max(1, line))
        };
      }
      function ensureFrame(activationKey, scopeId) {
        const key = `${activationKey}#${scopeId}`;
        if (!frameProps.has(key)) {
          frameProps.set(key, /* @__PURE__ */ new Map());
        }
        return frameProps.get(key);
      }
      function getFrame(activationKey, scopeId) {
        return frameProps.get(`${activationKey}#${scopeId}`);
      }
      function class_name(value) {
        if (value == null || typeof value !== "object") {
          return null;
        }
        return value.constructor && value.constructor.name ? value.constructor.name : null;
      }
      function classof(value) {
        if (value == null) {
          return null;
        }
        if (typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
          return null;
        }
        const builtinClass = typeof runtimePolicy2.builtin_class === "function" ? runtimePolicy2.builtin_class : () => null;
        if (Array.isArray(value)) {
          return builtinClass("Array") || value.constructor || null;
        }
        if (Object.prototype.toString.call(value) === "[object Set]") {
          return builtinClass("Set") || value.constructor || null;
        }
        if (value && value.constructor) {
          const ctor = value.constructor;
          const name2 = ctor.__zuzu_class_name || ctor.name || "";
          if (name2 === "Object") {
            return builtinClass("Dict") || ctor;
          }
          if (name2 === "ZuzuBag") {
            return builtinClass("Bag") || ctor;
          }
          return ctor;
        }
        if (typeof value === "function") {
          const source = Function.prototype.toString.call(value);
          if (/^\s*class\b/.test(source)) {
            return builtinClass("Class") || Function;
          }
          return builtinClass("Function") || Function;
        }
        return null;
      }
      function object_slots(value) {
        if (value == null || typeof value !== "object") {
          return null;
        }
        const out = {};
        for (const key of Object.keys(value)) {
          if (!key.startsWith("_")) {
            out[key] = value[key];
          }
        }
        Object.defineProperty(
          out,
          "get",
          {
            value(key) {
              const id = String(key);
              return Object.prototype.hasOwnProperty.call(out, id) ? out[id] : null;
            },
            enumerable: false
          }
        );
        Object.defineProperty(
          out,
          "keys",
          {
            value() {
              return Object.keys(out);
            },
            enumerable: false
          }
        );
        Object.defineProperty(
          out,
          "sorted_keys",
          {
            value() {
              return Object.keys(out).sort();
            },
            enumerable: false
          }
        );
        return out;
      }
      function ansi_esc() {
        return "\x1B";
      }
      function ref_id(value) {
        if (value == null || typeof value !== "object" && typeof value !== "function") {
          return null;
        }
        if (!refIds.has(value)) {
          refIds.set(value, `ref:${refSeq++}`);
        }
        return refIds.get(value);
      }
      function make_instance(klass, slots = null) {
        if (typeof klass !== "function" || typeof klass.__zuzu_class_name !== "string") {
          throw new Error("make_instance expects a user class");
        }
        if (slots == null) {
          return new klass(ZUZU_SKIP_BUILD);
        }
        if (typeof slots !== "object" || Array.isArray(slots)) {
          throw new Error("make_instance slot values must be Dict");
        }
        return new klass(ZUZU_SKIP_BUILD, slots);
      }
      function currentUserFile() {
        const frame = parseUserFrames()[0];
        return frame && frame.file ? frame.file : null;
      }
      function moduleExportKeys(loaded) {
        return Reflect.ownKeys(Object(loaded)).filter((key) => typeof key === "string").filter((key) => !key.startsWith("__zuzu_"));
      }
      function load_module(moduleName, symbolName = null) {
        if (arguments.length < 1 || arguments.length > 2) {
          throw new Error("load_module expects 1 to 2 arguments");
        }
        if (typeof moduleName !== "string") {
          throw new Error("load_module module must be String");
        }
        if (symbolName != null && typeof symbolName !== "string") {
          throw new Error("load_module symbol must be String");
        }
        if (typeof runtimePolicy2.load_module !== "function") {
          throw new Error("load_module is unavailable in this runtime");
        }
        const loaded = runtimePolicy2.load_module(moduleName, currentUserFile());
        if (symbolName != null) {
          if (!Object.prototype.hasOwnProperty.call(Object(loaded), symbolName)) {
            throw new Error(`Module '${moduleName}' has no export '${symbolName}'`);
          }
          return loaded[symbolName];
        }
        const out = {};
        for (const key of moduleExportKeys(loaded)) {
          out[key] = loaded[key];
        }
        return out;
      }
      function requirePolicyFunction(name2) {
        const fn2 = runtimePolicy2[name2];
        if (typeof fn2 !== "function") {
          throw new Error(`${name2} is unavailable in this runtime`);
        }
        return fn2;
      }
      function to_String(value) {
        return requirePolicyFunction("to_String")(value);
      }
      function to_Number(value) {
        return requirePolicyFunction("to_Number")(value);
      }
      function to_Boolean(value) {
        return requirePolicyFunction("to_Boolean")(value);
      }
      function to_Regexp(value) {
        return requirePolicyFunction("to_Regexp")(value);
      }
      function to_Regexp_with_flags(value, flags) {
        return requirePolicyFunction("to_Regexp_with_flags")(value, flags);
      }
      function validateKey(key) {
        if (typeof key !== "string") {
          throw new Error("getprop|setprop key must be String");
        }
      }
      function setprop(key, value) {
        validateKey(key);
        const ctx = contextAtDepth(0);
        if (!ctx) {
          return value;
        }
        ensureFrame(ctx.activationKey, ctx.scopePath[0]).set(key, value);
        return value;
      }
      function getprop(key) {
        validateKey(key);
        const ctx = contextAtDepth(0);
        if (!ctx) {
          return null;
        }
        for (const scopeId of ctx.scopePath) {
          const frame = getFrame(ctx.activationKey, scopeId);
          if (frame && frame.has(key)) {
            return frame.get(key);
          }
        }
        return null;
      }
      function setupperprop(level, key, value) {
        validateKey(key);
        const ctx = contextAtDepth(Number(level ?? 0));
        if (!ctx) {
          return value;
        }
        ensureFrame(ctx.activationKey, ctx.scopePath[0]).set(key, value);
        return value;
      }
      function getupperprop(level, key) {
        validateKey(key);
        const ctx = contextAtDepth(Number(level ?? 0));
        if (!ctx) {
          return null;
        }
        for (const scopeId of ctx.scopePath) {
          const frame = getFrame(ctx.activationKey, scopeId);
          if (frame && frame.has(key)) {
            return frame.get(key);
          }
        }
        return null;
      }
      var api = {
        active_task_count: taskRuntime2.activeCount,
        ansi_esc,
        class_name,
        classof,
        clear_task_trace: taskRuntime2.clearTrace,
        getprop,
        getupperprop,
        load_module,
        make_instance,
        object_slots,
        ref_id,
        setprop,
        setupperprop,
        shutdown_tasks: taskRuntime2.shutdown,
        task_trace: taskRuntime2.taskTrace,
        to_Boolean,
        to_Number,
        to_Regexp,
        to_Regexp_with_flags,
        to_String
      };
      Object.defineProperty(api, "__zuzu_set_runtime_policy", {
        value: setRuntimePolicy2,
        enumerable: false,
        configurable: true,
        writable: true
      });
      module2.exports = api;
    }
  });

  // node_modules/@std-uritemplate/std-uritemplate/dist/index.cjs
  var require_dist = __commonJS({
    "node_modules/@std-uritemplate/std-uritemplate/dist/index.cjs"(exports2) {
      "use strict";
      var StdUriTemplate = class _StdUriTemplate {
        static expand(template, substitutions) {
          return _StdUriTemplate.expandImpl(template, substitutions);
        }
        static validateLiteral(c, col) {
          switch (c) {
            case "+":
            case "#":
            case "/":
            case ";":
            case "?":
            case "&":
            case " ":
            case "!":
            case "=":
            case "$":
            case "|":
            case "*":
            case ":":
            case "~":
            case "-":
              throw new Error(`Illegal character identified in the token at col: ${col}`);
          }
        }
        static getMaxChar(buffer, col) {
          if (!buffer) {
            return -1;
          } else {
            const value = buffer.join("");
            if (value.length === 0) {
              return -1;
            } else {
              try {
                return parseInt(value, 10);
              } catch (e) {
                throw new Error(`Cannot parse max chars at col: ${col}`);
              }
            }
          }
        }
        static getOperator(c, token, col) {
          switch (c) {
            case "+":
              return 1;
            case "#":
              return 2;
            case ".":
              return 3;
            case "/":
              return 4;
            case ";":
              return 5;
            case "?":
              return 6;
            case "&":
              return 7;
            default:
              _StdUriTemplate.validateLiteral(c, col);
              token.push(c);
              return 0;
          }
        }
        static expandImpl(str, substitutions) {
          const result = [];
          let token = null;
          let operator = null;
          let composite = false;
          let maxCharBuffer = null;
          let firstToken = true;
          for (let i = 0; i < str.length; i++) {
            const character = str.charAt(i);
            switch (character) {
              case "{":
                token = [];
                firstToken = true;
                break;
              case "}":
                if (token !== null) {
                  const expanded = _StdUriTemplate.expandToken(
                    operator,
                    token.join(""),
                    composite,
                    _StdUriTemplate.getMaxChar(maxCharBuffer, i),
                    firstToken,
                    substitutions,
                    result,
                    i
                  );
                  if (expanded && firstToken) {
                    firstToken = false;
                  }
                  token = null;
                  operator = null;
                  composite = false;
                  maxCharBuffer = null;
                } else {
                  throw new Error(`Failed to expand token, invalid at col: ${i}`);
                }
                break;
              case ",":
                if (token !== null) {
                  const expanded = _StdUriTemplate.expandToken(
                    operator,
                    token.join(""),
                    composite,
                    _StdUriTemplate.getMaxChar(maxCharBuffer, i),
                    firstToken,
                    substitutions,
                    result,
                    i
                  );
                  if (expanded && firstToken) {
                    firstToken = false;
                  }
                  token = [];
                  composite = false;
                  maxCharBuffer = null;
                  break;
                }
              // Intentional fall-through for commas outside the {}
              default:
                if (token !== null) {
                  if (operator === null) {
                    operator = _StdUriTemplate.getOperator(character, token, i);
                  } else if (maxCharBuffer !== null) {
                    if (character.match(/^\d$/)) {
                      maxCharBuffer.push(character);
                    } else {
                      throw new Error(`Illegal character identified in the token at col: ${i}`);
                    }
                  } else {
                    if (character === ":") {
                      maxCharBuffer = [];
                    } else if (character === "*") {
                      composite = true;
                    } else {
                      _StdUriTemplate.validateLiteral(character, i);
                      token.push(character);
                    }
                  }
                } else {
                  result.push(character);
                }
                break;
            }
          }
          if (token === null) {
            return result.join("");
          } else {
            throw new Error("Unterminated token");
          }
        }
        static addPrefix(op, result) {
          switch (op) {
            case 2:
              result.push("#");
              break;
            case 3:
              result.push(".");
              break;
            case 4:
              result.push("/");
              break;
            case 5:
              result.push(";");
              break;
            case 6:
              result.push("?");
              break;
            case 7:
              result.push("&");
              break;
            default:
              return;
          }
        }
        static addSeparator(op, result) {
          switch (op) {
            case 3:
              result.push(".");
              break;
            case 4:
              result.push("/");
              break;
            case 5:
              result.push(";");
              break;
            case 6:
            case 7:
              result.push("&");
              break;
            default:
              result.push(",");
              return;
          }
        }
        static addValue(op, token, value, result, maxChar) {
          switch (op) {
            case 1:
            case 2:
              _StdUriTemplate.addExpandedValue(null, value, result, maxChar, false);
              break;
            case 6:
            case 7:
              result.push(`${token}=`);
              _StdUriTemplate.addExpandedValue(null, value, result, maxChar, true);
              break;
            case 5:
              result.push(token);
              _StdUriTemplate.addExpandedValue("=", value, result, maxChar, true);
              break;
            case 3:
            case 4:
            case 0:
              _StdUriTemplate.addExpandedValue(null, value, result, maxChar, true);
              break;
          }
        }
        static addValueElement(op, token, value, result, maxChar) {
          switch (op) {
            case 1:
            case 2:
              _StdUriTemplate.addExpandedValue(null, value, result, maxChar, false);
              break;
            case 6:
            case 7:
            case 5:
            case 3:
            case 4:
            case 0:
              _StdUriTemplate.addExpandedValue(null, value, result, maxChar, true);
              break;
          }
        }
        static isSurrogate(cp) {
          const codeUnit = cp.charCodeAt(0);
          return codeUnit >= 55296 && codeUnit <= 56319;
        }
        static isIprivate(cp) {
          return 57344 <= cp.charCodeAt(0) && cp.charCodeAt(0) <= 63743;
        }
        static isUcschar(cp) {
          const codePoint = cp.codePointAt(0) || 0;
          return 160 <= codePoint && codePoint <= 55295 || 63744 <= codePoint && codePoint <= 64975 || 65008 <= codePoint && codePoint <= 65519;
        }
        static addExpandedValue(prefix, value, result, maxChar, replaceReserved) {
          const stringValue = _StdUriTemplate.convertNativeTypes(value);
          const max = maxChar !== -1 ? Math.min(maxChar, stringValue.length) : stringValue.length;
          let reservedBuffer = void 0;
          if (max > 0 && prefix != null) {
            result.push(prefix);
          }
          for (let i = 0; i < max; i++) {
            const character = stringValue.charAt(i);
            if (character === "%" && !replaceReserved) {
              reservedBuffer = [];
            }
            let toAppend = character;
            if (_StdUriTemplate.isSurrogate(character)) {
              toAppend = encodeURIComponent(stringValue.charAt(i) + stringValue.charAt(i + 1));
              i++;
            } else if (replaceReserved || _StdUriTemplate.isUcschar(character) || _StdUriTemplate.isIprivate(character)) {
              if (character === "!") {
                toAppend = "%21";
              } else {
                toAppend = encodeURIComponent(toAppend);
              }
            }
            if (reservedBuffer) {
              reservedBuffer.push(toAppend);
              if (reservedBuffer.length === 3) {
                let isEncoded = false;
                try {
                  const reserved = reservedBuffer.join("");
                  const decoded = decodeURIComponent(reservedBuffer.join(""));
                  isEncoded = reserved !== decoded;
                } catch (e) {
                }
                if (isEncoded) {
                  result.push(reservedBuffer.join(""));
                } else {
                  result.push("%25");
                  result.push(reservedBuffer.slice(1).join(""));
                }
                reservedBuffer = void 0;
              }
            } else {
              if (character === " ") {
                result.push("%20");
              } else if (character === "%") {
                result.push("%25");
              } else {
                result.push(toAppend);
              }
            }
          }
          if (reservedBuffer) {
            result.push("%25");
            result.push(reservedBuffer.slice(1).join(""));
          }
        }
        static isList(value) {
          return Array.isArray(value) || value instanceof Set;
        }
        static isMap(value) {
          return value instanceof Map || typeof value === "object";
        }
        static getSubstitutionType(value, col) {
          if (value === void 0 || value === null) {
            return 0;
          } else if (_StdUriTemplate.isNativeType(value)) {
            return 1;
          } else if (_StdUriTemplate.isList(value)) {
            return 2;
          } else if (_StdUriTemplate.isMap(value)) {
            return 3;
          } else {
            throw new Error(`Illegal class passed as substitution, found ${typeof value} at col: ${col}`);
          }
        }
        static isEmpty(substType, value) {
          if (value === void 0 || value === null) {
            return true;
          } else {
            switch (substType) {
              case 1:
                return false;
              case 2:
                return value.length === 0;
              case 3:
                return Object.keys(value).length === 0;
              default:
                return true;
            }
          }
        }
        static isNativeType(value) {
          return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
        }
        static convertNativeTypes(value) {
          if (typeof value === "string") {
            return value;
          } else if (typeof value === "number" || typeof value === "boolean") {
            return value.toString();
          } else {
            throw new Error(`Illegal class passed as substitution, found ${typeof value}`);
          }
        }
        static expandToken(operator, token, composite, maxChar, firstToken, substitutions, result, col) {
          if (token.length === 0) {
            throw new Error(`Found an empty token at col: ${col}`);
          }
          const value = substitutions[token];
          const substType = _StdUriTemplate.getSubstitutionType(value, col);
          if (substType === 0 || _StdUriTemplate.isEmpty(substType, value)) {
            return false;
          }
          if (firstToken) {
            _StdUriTemplate.addPrefix(operator, result);
          } else {
            _StdUriTemplate.addSeparator(operator, result);
          }
          switch (substType) {
            case 1:
              _StdUriTemplate.addStringValue(operator, token, value, result, maxChar);
              break;
            case 2:
              _StdUriTemplate.addListValue(operator, token, value, result, maxChar, composite);
              break;
            case 3:
              _StdUriTemplate.addMapValue(operator, token, value, result, maxChar, composite);
              break;
          }
          return true;
        }
        static addStringValue(operator, token, value, result, maxChar) {
          _StdUriTemplate.addValue(operator, token, value, result, maxChar);
        }
        static addListValue(operator, token, value, result, maxChar, composite) {
          let first = true;
          for (const v of value) {
            if (first) {
              _StdUriTemplate.addValue(operator, token, v, result, maxChar);
              first = false;
            } else {
              if (composite) {
                _StdUriTemplate.addSeparator(operator, result);
                _StdUriTemplate.addValue(operator, token, v, result, maxChar);
              } else {
                result.push(",");
                _StdUriTemplate.addValueElement(operator, token, v, result, maxChar);
              }
            }
          }
        }
        static addMapValue(operator, token, value, result, maxChar, composite) {
          let first = true;
          if (maxChar !== -1) {
            throw new Error("Value trimming is not allowed on Maps");
          }
          for (const key in value) {
            const v = value[key];
            if (composite) {
              if (!first) {
                _StdUriTemplate.addSeparator(operator, result);
              }
              _StdUriTemplate.addValueElement(operator, token, key, result, maxChar);
              result.push("=");
            } else {
              if (first) {
                _StdUriTemplate.addValue(operator, token, key, result, maxChar);
              } else {
                result.push(",");
                _StdUriTemplate.addValueElement(operator, token, key, result, maxChar);
              }
              result.push(",");
            }
            _StdUriTemplate.addValueElement(operator, token, v, result, maxChar);
            first = false;
          }
        }
      };
      exports2.StdUriTemplate = StdUriTemplate;
    }
  });

  // modules/std/net/url.js
  var require_url = __commonJS({
    "modules/std/net/url.js"(exports2, module2) {
      "use strict";
      function _str(value, fallback = "") {
        if (value == null) {
          return fallback;
        }
        return String(value);
      }
      function _dict(source = {}) {
        const out = { ...source };
        Object.defineProperties(out, {
          has: {
            value(key) {
              return Object.prototype.hasOwnProperty.call(out, String(key)) ? 1 : 0;
            },
            enumerable: false
          },
          exists: {
            value(key) {
              return out.has(key);
            },
            enumerable: false
          },
          get: {
            value(key, fallback = null) {
              return out.has(key) ? out[String(key)] : fallback;
            },
            enumerable: false
          }
        });
        return out;
      }
      function escape(value) {
        return encodeURIComponent(_str(value));
      }
      function unescape(value) {
        return decodeURIComponent(_str(value));
      }
      function parse(value) {
        const urlText = _str(value);
        const parsed = new URL(urlText, "http://localhost");
        const out = _dict({
          url: parsed.href,
          scheme: parsed.protocol.replace(/:$/u, "") || null,
          authority: parsed.host || null,
          userinfo: null,
          host: parsed.hostname || null,
          port: parsed.port || null,
          path: parsed.pathname || "",
          query: parsed.search.replace(/^\?/u, "") || null,
          fragment: parsed.hash.replace(/^#/u, "") || null,
          query_params: _dict({})
        });
        if (parsed.username || parsed.password) {
          out.userinfo = parsed.username;
          if (parsed.password) {
            out.userinfo += `:${parsed.password}`;
          }
        }
        for (const [key, item] of parsed.searchParams.entries()) {
          out.query_params[key] = item;
        }
        return out;
      }
      var { StdUriTemplate } = require_dist();
      function _templateValue(value) {
        if (value == null) {
          return null;
        }
        if (Array.isArray(value)) {
          return value.map((item) => _str(item));
        }
        if (typeof value === "boolean") {
          return value ? "true" : "false";
        }
        if (typeof value === "object" && !(value.bytes instanceof Uint8Array)) {
          const out = {};
          for (const key of Object.keys(value).sort()) {
            out[key] = _str(value[key]);
          }
          return out;
        }
        return _str(value);
      }
      function fill_template(template, values) {
        const source = _str(template);
        const data = {};
        if (values && typeof values === "object" && !Array.isArray(values)) {
          for (const key of Object.keys(values)) {
            const converted = _templateValue(values[key]);
            if (converted != null) {
              data[key] = converted;
            }
          }
        }
        try {
          return StdUriTemplate.expand(source, data);
        } catch (err) {
          throw new Error(`Exception: invalid URL template: ${source}`);
        }
      }
      module2.exports = {
        escape,
        unescape,
        parse,
        fill_template
      };
    }
  });

  // ../../../../../tmp/zuzu-browser-build.UGYrnC/browser-stdlib.generated.js
  var require_browser_stdlib_generated = __commonJS({
    "../../../../../tmp/zuzu-browser-build.UGYrnC/browser-stdlib.generated.js"(exports2, module2) {
      "use strict";
      function createBrowserStdlib() {
        const jsModules = /* @__PURE__ */ Object.create(null);
        jsModules["/modules/javascript.js"] = require_javascript();
        jsModules["/modules/std/string.js"] = require_string();
        jsModules["/modules/std/string/base64.js"] = require_base64();
        jsModules["/modules/std/string/encode.js"] = require_encode();
        jsModules["/modules/std/time.js"] = require_time();
        jsModules["/modules/std/marshal.js"] = require_marshal();
        jsModules["/modules/std/task.js"] = require_task();
        jsModules["/modules/std/worker.js"] = require_worker();
        jsModules["/modules/std/secure.js"] = require_secure();
        jsModules["/modules/std/data/json.js"] = require_json();
        jsModules["/modules/std/data/yaml.js"] = require_yaml();
        jsModules["/modules/std/data/csv.js"] = require_csv();
        jsModules["/modules/std/data/xml.js"] = require_xml();
        jsModules["/modules/std/digest/md5.js"] = require_md5();
        jsModules["/modules/std/digest/sha.js"] = require_sha();
        jsModules["/modules/std/net/http.js"] = require_http();
        jsModules["/modules/std/math.js"] = require_math();
        jsModules["/modules/std/math/bignum.js"] = require_bignum();
        jsModules["/modules/std/eval.js"] = require_eval();
        jsModules["/modules/std/gui/objects.js"] = require_objects();
        jsModules["/modules/std/tui.js"] = require_tui();
        jsModules["/modules/std/internals.js"] = require_internals();
        jsModules["/modules/std/net/url.js"] = require_url();
        const virtualFiles = /* @__PURE__ */ Object.create(null);
        virtualFiles["/modules/std/colour.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/colour - Colour parsing helpers.\n\n=head1 SYNOPSIS\n\n  from std/colour import parse_colour;\n\n  say( parse_colour("red") );  # #ff0000\n  say( parse_colour("#abc") ); # #aabbcc\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nC<parse_colour> accepts three- and six-digit hexadecimal colours and the\nCSS3 extended colour keywords. It returns a lowercase six-digit\nhexadecimal colour string.\n\n=head1 EXPORTS\n\n=head2 Functions\n\n=over\n\n=item C<< parse_colour(String x) >>\n\nParameters: C<x> is a CSS colour keyword or a three- or six-digit\nhexadecimal colour string. Returns: C<String>. Returns the normalized\nlowercase C<#rrggbb> colour string, or throws if C<x> is not recognised.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/colour >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/string import trim;\n\nconst _COLOUR_KEYWORDS := {\n	aliceblue: "#f0f8ff",\n	antiquewhite: "#faebd7",\n	aqua: "#00ffff",\n	aquamarine: "#7fffd4",\n	azure: "#f0ffff",\n	beige: "#f5f5dc",\n	bisque: "#ffe4c4",\n	black: "#000000",\n	blanchedalmond: "#ffebcd",\n	blue: "#0000ff",\n	blueviolet: "#8a2be2",\n	brown: "#a52a2a",\n	burlywood: "#deb887",\n	cadetblue: "#5f9ea0",\n	chartreuse: "#7fff00",\n	chocolate: "#d2691e",\n	coral: "#ff7f50",\n	cornflowerblue: "#6495ed",\n	cornsilk: "#fff8dc",\n	crimson: "#dc143c",\n	cyan: "#00ffff",\n	darkblue: "#00008b",\n	darkcyan: "#008b8b",\n	darkgoldenrod: "#b8860b",\n	darkgray: "#a9a9a9",\n	darkgreen: "#006400",\n	darkgrey: "#a9a9a9",\n	darkkhaki: "#bdb76b",\n	darkmagenta: "#8b008b",\n	darkolivegreen: "#556b2f",\n	darkorange: "#ff8c00",\n	darkorchid: "#9932cc",\n	darkred: "#8b0000",\n	darksalmon: "#e9967a",\n	darkseagreen: "#8fbc8f",\n	darkslateblue: "#483d8b",\n	darkslategray: "#2f4f4f",\n	darkslategrey: "#2f4f4f",\n	darkturquoise: "#00ced1",\n	darkviolet: "#9400d3",\n	deeppink: "#ff1493",\n	deepskyblue: "#00bfff",\n	dimgray: "#696969",\n	dimgrey: "#696969",\n	dodgerblue: "#1e90ff",\n	firebrick: "#b22222",\n	floralwhite: "#fffaf0",\n	forestgreen: "#228b22",\n	fuchsia: "#ff00ff",\n	gainsboro: "#dcdcdc",\n	ghostwhite: "#f8f8ff",\n	gold: "#ffd700",\n	goldenrod: "#daa520",\n	gray: "#808080",\n	green: "#008000",\n	greenyellow: "#adff2f",\n	grey: "#808080",\n	honeydew: "#f0fff0",\n	hotpink: "#ff69b4",\n	indianred: "#cd5c5c",\n	indigo: "#4b0082",\n	ivory: "#fffff0",\n	khaki: "#f0e68c",\n	lavender: "#e6e6fa",\n	lavenderblush: "#fff0f5",\n	lawngreen: "#7cfc00",\n	lemonchiffon: "#fffacd",\n	lightblue: "#add8e6",\n	lightcoral: "#f08080",\n	lightcyan: "#e0ffff",\n	lightgoldenrodyellow: "#fafad2",\n	lightgray: "#d3d3d3",\n	lightgreen: "#90ee90",\n	lightgrey: "#d3d3d3",\n	lightpink: "#ffb6c1",\n	lightsalmon: "#ffa07a",\n	lightseagreen: "#20b2aa",\n	lightskyblue: "#87cefa",\n	lightslategray: "#778899",\n	lightslategrey: "#778899",\n	lightsteelblue: "#b0c4de",\n	lightyellow: "#ffffe0",\n	lime: "#00ff00",\n	limegreen: "#32cd32",\n	linen: "#faf0e6",\n	magenta: "#ff00ff",\n	maroon: "#800000",\n	mediumaquamarine: "#66cdaa",\n	mediumblue: "#0000cd",\n	mediumorchid: "#ba55d3",\n	mediumpurple: "#9370db",\n	mediumseagreen: "#3cb371",\n	mediumslateblue: "#7b68ee",\n	mediumspringgreen: "#00fa9a",\n	mediumturquoise: "#48d1cc",\n	mediumvioletred: "#c71585",\n	midnightblue: "#191970",\n	mintcream: "#f5fffa",\n	mistyrose: "#ffe4e1",\n	moccasin: "#ffe4b5",\n	navajowhite: "#ffdead",\n	navy: "#000080",\n	oldlace: "#fdf5e6",\n	olive: "#808000",\n	olivedrab: "#6b8e23",\n	orange: "#ffa500",\n	orangered: "#ff4500",\n	orchid: "#da70d6",\n	palegoldenrod: "#eee8aa",\n	palegreen: "#98fb98",\n	paleturquoise: "#afeeee",\n	palevioletred: "#db7093",\n	papayawhip: "#ffefd5",\n	peachpuff: "#ffdab9",\n	peru: "#cd853f",\n	pink: "#ffc0cb",\n	plum: "#dda0dd",\n	powderblue: "#b0e0e6",\n	purple: "#800080",\n	rebeccapurple: "#663399",\n	red: "#ff0000",\n	rosybrown: "#bc8f8f",\n	royalblue: "#4169e1",\n	saddlebrown: "#8b4513",\n	salmon: "#fa8072",\n	sandybrown: "#f4a460",\n	seagreen: "#2e8b57",\n	seashell: "#fff5ee",\n	sienna: "#a0522d",\n	silver: "#c0c0c0",\n	skyblue: "#87ceeb",\n	slateblue: "#6a5acd",\n	slategray: "#708090",\n	slategrey: "#708090",\n	snow: "#fffafa",\n	springgreen: "#00ff7f",\n	steelblue: "#4682b4",\n	tan: "#d2b48c",\n	teal: "#008080",\n	thistle: "#d8bfd8",\n	tomato: "#ff6347",\n	turquoise: "#40e0d0",\n	violet: "#ee82ee",\n	wheat: "#f5deb3",\n	white: "#ffffff",\n	whitesmoke: "#f5f5f5",\n	yellow: "#ffff00",\n	yellowgreen: "#9acd32",\n};\n\nfunction parse_colour ( String x ) {\n	let text := lc( trim(x) );\n\n	if ( text ~ /^#[0-9a-f]{6}$/ ) {\n		return text;\n	}\n\n	let short := text ~ /^#([0-9a-f])([0-9a-f])([0-9a-f])$/;\n	if ( short ) {\n		return "#"\n			_ short[1] _ short[1]\n			_ short[2] _ short[2]\n			_ short[3] _ short[3];\n	}\n\n	if ( _COLOUR_KEYWORDS.exists(text) ) {\n		return _COLOUR_KEYWORDS.get(text);\n	}\n\n	die `Invalid colour: ${x}`;\n}\n';
        virtualFiles["/modules/std/result.zzm"] = "=encoding utf8\n\n=head1 NAME\n\nstd/result - A simple Result object for explicit success and failure values.\n\n=head1 SYNOPSIS\n\n  from std/result import Result;\n\n  let r := Result.ok(42);\n\n  if ( r.is_ok() ) {\n    say r.unwrap();\n  }\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nC<Result> is a small, subclassable object modelled on a simplified version\nof Rust's C<Result> concept. It is useful when a function, task, or worker\nwants to return an explicit success or failure value without throwing an\nexception.\n\nIt is a normal ZuzuScript class. Workers do not require C<Result>; any value\nsupported by C<std/marshal> may be returned.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<Result>\n\nContainer for either an ok value or an error value.\n\n=over\n\n=item C<< Result.ok(value) >>\n\nParameters: C<value> is any success value. Returns: C<Result>. Creates an\nok result wrapping C<value>.\n\n=item C<< Result.err(error) >>\n\nParameters: C<error> is any error value. Returns: C<Result>. Creates an\nerror result wrapping C<error>.\n\n=item C<< result.is_ok() >>\n\nParameters: none. Returns: C<Boolean>. Returns true when the result is an\nok value.\n\n=item C<< result.is_err() >>\n\nParameters: none. Returns: C<Boolean>. Returns true when the result is an\nerror value.\n\n=item C<< result.value() >>\n\nParameters: none. Returns: value. Returns the stored ok value, or\nC<null> for an error result.\n\n=item C<< result.error() >>\n\nParameters: none. Returns: value. Returns the stored error value, or\nC<null> for an ok result.\n\n=item C<< result.unwrap() >>\n\nParameters: none. Returns: value. Returns the ok value, or throws if the\nresult is an error.\n\n=item C<< result.unwrap_err() >>\n\nParameters: none. Returns: value. Returns the error value, or throws if\nthe result is ok.\n\n=back\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/result >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nclass Result {\n	let Boolean _is_ok := true;\n	let _value := null;\n	let _error := null;\n\n	static method ok ( value ) {\n		return new self(\n			_is_ok: true,\n			_value: value,\n			_error: null,\n		);\n	}\n\n	static method err ( error ) {\n		return new self(\n			_is_ok: false,\n			_value: null,\n			_error: error,\n		);\n	}\n\n	method is_ok () {\n		return _is_ok;\n	}\n\n	method is_err () {\n		return not _is_ok;\n	}\n\n	method value () {\n		return _value;\n	}\n\n	method error () {\n		return _error;\n	}\n\n	method unwrap () {\n		if ( _is_ok ) {\n			return _value;\n		}\n\n		die `called Result.unwrap() on an err value: ${_error}`;\n	}\n\n	method unwrap_err () {\n		if ( not _is_ok ) {\n			return _error;\n		}\n\n		die `called Result.unwrap_err() on an ok value: ${_value}`;\n	}\n}\n";
        virtualFiles["/modules/std/string/quoted_printable.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/string/quoted_printable - Quoted-printable encoders and decoders.\n\n=head1 SYNOPSIS\n\n  from std/string/quoted_printable import encode, decode;\n\n  let raw := to_binary( "Hello, world!\\r\\n" );\n\n  let text := encode(raw);\n  let bytes := decode(text);\n\n  let binary_text := encode(raw, binary: true);\n  let short_lines := encode(raw, line_length: 40, newline: "\\n");\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module provides quoted-printable encoding and decoding helpers for\nRFC 2045-style byte transport. Encoding returns ASCII C<String> text.\nDecoding returns a C<BinaryString>, because quoted-printable is a byte\ntransfer encoding rather than a Unicode text format.\n\nThe C<binary> option controls how input line break bytes are encoded.\nIn the default non-binary mode, CRLF, CR, and LF bytes are normalized to\nthe configured C<newline> string. In binary mode, CR and LF bytes are\nencoded as C<=0D> and C<=0A>.\n\n=head1 EXPORTS\n\n=head2 Functions\n\n=over\n\n=item * C<encode(BinaryString bytes, ... PairList options)>\n\nParameters: C<bytes> is binary input data and C<options> controls\nencoding. Returns: C<String>. Encodes C<bytes> as quoted-printable ASCII\ntext.\n\n=item * C<decode(String text, ... PairList options)>\n\nParameters: C<text> is quoted-printable text and C<options> controls\nstrictness. Returns: C<BinaryString>. Decodes quoted-printable text into\nbytes.\n\n=back\n\n=head1 OPTIONS\n\n=over\n\n=item * C<line_length>\n\nMaximum encoded line length. Defaults to C<76> and must be at least\nC<4>.\n\n=item * C<newline>\n\nOutput newline for hard line breaks and encoded soft breaks. Defaults\nto CRLF.\n\n=item * C<binary>\n\nWhen true, encode CR and LF bytes as C<=0D> and C<=0A>. Defaults to\nfalse.\n\n=item * C<strict>\n\nWhen true, malformed quoted-printable escape sequences throw during\ndecoding. Non-strict decoding preserves malformed escape text\nliterally.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/string/quoted_printable >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\n\nlet encode := null;\nlet decode := null;\n\n{\n	from std/string import chr, index, ord, substr;\n	from std/string/base64 import\n		encode as _base64_encode,\n		decode as _base64_decode;\n\n	let _B64_ALPHABET := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"\n		_ "abcdefghijklmnopqrstuvwxyz0123456789+/";\n	let _HEX := "0123456789ABCDEF";\n\n	function _div_floor ( Number n, Number d ) {\n		return floor( n / d );\n	}\n\n	function _mod ( Number n, Number d ) {\n		return n - _div_floor( n, d ) * d;\n	}\n\n	function _bytes_to_binary ( Array bytes ) {\n		let out := "";\n		let i := 0;\n		let n := bytes.length();\n\n		while ( i < n ) {\n			let b0 := bytes[i];\n			let b1 := null;\n			let b2 := null;\n			if ( i + 1 < n ) {\n				b1 := bytes[i + 1];\n			}\n			if ( i + 2 < n ) {\n				b2 := bytes[i + 2];\n			}\n\n			let c0 := _div_floor( b0, 4 );\n			let c1 := _mod( b0, 4 ) * 16;\n			let c2 := 64;\n			let c3 := 64;\n\n			if ( not( b1 == null ) ) {\n				c1 += _div_floor( b1, 16 );\n				c2 := _mod( b1, 16 ) * 4;\n				if ( not( b2 == null ) ) {\n					c2 += _div_floor( b2, 64 );\n					c3 := _mod( b2, 64 );\n				}\n			}\n\n			out _= substr( _B64_ALPHABET, c0, 1 );\n			out _= substr( _B64_ALPHABET, c1, 1 );\n			out _= c2 == 64 ? "=" : substr( _B64_ALPHABET, c2, 1 );\n			out _= c3 == 64 ? "=" : substr( _B64_ALPHABET, c3, 1 );\n			i += 3;\n		}\n\n		return _base64_decode(out);\n	}\n\n	function _binary_to_bytes ( BinaryString raw ) {\n		let b64 := _base64_encode(raw);\n		let out := [];\n		let i := 0;\n		let n := length b64;\n\n		while ( i < n ) {\n			let c0 := index( _B64_ALPHABET, substr( b64, i, 1 ) );\n			let c1 := index( _B64_ALPHABET, substr( b64, i + 1, 1 ) );\n			let ch2 := substr( b64, i + 2, 1 );\n			let ch3 := substr( b64, i + 3, 1 );\n			let c2 := -1;\n			let c3 := -1;\n			if ( ch2 ne "=" ) {\n				c2 := index( _B64_ALPHABET, ch2 );\n			}\n			if ( ch3 ne "=" ) {\n				c3 := index( _B64_ALPHABET, ch3 );\n			}\n\n			out.push( c0 * 4 + _div_floor( c1, 16 ) );\n			if ( c2 >= 0 ) {\n				out.push( _mod( c1, 16 ) * 16 + _div_floor( c2, 4 ) );\n			}\n			if ( c3 >= 0 ) {\n				out.push( _mod( c2, 4 ) * 64 + c3 );\n			}\n\n			i += 4;\n		}\n\n		return out;\n	}\n\n	function _parse_options ( PairList options ) {\n		let line_length := 76;\n		let newline := "\\r\\n";\n		let binary := false;\n		let strict := false;\n\n		for ( let option in options.enumerate() ) {\n			let key := option.key;\n			let value := option.value;\n\n			if ( key eq "line_length" ) {\n				line_length := value;\n			}\n			else if ( key eq "newline" ) {\n				newline := value;\n			}\n			else if ( key eq "binary" ) {\n				binary := value;\n			}\n			else if ( key eq "strict" ) {\n				strict := value;\n			}\n			else {\n				die `quoted_printable option \'${key}\' is not supported`;\n			}\n		}\n\n		if ( not( line_length instanceof Number ) ) {\n			die "quoted_printable line_length option expects Number";\n		}\n		if ( line_length < 4 ) {\n			die "quoted_printable line_length option must be at least 4";\n		}\n		if ( not( newline instanceof String ) ) {\n			die "quoted_printable newline option expects String";\n		}\n		if ( not( binary instanceof Boolean ) ) {\n			die "quoted_printable binary option expects Boolean";\n		}\n		if ( not( strict instanceof Boolean ) ) {\n			die "quoted_printable strict option expects Boolean";\n		}\n\n		return {\n			line_length: int(line_length),\n			newline: newline,\n			binary: binary,\n			strict: strict,\n		};\n	}\n\n	function _is_safe_literal ( Number b ) {\n		return ( b >= 33 and b <= 60 ) or ( b >= 62 and b <= 126 );\n	}\n\n	function _byte_to_hex_token ( Number b ) {\n		return "="\n			_ substr( _HEX, _div_floor( b, 16 ), 1 )\n			_ substr( _HEX, _mod( b, 16 ), 1 );\n	}\n\n	function _simple_token_length ( Number b, Boolean final_byte ) {\n		if ( ( b == 9 or b == 32 ) and not final_byte ) {\n			return 1;\n		}\n		if ( _is_safe_literal(b) ) {\n			return 1;\n		}\n		return 3;\n	}\n\n	function _space_tab_needs_escape (\n		Array bytes,\n		Number i,\n		Number column,\n		Number line_length,\n	) {\n		let n := bytes.length();\n		if ( i + 1 >= n ) {\n			return true;\n		}\n\n		let j := i + 1;\n		while ( j < n and ( bytes[j] == 9 or bytes[j] == 32 ) ) {\n			j++;\n		}\n		if ( j >= n ) {\n			return true;\n		}\n\n		let next_is_final := i + 2 >= n;\n		let next_len := _simple_token_length( bytes[i + 1], next_is_final );\n		let max := next_is_final ? line_length : line_length - 1;\n		return column + 1 + next_len > max;\n	}\n\n	function _token_for_byte (\n		Array bytes,\n		Number i,\n		Number column,\n		Number line_length,\n	) {\n		let b := bytes[i];\n\n		if ( b == 9 or b == 32 ) {\n			if ( _space_tab_needs_escape( bytes, i, column, line_length ) ) {\n				return _byte_to_hex_token(b);\n			}\n			return chr(b);\n		}\n\n		if ( _is_safe_literal(b) ) {\n			return chr(b);\n		}\n\n		return _byte_to_hex_token(b);\n	}\n\n	function _emit_token (\n		String out,\n		Number column,\n		String token,\n		Boolean more_after,\n		Number line_length,\n		String newline,\n	) {\n		let max := more_after ? line_length - 1 : line_length;\n		let updated_out := out;\n		let updated_column := column;\n\n		if ( updated_column > 0 and updated_column + ( length token ) > max ) {\n			updated_out _= "=" _ newline;\n			updated_column := 0;\n		}\n\n		updated_out _= token;\n		updated_column += length token;\n\n		return [ updated_out, updated_column ];\n	}\n\n	function _encode_segment (\n		Array bytes,\n		Number line_length,\n		String newline,\n	) {\n		let out := "";\n		let column := 0;\n		let i := 0;\n		let n := bytes.length();\n\n		while ( i < n ) {\n			let token := _token_for_byte( bytes, i, column, line_length );\n			let emitted := _emit_token(\n				out,\n				column,\n				token,\n				i + 1 < n,\n				line_length,\n				newline,\n			);\n			out := emitted[0];\n			column := emitted[1];\n			i++;\n		}\n\n		return out;\n	}\n\n	function _encode_text_bytes (\n		Array bytes,\n		Number line_length,\n		String newline,\n	) {\n		let out := "";\n		let line := [];\n		let i := 0;\n		let n := bytes.length();\n\n		while ( i < n ) {\n			let b := bytes[i];\n			if ( b == 13 or b == 10 ) {\n				out _= _encode_segment( line, line_length, newline );\n				out _= newline;\n				line := [];\n\n				if ( b == 13 and i + 1 < n and bytes[i + 1] == 10 ) {\n					i++;\n				}\n			}\n			else {\n				line.push(b);\n			}\n\n			i++;\n		}\n\n		out _= _encode_segment( line, line_length, newline );\n		return out;\n	}\n\n	function _hex_value ( String ch ) {\n		let cp := ord(ch);\n		if ( cp >= 48 and cp <= 57 ) {\n			return cp - 48;\n		}\n		if ( cp >= 65 and cp <= 70 ) {\n			return cp - 55;\n		}\n		if ( cp >= 97 and cp <= 102 ) {\n			return cp - 87;\n		}\n		return -1;\n	}\n\n	function _decode_text_bytes ( String text, Boolean strict ) {\n		let out := [];\n		let i := 0;\n		let n := length text;\n\n		while ( i < n ) {\n			let ch := substr( text, i, 1 );\n			let cp := ord( text, i );\n\n			if ( cp > 127 ) {\n				die "quoted_printable.decode rejects non-ASCII input";\n			}\n\n			if ( ch eq "=" ) {\n				if ( i + 1 >= n ) {\n					die "malformed quoted-printable escape" if strict;\n					out.push(61);\n					i++;\n					next;\n				}\n\n				let ch1 := substr( text, i + 1, 1 );\n				if ( ch1 eq "\\r" ) {\n					if ( i + 2 < n and substr( text, i + 2, 1 ) eq "\\n" ) {\n						i += 3;\n					}\n					else {\n						i += 2;\n					}\n					next;\n				}\n				if ( ch1 eq "\\n" ) {\n					i += 2;\n					next;\n				}\n\n				if ( i + 2 < n ) {\n					let hi := _hex_value(ch1);\n					let lo := _hex_value( substr( text, i + 2, 1 ) );\n					if ( hi >= 0 and lo >= 0 ) {\n						out.push( hi * 16 + lo );\n						i += 3;\n						next;\n					}\n				}\n\n				die "malformed quoted-printable escape" if strict;\n				out.push(61);\n				i++;\n				next;\n			}\n\n			out.push(cp);\n			i++;\n		}\n\n		return out;\n	}\n\n	encode := function ( BinaryString bytes, ... PairList options ) {\n		let opts := _parse_options(options);\n		let raw := _binary_to_bytes(bytes);\n\n		if ( opts{binary} ) {\n			return _encode_segment(\n				raw,\n				opts{line_length},\n				opts{newline},\n			);\n		}\n\n		return _encode_text_bytes(\n			raw,\n			opts{line_length},\n			opts{newline},\n		);\n	};\n\n	decode := function ( String text, ... PairList options ) {\n		let opts := _parse_options(options);\n		return _bytes_to_binary( _decode_text_bytes( text, opts{strict} ) );\n	};\n}\n';
        virtualFiles["/modules/std/gui.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/gui - User-facing GUI constructor helpers.\n\n=head1 SYNOPSIS\n\n  from std/gui import *;\n\n  let w := Window(\n  	title: "Demo",\n  	VBox(\n  		Label( text: "Name:" ),\n  		Input( id: "name" ),\n  		Button( text: "OK", id: "submit" ),\n  	),\n  );\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Electron.\nIt is not supported by zuzu-js on Node. It is partially supported by\nzuzu-js in the browser: core GUI and widget lifecycle coverage passes,\nbut filesystem-backed file and directory dialogue coverage is unsupported.\n\n=head1 DESCRIPTION\n\nThis module provides thin constructor helpers over C<std/gui/objects>.\nHost runtimes expose the shared widget, object tree, event, and window\nlifecycle APIs when GUI support is available. It also re-exports\nbackend-native file and directory dialogue hooks for C<std/gui/dialogue>.\n\nThe module exports C<EM>, the standard UI font height in logical\npixels, derived from C<std/gui/objects> metadata.\n\n=head1 EXPORTS\n\n=head2 Constants\n\n=over\n\n=item C<EM>\n\nType: C<Number>. Standard UI font height in logical pixels.\n\n=item C<GUI_XML_NS>\n\nType: C<String>. XML namespace URI used by GUI XML serialization and\nparsing.\n\n=back\n\n=head2 Functions\n\n=over\n\n=item C<< Window(... PairList p, Array c) >>, C<< VBox(... PairList p, Array c) >>, C<< HBox(... PairList p, Array c) >>, C<< Frame(... PairList p, Array c) >>\n\nParameters: C<p> are widget properties and C<c> contains child widgets.\nReturns: widget object. Constructs window and layout widgets.\n\n=item C<< Label(... PairList p, Array c) >>, C<< Text(... PairList p, Array c) >>, C<< RichText(... PairList p, Array c) >>, C<< Image(... PairList p, Array c) >>\n\nParameters: C<p> are widget properties and C<c> contains child widgets.\nReturns: widget object. Constructs content widgets.\n\n=item C<< Input(... PairList p, Array c) >>, C<< DatePicker(... PairList p, Array c) >>, C<< Checkbox(... PairList p, Array c) >>, C<< Radio(... PairList p, Array c) >>, C<< RadioGroup(... PairList p, Array c) >>, C<< Select(... PairList p, Array c) >>\n\nParameters: C<p> are widget properties and C<c> contains child widgets.\nReturns: widget object. Constructs input widgets.\n\n=item C<< Menu(... PairList p, Array c) >>, C<< MenuItem(... PairList p, Array c) >>, C<< Button(... PairList p, Array c) >>, C<< Separator(... PairList p, Array c) >>, C<< Slider(... PairList p, Array c) >>, C<< Progress(... PairList p, Array c) >>\n\nParameters: C<p> are widget properties and C<c> contains child widgets.\nReturns: widget object. Constructs command and control widgets.\n\n=item C<< Tabs(... PairList p, Array c) >>, C<< Tab(... PairList p, Array c) >>, C<< ListView(... PairList p, Array c) >>, C<< TreeView(... PairList p, Array c) >>\n\nParameters: C<p> are widget properties and C<c> contains child widgets.\nReturns: widget object. Constructs tabular and collection widgets.\n\n=item C<< unbind(BindingToken token) >>\n\nParameters: C<token> is a binding token. Returns: C<null>. Removes a GUI\nbinding.\n\n=item C<< gui_from_xml(String xml) >>, C<< gui_from_xml_file(path) >>\n\nParameters: C<xml> is GUI XML text and C<path> is a file path. Returns:\nwidget object. Builds a GUI object tree from XML.\n\n=item C<< gui_to_xml(Widget root) >>\n\nParameters: C<root> is a GUI widget. Returns: C<String>. Serializes a\nGUI object tree to XML.\n\n=back\n\n=head2 Classes\n\n=over\n\n=item C<BindingToken>\n\nRepresents a model/widget binding.\n\n=over\n\n=item C<< token.is_active() >>\n\nParameters: none. Returns: C<Boolean>. Returns true while the binding is\nactive.\n\n=item C<< token.set_listener(token) >>\n\nParameters: C<token> is a listener token. Returns: C<BindingToken>.\nStores the listener token associated with the binding.\n\n=item C<< token.sync_model_to_widget() >>, C<< token.sync_widget_to_model() >>\n\nParameters: none. Returns: C<null>. Synchronizes the bound values.\n\n=item C<< token.unbind() >>\n\nParameters: none. Returns: C<null>. Removes the binding.\n\n=back\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/gui >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/gui/objects import\n	Window as _WindowClass,\n	VBox as _VBoxClass,\n	HBox as _HBoxClass,\n	Frame as _FrameClass,\n	Label as _LabelClass,\n	Text as _TextClass,\n	RichText as _RichTextClass,\n	Image as _ImageClass,\n	Input as _InputClass,\n	DatePicker as _DatePickerClass,\n	Checkbox as _CheckboxClass,\n	Radio as _RadioClass,\n	RadioGroup as _RadioGroupClass,\n	Select as _SelectClass,\n	Menu as _MenuClass,\n	MenuItem as _MenuItemClass,\n	Button as _ButtonClass,\n	Separator as _SeparatorClass,\n	Slider as _SliderClass,\n	Progress as _ProgressClass,\n	Tabs as _TabsClass,\n	Tab as _TabClass,\n	ListView as _ListViewClass,\n	TreeView as _TreeViewClass,\n	Widget,\n	Event,\n	ListenerToken,\n	native_file_open,\n	native_file_save,\n	native_directory_open,\n	native_directory_save,\n	native_colour_picker,\n	meta as _gui_meta;\n\nfrom std/gui/objects try import\n	native_alert,\n	native_confirm,\n	native_prompt;\n\nfrom std/data/xml import XML;\nfrom std/data/xml/escape import escape_xml;\nfrom std/internals import getupperprop;\nfrom std/path/zz import ZZPath;\nfrom std/string import join, split, substr, trim;\n\n\nconst Number EM := _gui_meta{font_size_pixels};\n\nfunction _assert_known_props ( String ctor, PairList props, Array allowed ) {\n	let geometry := [\n		"width",\n		"height",\n		"minwidth",\n		"minheight",\n		"maxwidth",\n		"maxheight",\n	];\n	for ( let key in props.keys() ) {\n		if ( key \u2209 allowed and key \u2209 geometry ) {\n			die `GUI_PROP_UNKNOWN: ${ctor} does not accept property \'${key}\'`;\n		}\n	}\n}\n\nfunction _assert_prop_value ( String ctor, String prop, value, Array allowed ) {\n	if ( value \u2209 allowed ) {\n		die `GUI_PROP_TYPE: ${ctor} property \'${prop}\' has invalid value`;\n	}\n}\n\nfunction _assert_prop_array ( String ctor, String prop, value ) {\n	if ( not( value instanceof Array ) ) {\n		die `GUI_PROP_TYPE: ${ctor} property \'${prop}\' expects Array`;\n	}\n}\n\nfunction _with_geometry_props ( Array allowed ) {\n	for ( let key in [\n		"width",\n		"height",\n		"minwidth",\n		"minheight",\n		"maxwidth",\n		"maxheight",\n	] ) {\n		allowed.push(key) unless key \u2208 allowed;\n	}\n	return allowed;\n}\n\nfunction _apply_geometry ( Widget widget, PairList p ) {\n	for ( let key in [\n		"width",\n		"height",\n		"minwidth",\n		"minheight",\n		"maxwidth",\n		"maxheight",\n	] ) {\n		if ( p.has(key) ) {\n			widget.(key)( p.get(key) );\n		}\n	}\n	return widget;\n}\n\nfunction Window ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"Window",\n		p,\n		_with_geometry_props( [\n			"id",\n			"title",\n			"width",\n			"height",\n			"resizable",\n			"modal",\n			"visible",\n			"enabled",\n			"disabled",\n		] ),\n	);\n\n	return new _WindowClass(\n		id: p.get( "id", null ),\n		title: p.get( "title", "" ),\n		width: p.get( "width", 800 ),\n		height: p.get( "height", 600 ),\n		minwidth: p.get( "minwidth", null ),\n		minheight: p.get( "minheight", null ),\n		maxwidth: p.get( "maxwidth", null ),\n		maxheight: p.get( "maxheight", null ),\n		resizable: p.get( "resizable", true ),\n		modal: p.get( "modal", false ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	);\n}\n\nfunction VBox ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"VBox",\n		p,\n		[\n			"id",\n			"align",\n			"gap",\n			"padding",\n			"visible",\n			"enabled",\n			"disabled",\n		],\n	);\n\n	_assert_prop_value(\n		"VBox",\n		"align",\n		p.get( "align", "top" ),\n		[ "top", "centre", "bottom", "stretch" ],\n	);\n\n	return _apply_geometry( new _VBoxClass(\n		id: p.get( "id", null ),\n		align: p.get( "align", "top" ),\n		gap: p.get( "gap", 0 ),\n		padding: p.get( "padding", 0 ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction HBox ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"HBox",\n		p,\n		_with_geometry_props( [\n			"id",\n			"align",\n			"gap",\n			"padding",\n			"visible",\n			"enabled",\n			"disabled",\n		] ),\n	);\n\n	_assert_prop_value(\n		"HBox",\n		"align",\n		p.get( "align", "left" ),\n		[ "left", "centre", "right", "stretch" ],\n	);\n\n	return new _HBoxClass(\n		id: p.get( "id", null ),\n		align: p.get( "align", "left" ),\n		gap: p.get( "gap", 0 ),\n		padding: p.get( "padding", 0 ),\n		width: p.get( "width", null ),\n		height: p.get( "height", null ),\n		minwidth: p.get( "minwidth", null ),\n		minheight: p.get( "minheight", null ),\n		maxwidth: p.get( "maxwidth", null ),\n		maxheight: p.get( "maxheight", null ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	);\n}\n\nfunction Frame ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"Frame",\n		p,\n		[\n			"id",\n			"label",\n			"collapsible",\n			"collapsed",\n			"visible",\n			"enabled",\n			"disabled",\n		],\n	);\n\n	return _apply_geometry( new _FrameClass(\n		id: p.get( "id", null ),\n		label: p.get( "label", "" ),\n		collapsible: p.get( "collapsible", false ),\n		collapsed: p.get( "collapsed", false ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction Label ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"Label",\n		p,\n		[ "id", "text", "for", "visible", "enabled", "disabled" ],\n	);\n\n	let label := new _LabelClass(\n		id: p.get( "id", null ),\n		text: p.get( "text", "" ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	);\n	if ( p.has("for") ) {\n		label.set_for_id( p.get( "for", null ) );\n	}\n\n	return _apply_geometry( label, p );\n}\n\nfunction Text ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"Text",\n		p,\n		[\n			"id",\n			"value",\n			"multiline",\n			"readonly",\n			"wrap",\n			"visible",\n			"enabled",\n			"disabled",\n		],\n	);\n\n	return _apply_geometry( new _TextClass(\n		id: p.get( "id", null ),\n		value: p.get( "value", "" ),\n		multiline: p.get( "multiline", false ),\n		readonly: p.get( "readonly", false ),\n		wrap: p.get( "wrap", true ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction RichText ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"RichText",\n		p,\n		[\n			"id",\n			"value",\n			"multiline",\n			"readonly",\n			"visible",\n			"enabled",\n			"disabled",\n		],\n	);\n\n	return _apply_geometry( new _RichTextClass(\n		id: p.get( "id", null ),\n		value: p.get( "value", "" ),\n		multiline: p.get( "multiline", true ),\n		readonly: p.get( "readonly", true ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction Image ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"Image",\n		p,\n		[ "id", "src", "alt", "fit", "visible", "enabled", "disabled" ],\n	);\n\n	_assert_prop_value(\n		"Image",\n		"fit",\n		p.get( "fit", "none" ),\n		[ "none", "contain", "cover", "stretch" ],\n	);\n\n	return _apply_geometry( new _ImageClass(\n		id: p.get( "id", null ),\n		src: p.get( "src", "" ),\n		alt: p.get( "alt", "" ),\n		fit: p.get( "fit", "none" ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction Input ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"Input",\n		p,\n		[\n			"id",\n			"value",\n			"placeholder",\n			"multiline",\n			"readonly",\n			"password",\n			"required",\n			"visible",\n			"enabled",\n			"disabled",\n		],\n	);\n\n	return _apply_geometry( new _InputClass(\n		id: p.get( "id", null ),\n		value: p.get( "value", "" ),\n		placeholder: p.get( "placeholder", "" ),\n		multiline: p.get( "multiline", false ),\n		readonly: p.get( "readonly", false ),\n		password: p.get( "password", false ),\n		required: p.get( "required", false ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction DatePicker ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"DatePicker",\n		p,\n		[\n			"id",\n			"value",\n			"min",\n			"max",\n			"first_day_of_week",\n			"visible",\n			"enabled",\n			"disabled",\n		],\n	);\n\n	return _apply_geometry( new _DatePickerClass(\n		id: p.get( "id", null ),\n		value: p.get( "value", null ),\n		min: p.get( "min", null ),\n		max: p.get( "max", null ),\n		first_day_of_week: p.get( "first_day_of_week", 0 ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction Checkbox ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"Checkbox",\n		p,\n		[\n			"id",\n			"label",\n			"checked",\n			"indeterminate",\n			"visible",\n			"enabled",\n			"disabled",\n		],\n	);\n\n	return _apply_geometry( new _CheckboxClass(\n		id: p.get( "id", null ),\n		label: p.get( "label", "" ),\n		checked: p.get( "checked", false ),\n		indeterminate: p.get( "indeterminate", false ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction Radio ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"Radio",\n		p,\n		[\n			"id",\n			"label",\n			"value",\n			"group",\n			"checked",\n			"visible",\n			"enabled",\n			"disabled",\n		],\n	);\n\n	return _apply_geometry( new _RadioClass(\n		id: p.get( "id", null ),\n		label: p.get( "label", "" ),\n		value: p.get( "value", "" ),\n		group: p.get( "group", null ),\n		checked: p.get( "checked", false ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction RadioGroup ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"RadioGroup",\n		p,\n		[\n			"id",\n			"name",\n			"value",\n			"visible",\n			"enabled",\n			"disabled",\n		],\n	);\n\n	return _apply_geometry( new _RadioGroupClass(\n		id: p.get( "id", null ),\n		name: p.get( "name", "" ),\n		value: p.get( "value", null ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction Select ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"Select",\n		p,\n		[\n			"id",\n			"value",\n			"options",\n			"multiple",\n			"visible",\n			"enabled",\n			"disabled",\n		],\n	);\n\n	if ( p.has("options") ) {\n		_assert_prop_array( "Select", "options", p.get("options") );\n	}\n\n	return _apply_geometry( new _SelectClass(\n		id: p.get( "id", null ),\n		value: p.get( "value", null ),\n		options: p.get( "options", [] ),\n		multiple: p.get( "multiple", false ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction Menu ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"Menu",\n		p,\n		[ "id", "text", "visible", "enabled", "disabled" ],\n	);\n\n	return _apply_geometry( new _MenuClass(\n		id: p.get( "id", null ),\n		text: p.get( "text", "" ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction MenuItem ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"MenuItem",\n		p,\n		[ "id", "text", "disabled", "visible", "enabled" ],\n	);\n\n	return _apply_geometry( new _MenuItemClass(\n		id: p.get( "id", null ),\n		text: p.get( "text", "" ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction Button ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"Button",\n		p,\n		_with_geometry_props( [\n			"id",\n			"text",\n			"variant",\n			"visible",\n			"enabled",\n			"disabled",\n		] ),\n	);\n\n	_assert_prop_value(\n		"Button",\n		"variant",\n		p.get( "variant", "default" ),\n		[ "default", "primary", "danger" ],\n	);\n\n	return new _ButtonClass(\n		id: p.get( "id", null ),\n		text: p.get( "text", "" ),\n		variant: p.get( "variant", "default" ),\n		width: p.get( "width", null ),\n		height: p.get( "height", null ),\n		minwidth: p.get( "minwidth", null ),\n		minheight: p.get( "minheight", null ),\n		maxwidth: p.get( "maxwidth", null ),\n		maxheight: p.get( "maxheight", null ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	);\n}\n\nfunction Separator ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"Separator",\n		p,\n		[ "id", "orientation", "visible", "enabled", "disabled" ],\n	);\n\n	_assert_prop_value(\n		"Separator",\n		"orientation",\n		p.get( "orientation", "horizontal" ),\n		[ "horizontal", "vertical" ],\n	);\n\n	return _apply_geometry( new _SeparatorClass(\n		id: p.get( "id", null ),\n		orientation: p.get( "orientation", "horizontal" ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction Slider ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"Slider",\n		p,\n		[\n			"id",\n			"value",\n			"min",\n			"max",\n			"step",\n			"orientation",\n			"readonly",\n			"visible",\n			"enabled",\n			"disabled",\n		],\n	);\n\n	_assert_prop_value(\n		"Slider",\n		"orientation",\n		p.get( "orientation", "horizontal" ),\n		[ "horizontal", "vertical" ],\n	);\n\n	return _apply_geometry( new _SliderClass(\n		id: p.get( "id", null ),\n		value: p.get( "value", 0 ),\n		min: p.get( "min", 0 ),\n		max: p.get( "max", 100 ),\n		step: p.get( "step", 1 ),\n		orientation: p.get( "orientation", "horizontal" ),\n		readonly: p.get( "readonly", false ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction Progress ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"Progress",\n		p,\n		[\n			"id",\n			"value",\n			"min",\n			"max",\n			"indeterminate",\n			"show_text",\n			"visible",\n			"enabled",\n			"disabled",\n		],\n	);\n\n	return _apply_geometry( new _ProgressClass(\n		id: p.get( "id", null ),\n		value: p.get( "value", 0 ),\n		min: p.get( "min", 0 ),\n		max: p.get( "max", 100 ),\n		indeterminate: p.get( "indeterminate", false ),\n		show_text: p.get( "show_text", false ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction Tabs ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"Tabs",\n		p,\n		[\n			"id",\n			"selected",\n			"placement",\n			"visible",\n			"enabled",\n			"disabled",\n		],\n	);\n\n	_assert_prop_value(\n		"Tabs",\n		"placement",\n		p.get( "placement", "top" ),\n		[ "top", "bottom", "left", "right" ],\n	);\n\n	return _apply_geometry( new _TabsClass(\n		id: p.get( "id", null ),\n		selected: p.get( "selected", null ),\n		placement: p.get( "placement", "top" ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction Tab ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"Tab",\n		p,\n		[\n			"id",\n			"title",\n			"value",\n			"selected",\n			"closable",\n			"icon",\n			"visible",\n			"enabled",\n			"disabled",\n		],\n	);\n\n	return _apply_geometry( new _TabClass(\n		id: p.get( "id", null ),\n		title: p.get( "title", "" ),\n		value: p.get( "value", "" ),\n		selected: p.get( "selected", false ),\n		closable: p.get( "closable", false ),\n		icon: p.get( "icon", null ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction ListView ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"ListView",\n		p,\n		[\n			"id",\n			"items",\n			"selected_index",\n			"multiple",\n			"visible",\n			"enabled",\n			"disabled",\n		],\n	);\n\n	if ( p.has("items") ) {\n		_assert_prop_array( "ListView", "items", p.get("items") );\n	}\n\n	return _apply_geometry( new _ListViewClass(\n		id: p.get( "id", null ),\n		items: p.get( "items", [] ),\n		selected_index: p.get( "selected_index", null ),\n		multiple: p.get( "multiple", false ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction TreeView ( ... PairList p, Array c ) {\n	_assert_known_props(\n		"TreeView",\n		p,\n		[\n			"id",\n			"items",\n			"selected_path",\n			"multiple",\n			"visible",\n			"enabled",\n			"disabled",\n		],\n	);\n\n	if ( p.has("items") ) {\n		_assert_prop_array( "TreeView", "items", p.get("items") );\n	}\n	if ( p.has("selected_path") ) {\n		_assert_prop_array( "TreeView", "selected_path", p.get("selected_path") );\n	}\n\n	return _apply_geometry( new _TreeViewClass(\n		id: p.get( "id", null ),\n		items: p.get( "items", [] ),\n		selected_path: p.get( "selected_path", [] ),\n		multiple: p.get( "multiple", false ),\n		visible: p.get( "visible", true ),\n		enabled: p.get( "enabled", true ),\n		disabled: p.get( "disabled", false ),\n		children: c,\n	), p );\n}\n\nfunction _binding_path_class ( path_class ) {\n	if ( path_class \u2261 null ) {\n		return ZZPath;\n	}\n	if ( not( path_class instanceof Class ) ) {\n		die "GUI_BIND_PATH: paths special property must be Class or null";\n	}\n	return path_class;\n}\n\nfunction _binding_compile_path ( String path_text, path_class ) {\n	if ( path_class \u2261 null ) {\n		try {\n			return new ZZPath( path: path_text );\n		}\n		catch ( Exception e ) {\n			die `GUI_BIND_PATH: ${e{message}}`;\n		}\n	}\n\n	let path_type := _binding_path_class(path_class);\n	try {\n		return new path_type( path: path_text );\n	}\n	catch ( Exception e ) {\n		die `GUI_BIND_PATH: ${e{message}}`;\n	}\n}\n\nfunction _binding_path ( pathish, path_class ) {\n	if ( pathish instanceof String ) {\n		return _binding_compile_path( pathish, path_class );\n	}\n	if (\n		pathish can first\n		and ( pathish can assign_first or pathish can ref_first )\n	) {\n		return pathish;\n	}\n\n	die "GUI_BIND_PATH: binding path must be String or path-like Object";\n}\n\nfunction _binding_get ( model, path ) {\n	return path.first( model, null );\n}\n\nfunction _binding_set ( model, path, value ) {\n	if ( path can assign_first ) {\n		return path.assign_first( model, value );\n	}\n\n	let ref := path.ref_first(model);\n	return ref(value);\n}\n\nclass BindingToken {\n	let Widget widget but weak;\n	let String widget_prop;\n	let model;\n	let model_path;\n	let String event := "change";\n	let listener := null;\n	let Boolean _active := true;\n\n	method is_active () {\n		return _active;\n	}\n\n	method set_listener ( token ) {\n		listener := token;\n		return self;\n	}\n\n	method sync_model_to_widget () {\n		widget.(widget_prop)( _binding_get( model, model_path ) );\n		return self;\n	}\n\n	method sync_widget_to_model () {\n		_binding_set( model, model_path, widget.(widget_prop)() );\n		return self;\n	}\n\n	method unbind () {\n		if ( _active and listener \u2262 null ) {\n			widget.off(listener);\n		}\n		_active := false;\n		return self;\n	}\n}\n\nfunction bind (\n	Widget widget,\n	String widget_prop,\n	model,\n	model_path,\n	... PairList p\n) {\n	let path := _binding_path( model_path, getupperprop( 1, "paths" ) );\n\n	let token := new BindingToken(\n		widget: widget,\n		widget_prop: widget_prop,\n		model: model,\n		model_path: path,\n		event: p.get( "event", "change" ),\n	);\n	let event_name := p.get( "event", "change" );\n\n	switch ( p.get( "initial", "model" ): eq ) {\n		case "model":\n			token.sync_model_to_widget();\n		case "widget":\n			token.sync_widget_to_model();\n		case "none":\n			// No initial sync.\n		default:\n			die "GUI_BIND_INITIAL: initial must be model, widget, or none";\n	}\n\n	token.set_listener(\n		widget.on( event_name, function () {\n			if ( token.is_active() ) {\n				token.sync_widget_to_model();\n			}\n		} ),\n	);\n	return token;\n}\n\nfunction unbind ( BindingToken token ) {\n	return token.unbind();\n}\n\nlet GUI_XML_NS := "https://zuzulang.org/ns/std/gui";\n\nfunction _xml_error ( String code, String message ) {\n	die `${code}: ${message}`;\n}\n\nfunction _xml_tag_name ( node ) {\n	return node.localName() or? node.nodeName();\n}\n\nfunction _xml_assert_namespace ( node ) {\n	let ns := node.namespaceURI();\n	if ( ns \u2262 null and ns \u2262 "" and ns \u2262 GUI_XML_NS ) {\n		_xml_error(\n			"GUI_XML_STRUCTURE",\n			`unsupported GUI XML namespace \'${ns}\'`,\n		);\n	}\n}\n\nfunction _xml_common_allowed ( Array extra ) {\n	let out := [\n		"id",\n		"visible",\n		"enabled",\n		"disabled",\n		"width",\n		"height",\n		"minwidth",\n		"minheight",\n		"maxwidth",\n		"maxheight",\n	];\n	for ( let attr in extra ) {\n		out.push(attr);\n	}\n	return out;\n}\n\nfunction _xml_allowed_attrs ( String tag ) {\n	switch ( tag: eq ) {\n		case "Window":\n			return _xml_common_allowed(\n				[ "title", "width", "height", "resizable", "modal" ],\n			);\n		case "VBox", "HBox":\n			return _xml_common_allowed( [ "align", "gap", "padding" ] );\n		case "Frame":\n			return _xml_common_allowed( [ "label", "collapsible", "collapsed" ] );\n		case "Label":\n			return _xml_common_allowed( [ "text", "for" ] );\n		case "Text":\n			return _xml_common_allowed(\n				[ "value", "multiline", "readonly", "wrap" ],\n			);\n		case "RichText":\n			return _xml_common_allowed(\n				[ "value", "multiline", "readonly" ],\n			);\n		case "Image":\n			return _xml_common_allowed( [ "src", "alt", "fit" ] );\n		case "Input":\n			return _xml_common_allowed( [\n				"value",\n				"placeholder",\n				"multiline",\n				"readonly",\n				"password",\n				"required",\n			] );\n		case "DatePicker":\n			return _xml_common_allowed(\n				[ "value", "min", "max", "first_day_of_week" ],\n			);\n		case "Checkbox":\n			return _xml_common_allowed( [ "label", "checked", "indeterminate" ] );\n		case "Radio":\n			return _xml_common_allowed( [ "label", "value", "group", "checked" ] );\n		case "RadioGroup":\n			return _xml_common_allowed( [ "name", "value" ] );\n		case "Select":\n			return _xml_common_allowed( [ "value", "multiple" ] );\n		case "Menu":\n			return _xml_common_allowed( [ "text" ] );\n		case "MenuItem":\n			return _xml_common_allowed( [ "text" ] );\n		case "Button":\n			return _xml_common_allowed( [ "text", "variant" ] );\n		case "Separator":\n			return _xml_common_allowed( [ "orientation" ] );\n		case "Slider":\n			return _xml_common_allowed( [\n				"value",\n				"min",\n				"max",\n				"step",\n				"orientation",\n				"readonly",\n			] );\n		case "Progress":\n			return _xml_common_allowed( [\n				"value",\n				"min",\n				"max",\n				"indeterminate",\n				"show_text",\n			] );\n		case "Tabs":\n			return _xml_common_allowed( [ "selected", "placement" ] );\n		case "Tab":\n			return _xml_common_allowed(\n				[ "title", "value", "selected", "closable", "icon" ],\n			);\n		case "ListView":\n			return _xml_common_allowed( [ "selected_index", "multiple" ] );\n		case "TreeView":\n			return _xml_common_allowed( [ "selected_path", "multiple" ] );\n	}\n\n	_xml_error( "GUI_XML_STRUCTURE", `unsupported GUI XML element \'${tag}\'` );\n}\n\nfunction _xml_bool_attrs ( String tag ) {\n	return [\n		"visible",\n		"enabled",\n		"disabled",\n		"resizable",\n		"modal",\n		"collapsible",\n		"collapsed",\n		"multiline",\n		"readonly",\n		"wrap",\n		"password",\n		"required",\n		"checked",\n		"indeterminate",\n		"multiple",\n		"show_text",\n		"selected",\n		"closable",\n	];\n}\n\nfunction _xml_number_attrs ( String tag ) {\n	return [\n		"width",\n		"height",\n		"minwidth",\n		"minheight",\n		"maxwidth",\n		"maxheight",\n		"gap",\n		"padding",\n		"first_day_of_week",\n		"selected_index",\n		"value",\n		"min",\n		"max",\n		"step",\n	];\n}\n\nfunction _xml_bool ( String tag, String attr, String raw ) {\n	switch ( lc(raw): eq ) {\n		case "true", "1", "yes", "on": return true;\n		case "false", "0", "no", "off": return false;\n	}\n	_xml_error(\n		"GUI_XML_ATTR_TYPE",\n		`${tag}.${attr} expects a boolean XML attribute`,\n	);\n}\n\nfunction _xml_number ( String tag, String attr, String raw ) {\n	if ( not ( raw ~ /^-?[0-9]+(\\.[0-9]+)?$/ ) ) {\n		_xml_error(\n			"GUI_XML_ATTR_TYPE",\n			`${tag}.${attr} expects a numeric XML attribute`,\n		);\n	}\n	return 0 + raw;\n}\n\nfunction _xml_int_list ( String tag, String attr, String raw ) {\n	let out := [];\n	return out if raw eq "";\n	for ( let part in split( raw, "," ) ) {\n		let item := trim(part);\n		if ( not ( item ~ /^-?[0-9]+$/ ) ) {\n			_xml_error(\n				"GUI_XML_ATTR_TYPE",\n				`${tag}.${attr} expects comma-separated integers`,\n			);\n		}\n		out.push( 0 + item );\n	}\n	return out;\n}\n\nfunction _xml_coerce_attr ( String tag, String attr, String raw ) {\n	if ( attr eq "selected" and tag eq "Tabs" ) {\n		return raw;\n	}\n	if ( attr eq "value" and tag \u2209 [ "Slider", "Progress" ] ) {\n		return raw;\n	}\n	if ( attr eq "min" and tag eq "DatePicker" ) {\n		return raw;\n	}\n	if ( attr eq "max" and tag eq "DatePicker" ) {\n		return raw;\n	}\n	if ( attr eq "selected_path" ) {\n		return _xml_int_list( tag, attr, raw );\n	}\n	if ( attr \u2208 _xml_bool_attrs(tag) ) {\n		return _xml_bool( tag, attr, raw );\n	}\n	if ( attr \u2208 _xml_number_attrs(tag) ) {\n		return _xml_number( tag, attr, raw );\n	}\n	return raw;\n}\n\nfunction _xml_attrs ( node ) {\n	let tag := _xml_tag_name(node);\n	let props := {};\n	let meta := {};\n	let meta_keys := [];\n	let style := {};\n	let style_keys := [];\n	let allowed := _xml_allowed_attrs(tag);\n\n	for ( let attr in node.attributeNames() ) {\n		next if attr eq "xmlns";\n		next if substr( attr, 0, 6 ) eq "xmlns:";\n		let value := node.getAttribute(attr);\n		if ( substr( attr, 0, 5 ) eq "meta." ) {\n			let key := substr( attr, 5 );\n			_xml_error( "GUI_XML_ATTR_UNKNOWN", "empty meta attribute name" )\n				if key eq "";\n			meta{(key)} := value;\n			meta_keys.push(key);\n			next;\n		}\n		if ( substr( attr, 0, 6 ) eq "style." ) {\n			let key := substr( attr, 6 );\n			_xml_error( "GUI_XML_ATTR_UNKNOWN", "empty style attribute name" )\n				if key eq "";\n			style{(key)} := value;\n			style_keys.push(key);\n			next;\n		}\n		if ( attr \u2209 allowed ) {\n			_xml_error(\n				"GUI_XML_ATTR_UNKNOWN",\n				`${tag} does not accept XML attribute \'${attr}\'`,\n			);\n		}\n		props{(attr)} := _xml_coerce_attr( tag, attr, value );\n	}\n\n	return {\n		props: props,\n		meta: meta,\n		meta_keys: meta_keys,\n		style: style,\n		style_keys: style_keys,\n	};\n}\n\nfunction _xml_apply_meta ( Widget widget, Dict meta, Array keys ) {\n	for ( let key in keys ) {\n		widget.meta( key, meta{(key)} );\n	}\n	if ( keys.length() > 0 ) {\n		widget.meta( "__xml_meta_keys", keys );\n	}\n	return widget;\n}\n\nfunction _xml_apply_style ( Widget widget, Dict style, Array keys ) {\n	for ( let key in keys ) {\n		widget.style( key, style{(key)} );\n	}\n	if ( keys.length() > 0 ) {\n		widget.meta( "__xml_style_keys", keys );\n	}\n	return widget;\n}\n\nfunction _xml_widget_from_node ( node ) {\n	_xml_assert_namespace(node);\n\n	let tag := _xml_tag_name(node);\n	let child_widgets := [];\n	for ( let child in node.children() ) {\n		child_widgets.push( _xml_widget_from_node(child) );\n	}\n	let parsed := _xml_attrs(node);\n	let p := parsed{props};\n	let widget;\n\n	switch ( tag: eq ) {\n		case "Window":\n			widget := new _WindowClass(\n				id: p.get( "id", null ),\n				title: p.get( "title", "" ),\n				width: p.get( "width", 800 ),\n				height: p.get( "height", 600 ),\n				resizable: p.get( "resizable", true ),\n				modal: p.get( "modal", false ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n				children: child_widgets,\n			);\n		case "VBox":\n			widget := new _VBoxClass(\n				id: p.get( "id", null ),\n				align: p.get( "align", "top" ),\n				gap: p.get( "gap", 0 ),\n				padding: p.get( "padding", 0 ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n				children: child_widgets,\n			);\n		case "HBox":\n			widget := new _HBoxClass(\n				id: p.get( "id", null ),\n				align: p.get( "align", "left" ),\n				gap: p.get( "gap", 0 ),\n				padding: p.get( "padding", 0 ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n				children: child_widgets,\n			);\n		case "Frame":\n			widget := new _FrameClass(\n				id: p.get( "id", null ),\n				label: p.get( "label", "" ),\n				collapsible: p.get( "collapsible", false ),\n				collapsed: p.get( "collapsed", false ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n				children: child_widgets,\n			);\n		case "Label":\n			widget := Label(\n				id: p.get( "id", null ),\n				text: p.get( "text", "" ),\n				("for"): p.get( "for", null ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n			);\n		case "Text":\n			widget := Text(\n				id: p.get( "id", null ),\n				value: p.get( "value", "" ),\n				multiline: p.get( "multiline", false ),\n				readonly: p.get( "readonly", false ),\n				wrap: p.get( "wrap", true ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n			);\n		case "RichText":\n			widget := RichText(\n				id: p.get( "id", null ),\n				value: p.get( "value", "" ),\n				multiline: p.get( "multiline", true ),\n				readonly: p.get( "readonly", true ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n			);\n		case "Image":\n			widget := Image(\n				id: p.get( "id", null ),\n				src: p.get( "src", "" ),\n				alt: p.get( "alt", "" ),\n				fit: p.get( "fit", "none" ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n			);\n		case "Input":\n			widget := Input(\n				id: p.get( "id", null ),\n				value: p.get( "value", "" ),\n				placeholder: p.get( "placeholder", "" ),\n				multiline: p.get( "multiline", false ),\n				readonly: p.get( "readonly", false ),\n				password: p.get( "password", false ),\n				required: p.get( "required", false ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n			);\n		case "DatePicker":\n			widget := DatePicker(\n				id: p.get( "id", null ),\n				value: p.get( "value", null ),\n				min: p.get( "min", null ),\n				max: p.get( "max", null ),\n				first_day_of_week: p.get( "first_day_of_week", 0 ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n			);\n		case "Checkbox":\n			widget := Checkbox(\n				id: p.get( "id", null ),\n				label: p.get( "label", "" ),\n				checked: p.get( "checked", false ),\n				indeterminate: p.get( "indeterminate", false ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n			);\n		case "Radio":\n			widget := Radio(\n				id: p.get( "id", null ),\n				label: p.get( "label", "" ),\n				value: p.get( "value", "" ),\n				group: p.get( "group", null ),\n				checked: p.get( "checked", false ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n			);\n		case "RadioGroup":\n			widget := new _RadioGroupClass(\n				id: p.get( "id", null ),\n				name: p.get( "name", "" ),\n				value: p.get( "value", null ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n				children: child_widgets,\n			);\n		case "Select":\n			widget := Select(\n				id: p.get( "id", null ),\n				value: p.get( "value", null ),\n				multiple: p.get( "multiple", false ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n			);\n		case "Menu":\n			widget := new _MenuClass(\n				id: p.get( "id", null ),\n				text: p.get( "text", "" ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n				children: child_widgets,\n			);\n		case "MenuItem":\n			widget := MenuItem(\n				id: p.get( "id", null ),\n				text: p.get( "text", "" ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n			);\n		case "Button":\n			widget := Button(\n				id: p.get( "id", null ),\n				text: p.get( "text", "" ),\n				variant: p.get( "variant", "default" ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n			);\n		case "Separator":\n			widget := Separator(\n				id: p.get( "id", null ),\n				orientation: p.get( "orientation", "horizontal" ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n			);\n		case "Slider":\n			widget := Slider(\n				id: p.get( "id", null ),\n				value: p.get( "value", 0 ),\n				min: p.get( "min", 0 ),\n				max: p.get( "max", 100 ),\n				step: p.get( "step", 1 ),\n				orientation: p.get( "orientation", "horizontal" ),\n				readonly: p.get( "readonly", false ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n			);\n		case "Progress":\n			widget := Progress(\n				id: p.get( "id", null ),\n				value: p.get( "value", 0 ),\n				min: p.get( "min", 0 ),\n				max: p.get( "max", 100 ),\n				indeterminate: p.get( "indeterminate", false ),\n				show_text: p.get( "show_text", false ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n			);\n		case "Tabs":\n			widget := new _TabsClass(\n				id: p.get( "id", null ),\n				selected: p.get( "selected", null ),\n				placement: p.get( "placement", "top" ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n				children: child_widgets,\n			);\n		case "Tab":\n			widget := new _TabClass(\n				id: p.get( "id", null ),\n				title: p.get( "title", "" ),\n				value: p.get( "value", "" ),\n				selected: p.get( "selected", false ),\n				closable: p.get( "closable", false ),\n				icon: p.get( "icon", null ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n				children: child_widgets,\n			);\n		case "ListView":\n			widget := ListView(\n				id: p.get( "id", null ),\n				selected_index: p.get( "selected_index", null ),\n				multiple: p.get( "multiple", false ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n			);\n		case "TreeView":\n			widget := TreeView(\n				id: p.get( "id", null ),\n				selected_path: p.get( "selected_path", [] ),\n				multiple: p.get( "multiple", false ),\n				visible: p.get( "visible", true ),\n				enabled: p.get( "enabled", true ),\n				disabled: p.get( "disabled", false ),\n			);\n		default:\n			_xml_error(\n				"GUI_XML_STRUCTURE",\n				`unsupported GUI XML element \'${tag}\'`,\n			);\n	}\n\n	_xml_apply_meta( widget, parsed{meta}, parsed{meta_keys} );\n	return _xml_apply_style( widget, parsed{style}, parsed{style_keys} );\n}\n\nfunction gui_from_xml ( String xml ) {\n	return _xml_widget_from_node( XML.parse(xml).documentElement() );\n}\n\nfunction gui_from_xml_file ( path ) {\n	die "XML.load is denied by runtime policy" if __system__{deny_fs};\n	from std/io import Path;\n	let file := path instanceof Path ? path : new Path(path);\n	return _xml_widget_from_node( XML.load(file).documentElement() );\n}\n\nfunction _xml_tag_for_widget ( Widget widget ) {\n	if ( widget instanceof _WindowClass ) { return "Window"; }\n	if ( widget instanceof _VBoxClass ) { return "VBox"; }\n	if ( widget instanceof _HBoxClass ) { return "HBox"; }\n	if ( widget instanceof _FrameClass ) { return "Frame"; }\n	if ( widget instanceof _LabelClass ) { return "Label"; }\n	if ( widget instanceof _TextClass ) { return "Text"; }\n	if ( widget instanceof _RichTextClass ) { return "RichText"; }\n	if ( widget instanceof _ImageClass ) { return "Image"; }\n	if ( widget instanceof _InputClass ) { return "Input"; }\n	if ( widget instanceof _DatePickerClass ) { return "DatePicker"; }\n	if ( widget instanceof _CheckboxClass ) { return "Checkbox"; }\n	if ( widget instanceof _RadioClass ) { return "Radio"; }\n	if ( widget instanceof _RadioGroupClass ) { return "RadioGroup"; }\n	if ( widget instanceof _SelectClass ) { return "Select"; }\n	if ( widget instanceof _MenuClass ) { return "Menu"; }\n	if ( widget instanceof _MenuItemClass ) { return "MenuItem"; }\n	if ( widget instanceof _ButtonClass ) { return "Button"; }\n	if ( widget instanceof _SeparatorClass ) { return "Separator"; }\n	if ( widget instanceof _SliderClass ) { return "Slider"; }\n	if ( widget instanceof _ProgressClass ) { return "Progress"; }\n	if ( widget instanceof _TabsClass ) { return "Tabs"; }\n	if ( widget instanceof _TabClass ) { return "Tab"; }\n	if ( widget instanceof _ListViewClass ) { return "ListView"; }\n	if ( widget instanceof _TreeViewClass ) { return "TreeView"; }\n	_xml_error( "GUI_XML_STRUCTURE", "unsupported widget for gui_to_xml" );\n}\n\nfunction _xml_attr ( String name, value ) {\n	return "" if value \u2261 null;\n	return ` ${name}="${escape_xml(value)}"`;\n}\n\nfunction _xml_attr_if ( String name, value, fallback ) {\n	return "" if value \u2261 fallback;\n	return _xml_attr( name, value );\n}\n\nfunction _xml_bool_attr_if ( String name, value, fallback ) {\n	let normalized := value ? true : false;\n	let normalized_fallback := fallback ? true : false;\n	return "" if normalized \u2261 normalized_fallback;\n	return _xml_attr( name, normalized ? "true" : "false" );\n}\n\nfunction _xml_attr_nonempty ( String name, value ) {\n	return "" if value \u2261 null or value eq "";\n	return _xml_attr( name, value );\n}\n\nfunction _xml_join_ints ( Array values ) {\n	let out := [];\n	for ( let value in values ) {\n		out.push( "" _ value );\n	}\n	return join( ",", out );\n}\n\nfunction _xml_meta_attrs ( Widget widget ) {\n	// These metadata slots are null or arrays; empty arrays are values.\n	let keys := widget.meta( "__xml_meta_keys" ) ?: [];\n	let out := "";\n	for ( let key in keys ) {\n		out _= _xml_attr( "meta." _ key, widget.meta(key) );\n	}\n	return out;\n}\n\nfunction _xml_style_attrs ( Widget widget ) {\n	// These metadata slots are null or arrays; empty arrays are values.\n	let keys := widget.meta( "__xml_style_keys" ) ?: [];\n	let out := "";\n	for ( let key in keys ) {\n		out _= _xml_attr( "style." _ key, widget.style(key) );\n	}\n	return out;\n}\n\nfunction _xml_common_attrs ( Widget widget ) {\n	let out := "";\n	out _= _xml_attr( "id", widget.id() ) if widget.id() \u2262 null;\n	out _= _xml_bool_attr_if( "visible", widget.visible(), true );\n	out _= _xml_bool_attr_if( "disabled", not widget.enabled(), false );\n	out _= _xml_meta_attrs(widget);\n	out _= _xml_style_attrs(widget);\n	return out;\n}\n\nfunction _xml_widget_attrs ( Widget widget ) {\n	let out := _xml_common_attrs(widget);\n	if ( widget instanceof _WindowClass ) {\n		out _= _xml_attr_if( "title", widget.title(), "" );\n	}\n	else if ( widget instanceof _VBoxClass or widget instanceof _HBoxClass ) {\n		let default_align := widget instanceof _VBoxClass ? "top" : "left";\n		out _= _xml_attr_if( "align", widget.align(), default_align );\n		out _= _xml_attr_if( "gap", widget.gap(), 0 );\n		out _= _xml_attr_if( "padding", widget.padding(), 0 )\n			unless widget.padding() instanceof Array;\n	}\n	else if ( widget instanceof _FrameClass ) {\n		out _= _xml_attr_if( "label", widget.label(), "" );\n		out _= _xml_bool_attr_if( "collapsible", widget.collapsible(), false );\n		out _= _xml_bool_attr_if( "collapsed", widget.collapsed(), false );\n	}\n	else if ( widget instanceof _LabelClass ) {\n		out _= _xml_attr_if( "text", widget.text(), "" );\n		out _= _xml_attr_nonempty( "for", widget.for_id() );\n	}\n	else if ( widget instanceof _TextClass ) {\n		out _= _xml_attr_if( "value", widget.value(), "" );\n		out _= _xml_bool_attr_if( "multiline", widget.multiline(), false );\n		out _= _xml_bool_attr_if( "readonly", widget.readonly(), false );\n		out _= _xml_bool_attr_if( "wrap", widget.wrap(), true );\n	}\n	else if ( widget instanceof _RichTextClass ) {\n		out _= _xml_attr_if( "value", widget.value(), "" );\n		out _= _xml_bool_attr_if( "multiline", widget.multiline(), true );\n		out _= _xml_bool_attr_if( "readonly", widget.readonly(), true );\n	}\n	else if ( widget instanceof _ImageClass ) {\n		out _= _xml_attr_if( "src", widget.src(), "" );\n		out _= _xml_attr_if( "alt", widget.alt(), "" );\n		out _= _xml_attr_if( "fit", widget.fit(), "none" );\n	}\n	else if ( widget instanceof _InputClass ) {\n		out _= _xml_attr_if( "value", widget.value(), "" );\n		out _= _xml_attr_if( "placeholder", widget.placeholder(), "" );\n		out _= _xml_bool_attr_if( "multiline", widget.multiline(), false );\n		out _= _xml_bool_attr_if( "readonly", widget.readonly(), false );\n		out _= _xml_bool_attr_if( "password", widget.password(), false );\n		out _= _xml_bool_attr_if( "required", widget.required(), false );\n	}\n	else if ( widget instanceof _DatePickerClass ) {\n		out _= _xml_attr( "value", widget.value() );\n		out _= _xml_attr( "min", widget.min() ) if widget.min() \u2262 null;\n		out _= _xml_attr( "max", widget.max() ) if widget.max() \u2262 null;\n		out _= _xml_attr_if(\n			"first_day_of_week",\n			widget.first_day_of_week(),\n			0,\n		);\n	}\n	else if ( widget instanceof _CheckboxClass ) {\n		out _= _xml_attr_if( "label", widget.label(), "" );\n		out _= _xml_bool_attr_if( "checked", widget.checked(), false );\n		out _= _xml_bool_attr_if( "indeterminate", widget.indeterminate(), false );\n	}\n	else if ( widget instanceof _RadioClass ) {\n		out _= _xml_attr_if( "label", widget.label(), "" );\n		out _= _xml_attr_if( "value", widget.value(), "" );\n		out _= _xml_attr_nonempty( "group", widget.group() );\n		out _= _xml_bool_attr_if( "checked", widget.checked(), false );\n	}\n	else if ( widget instanceof _RadioGroupClass ) {\n		out _= _xml_attr_if( "name", widget.name(), "" );\n		out _= _xml_attr( "value", widget.value() ) if widget.value() \u2262 null;\n	}\n	else if ( widget instanceof _SelectClass ) {\n		out _= _xml_attr( "value", widget.value() ) if widget.value() \u2262 null;\n		out _= _xml_bool_attr_if( "multiple", widget.multiple(), false );\n	}\n	else if ( widget instanceof _MenuClass ) {\n		out _= _xml_attr_if( "text", widget.text(), "" );\n	}\n	else if ( widget instanceof _MenuItemClass ) {\n		out _= _xml_attr_if( "text", widget.text(), "" );\n	}\n	else if ( widget instanceof _ButtonClass ) {\n		out _= _xml_attr_if( "text", widget.text(), "" );\n		out _= _xml_attr_if( "variant", widget.variant(), "default" );\n	}\n	else if ( widget instanceof _SeparatorClass ) {\n		out _= _xml_attr_if( "orientation", widget.orientation(), "horizontal" );\n	}\n	else if ( widget instanceof _SliderClass ) {\n		out _= _xml_attr_if( "value", widget.value(), 0 );\n		out _= _xml_attr_if( "min", widget.min(), 0 );\n		out _= _xml_attr_if( "max", widget.max(), 100 );\n		out _= _xml_attr_if( "step", widget.step(), 1 );\n		out _= _xml_attr_if( "orientation", widget.orientation(), "horizontal" );\n		out _= _xml_bool_attr_if( "readonly", widget.readonly(), false );\n	}\n	else if ( widget instanceof _ProgressClass ) {\n		out _= _xml_attr_if( "value", widget.value(), 0 );\n		out _= _xml_attr_if( "min", widget.min(), 0 );\n		out _= _xml_attr_if( "max", widget.max(), 100 );\n		out _= _xml_bool_attr_if( "indeterminate", widget.indeterminate(), false );\n		out _= _xml_bool_attr_if( "show_text", widget.show_text(), false );\n	}\n	else if ( widget instanceof _TabsClass ) {\n		out _= _xml_attr( "selected", widget.selected() )\n			if widget.selected() \u2262 null;\n		out _= _xml_attr_if( "placement", widget.placement(), "top" );\n	}\n	else if ( widget instanceof _TabClass ) {\n		out _= _xml_attr_if( "title", widget.title(), "" );\n		out _= _xml_attr_if( "value", widget.value(), "" );\n		out _= _xml_attr( "icon", widget.icon() ) if widget.icon() \u2262 null;\n		out _= _xml_bool_attr_if( "selected", widget.selected(), false );\n		out _= _xml_bool_attr_if( "closable", widget.closable(), false );\n	}\n	else if ( widget instanceof _ListViewClass ) {\n		out _= _xml_attr( "selected_index", widget.selected_index() )\n			if widget.selected_index() \u2262 null;\n		out _= _xml_bool_attr_if( "multiple", widget.multiple(), false );\n	}\n	else if ( widget instanceof _TreeViewClass ) {\n		let selected_path := widget.selected_path();\n		out _= _xml_attr( "selected_path", _xml_join_ints(selected_path) )\n			if selected_path.length() > 0;\n		out _= _xml_bool_attr_if( "multiple", widget.multiple(), false );\n	}\n	return out;\n}\n\nfunction _xml_serialize_widget ( Widget widget, Number depth ) {\n	let indent := "";\n	let i := 0;\n	while ( i < depth ) {\n		indent _= "\\t";\n		i++;\n	}\n\n	let tag := _xml_tag_for_widget(widget);\n	let attrs := _xml_widget_attrs(widget);\n	attrs _= _xml_attr( "xmlns", GUI_XML_NS ) if depth = 0;\n	let children := widget.children();\n	if ( children.length() = 0 ) {\n		return indent _ "<" _ tag _ attrs _ " />";\n	}\n\n	let parts := [];\n	for ( let child in children ) {\n		parts.push( _xml_serialize_widget( child, depth + 1 ) );\n	}\n\n	return indent _ "<" _ tag _ attrs _ ">\\n"\n		_ join( "\\n", parts )\n		_ "\\n" _ indent _ "</" _ tag _ ">";\n}\n\nfunction gui_to_xml ( Widget root ) {\n	return _xml_serialize_widget( root, 0 ) _ "\\n";\n}\n';
        virtualFiles["/modules/std/gui/dialogue.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/gui/dialogue - Dialogue helpers.\n\n=head1 SYNOPSIS\n\n  from std/gui/dialogue import *;\n\n  alert("Saved");\n  let ok := confirm("Continue?");\n  let name := prompt("Name:", value: "Ada");\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Electron\nand Browser. It is not supported by zuzu-js on Node.\n\n=head1 DESCRIPTION\n\nThis module provides convenience dialogue helpers layered on top of the\nregular C<std/gui> widgets.\n\n=head1 EXPORTS\n\n=head2 Functions\n\n=over\n\n=item C<< alert(String message, ... PairList p) >>, C<< alert_window(String message, ... PairList p) >>\n\nParameters: C<message> is display text and C<p> contains options.\nReturns: C<null> for C<alert> or C<Window> for C<alert_window>. Shows or\nbuilds an alert dialogue.\n\n=item C<< confirm(String message, ... PairList p) >>, C<< confirm_window(String message, ... PairList p) >>\n\nParameters: C<message> is display text and C<p> contains options.\nReturns: C<Boolean> for C<confirm> or C<Window> for\nC<confirm_window>. Shows or builds a confirmation dialogue.\n\n=item C<< prompt(String message, ... PairList p) >>, C<< prompt_window(String message, ... PairList p) >>\n\nParameters: C<message> is prompt text and C<p> contains options such as\nC<value>. Returns: C<String> or C<null> for C<prompt>, or C<Window> for\nC<prompt_window>. Shows or builds a text prompt.\n\n=item C<< file_open(... PairList p) >>, C<< file_save(... PairList p) >>\n\nParameters: C<p> contains dialogue options. Returns: path value or\nC<null>. Opens a file selection dialogue.\n\n=item C<< directory_open(... PairList p) >>, C<< directory_save(... PairList p) >>\n\nParameters: C<p> contains dialogue options. Returns: path value or\nC<null>. Opens a directory selection dialogue.\n\n=item C<< colour_picker(... PairList p) >>\n\nParameters: C<p> contains dialogue options. Returns: C<String> or\nC<null>. Opens a colour picker and returns a normalized colour string.\n\n=item C<< file_open_window(... PairList p) >>, C<< file_save_window(... PairList p) >>, C<< directory_open_window(... PairList p) >>, C<< directory_save_window(... PairList p) >>, C<< colour_picker_window(... PairList p) >>\n\nParameters: C<p> contains dialogue options. Returns: C<Window>. Builds\nthe corresponding GUI dialogue window.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/gui/dialogue >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/gui try import\n	EM,\n	Window,\n	VBox,\n	HBox,\n	Label,\n	Text,\n	Input,\n	Button,\n	Widget,\n	native_file_open,\n	native_file_save,\n	native_directory_open,\n	native_directory_save,\n	native_colour_picker;\nfrom std/gui/objects try import\n	meta as _objects_meta,\n	native_alert,\n	native_confirm,\n	native_prompt;\nfrom std/colour import parse_colour;\nfrom std/string import split;\nfrom std/tui import\n	colour_text,\n	directory_completions,\n	filename_completions,\n	readline;\n\nfunction _tui_string ( value ) {\n	return value \u2261 null ? "" : "" _ value;\n}\n\nfunction _gui_backend () {\n	if ( _objects_meta \u2262 null ) {\n		return _objects_meta{backend};\n	}\n	return "";\n}\n\nfunction _path_dialogue_unsupported () {\n	if ( __system__{deny_fs} ) {\n		die "GUI_DIALOGUE_FS_DENIED: file and directory dialogues require filesystem capability";\n	}\n	if ( _gui_backend() eq "browser-dom" ) {\n		die "GUI_DIALOGUE_UNSUPPORTED: file and directory dialogues are unsupported in JS/Browser";\n	}\n}\n\nfunction _tui_prompt ( String message, PairList p, String default_value ) {\n	return readline(\n		colour_text( message _ " ", "cyan" ),\n		default_value,\n		null,\n	);\n}\n\nfunction _tui_path_dialog (\n	String label,\n	String default_value,\n	completion,\n	PairList p\n) {\n	let answer := readline(\n		colour_text( p.get( "label", label ) _ " ", "cyan" ),\n		_tui_string( p.get( "value", default_value ) ),\n		completion,\n	);\n	if ( p.get( "multiple", false ) ) {\n		return split( answer, p.get( "separator", "\\n" ) );\n	}\n	return answer;\n}\n\nfunction _parse_colour_or_null ( value ) {\n	return try {\n		parse_colour( _tui_string(value) );\n	}\n	catch {\n		null;\n	};\n}\n\nfunction _colour_initial_value ( PairList p ) {\n	let raw := _tui_string( p.get( "value", "#000000" ) );\n	let parsed := _parse_colour_or_null(raw);\n	return parsed \u2262 null ? parsed : raw;\n}\n\nfunction _colour_default_value ( PairList p ) {\n	// The parser returns null for invalid input; valid colours are values.\n	return _parse_colour_or_null( p.get( "value", "#000000" ) ) ?: "#000000";\n}\n\nfunction _tui_colour_dialog ( PairList p ) {\n	let default_value := _colour_default_value(p);\n	while ( true ) {\n		let answer := readline(\n			colour_text( p.get( "label", "Colour:" ) _ " ", "cyan" ),\n			default_value,\n			null,\n		);\n		let parsed := _parse_colour_or_null(answer);\n		if ( parsed \u2262 null ) {\n			return parsed;\n		}\n		say( colour_text( "Invalid colour; try #336699 or red.", "yellow" ) );\n	}\n}\n\nfunction _dialogue_window (\n	String kind,\n	String title,\n	Widget body,\n	Array buttons,\n	PairList p\n) {\n	let button_row := HBox(\n		id: "buttons",\n		align: "right",\n		gap: 6,\n		height: p.get( "button_row_height", 2.125 \xD7 EM ),\n		maxheight: p.get( "button_row_height", 2.125 \xD7 EM ),\n	);\n	for ( let button in buttons ) {\n		button_row.add_child(button);\n	}\n	let w := Window(\n		title: title,\n		width: p.get( "width", 360 ),\n		height: p.get( "height", 180 ),\n		resizable: p.get( "resizable", false ),\n		modal: true,\n		VBox(\n			id: p.get( "id", null ),\n			gap: p.get( "gap", 8 ),\n			padding: p.get( "padding", 12 ),\n			body,\n			button_row,\n		),\n	);\n	w.meta( "dialogue.kind", kind );\n	return w;\n}\n\nfunction _message_body ( String message, PairList p ) {\n	return Text(\n		id: p.get( "message_id", "message" ),\n		value: message,\n		readonly: true,\n		wrap: true,\n	);\n}\n\nfunction _primary_button ( PairList p, String fallback ) {\n	return Button(\n		id: p.get( "ok_id", "ok" ),\n		text: p.get( "ok_text", fallback ),\n		variant: "primary",\n		width: p.get( "button_width", 5.5 \xD7 EM ),\n		height: p.get( "button_height", 1.75 \xD7 EM ),\n		maxheight: p.get( "button_height", 1.75 \xD7 EM ),\n	);\n}\n\nfunction _cancel_button ( PairList p ) {\n	return Button(\n		id: p.get( "cancel_id", "cancel" ),\n		text: p.get( "cancel_text", "Cancel" ),\n		width: p.get( "button_width", 5.5 \xD7 EM ),\n		height: p.get( "button_height", 1.75 \xD7 EM ),\n		maxheight: p.get( "button_height", 1.75 \xD7 EM ),\n	);\n}\n\nfunction _alert_window ( String message, PairList p ) {\n	let ok := _primary_button( p, "OK" );\n	let w := _dialogue_window(\n		"alert",\n		p.get( "title", "Alert" ),\n		_message_body( message, p ),\n		[ ok ],\n		p,\n	);\n	ok.click( function () {\n		w.close(null);\n	} );\n	return w;\n}\n\nfunction alert_window ( String message, ... PairList p ) {\n	return _alert_window( message, p );\n}\n\nfunction alert ( String message, ... PairList p ) {\n	if ( p.has("auto_result") ) {\n		return null;\n	}\n	if ( __system__{deny_gui} ) {\n		say( colour_text( message, "yellow" ) );\n		return null;\n	}\n	if ( native_alert \u2262 null ) {\n		let native_result := native_alert( message, p );\n		if ( native_result ) {\n			return null;\n		}\n	}\n	return _alert_window( message, p ).call();\n}\n\nfunction _confirm_window ( String message, PairList p ) {\n	let ok := _primary_button( p, p.get( "ok_text", "OK" ) );\n	let cancel := _cancel_button(p);\n	let w := _dialogue_window(\n		"confirm",\n		p.get( "title", "Confirm" ),\n		_message_body( message, p ),\n		[ cancel, ok ],\n		p,\n	);\n	ok.click( function () {\n		w.close(true);\n	} );\n	cancel.click( function () {\n		w.close(false);\n	} );\n	return w;\n}\n\nfunction confirm_window ( String message, ... PairList p ) {\n	return _confirm_window( message, p );\n}\n\nfunction confirm ( String message, ... PairList p ) {\n	if ( p.has("auto_result") ) {\n		return p.get("auto_result") ? true : false;\n	}\n	if ( __system__{deny_gui} ) {\n		let yes_default := p.get( "value", p.get( "default", false ) );\n		let suffix := yes_default ? " [Y/n] " : " [y/N] ";\n		let answer := readline(\n			colour_text( message _ suffix, "cyan" ),\n			yes_default ? "y" : "n",\n			null,\n		);\n		return ( answer ~ /^(?:y|yes|1|true)$/i ) ? true : false;\n	}\n	if ( native_confirm \u2262 null ) {\n		let native_result := native_confirm( message, p );\n		if ( native_result \u2262 null ) {\n			return native_result ? true : false;\n		}\n	}\n	return _confirm_window( message, p ).call() ? true : false;\n}\n\nfunction _prompt_window ( String message, PairList p ) {\n	let input := Input(\n		id: p.get( "input_id", "value" ),\n		value: p.get( "value", "" ),\n		placeholder: p.get( "placeholder", "" ),\n	);\n	let ok := _primary_button( p, p.get( "ok_text", "OK" ) );\n	let cancel := _cancel_button(p);\n	let w := _dialogue_window(\n		"prompt",\n		p.get( "title", "Prompt" ),\n		VBox(\n			gap: 6,\n			_message_body( message, p ),\n			input,\n		),\n		[ cancel, ok ],\n		p,\n	);\n	ok.click( function () {\n		w.close( input.value() );\n	} );\n	cancel.click( function () {\n		w.close(null);\n	} );\n	return w;\n}\n\nfunction prompt_window ( String message, ... PairList p ) {\n	return _prompt_window( message, p );\n}\n\nfunction prompt ( String message, ... PairList p ) {\n	if ( p.has("auto_result") ) {\n		return p.get("auto_result");\n	}\n	if ( __system__{deny_gui} ) {\n		return _tui_prompt(\n			message,\n			p,\n			_tui_string( p.get( "value", "" ) ),\n		);\n	}\n	if ( native_prompt \u2262 null ) {\n		let native_result := native_prompt( message, p );\n		if ( _gui_backend() eq "browser-dom" ) {\n			return native_result;\n		}\n		if ( native_result \u2262 null ) {\n			return native_result;\n		}\n	}\n	return _prompt_window( message, p ).call();\n}\n\nfunction _path_dialog_window (\n	String kind,\n	String title,\n	String label,\n	String default_value,\n	PairList p\n) {\n	let input := Input(\n		id: p.get( "input_id", "path" ),\n		value: p.get( "value", default_value ),\n		placeholder: p.get( "placeholder", "" ),\n		multiline: p.get( "multiple", false ),\n	);\n	let ok := _primary_button( p, p.get( "ok_text", "OK" ) );\n	let cancel := _cancel_button(p);\n	let w := _dialogue_window(\n		kind,\n		p.get( "title", title ),\n		VBox(\n			gap: 6,\n			Label( text: p.get( "label", label ), ("for"): input.id() ),\n			input,\n		),\n		[ cancel, ok ],\n		p,\n	);\n	ok.click( function () {\n		if ( p.get( "multiple", false ) ) {\n			w.close( split( input.value(), p.get( "separator", "\\n" ) ) );\n		}\n		else {\n			w.close( input.value() );\n		}\n	} );\n	cancel.click( function () {\n		w.close(null);\n	} );\n	return w;\n}\n\nfunction file_open_window ( ... PairList p ) {\n	return _path_dialog_window( "file_open", "Open File", "File:", "", p );\n}\n\nfunction file_save_window ( ... PairList p ) {\n	return _path_dialog_window( "file_save", "Save File", "File:", "", p );\n}\n\nfunction directory_open_window ( ... PairList p ) {\n	return _path_dialog_window(\n		"directory_open",\n		"Open Directory",\n		"Directory:",\n		"",\n		p,\n	);\n}\n\nfunction directory_save_window ( ... PairList p ) {\n	return _path_dialog_window(\n		"directory_save",\n		"Save Directory",\n		"Directory:",\n		"",\n		p,\n	);\n}\n\nfunction _colour_picker_window ( PairList p ) {\n	let input := Input(\n		id: p.get( "input_id", "path" ),\n		value: _colour_initial_value(p),\n		placeholder: p.get( "placeholder", "#336699" ),\n	);\n	let ok := _primary_button( p, p.get( "ok_text", "OK" ) );\n	let cancel := _cancel_button(p);\n	let default_value := _colour_default_value(p);\n	let sync_ok := function () {\n		ok.set_enabled( _parse_colour_or_null( input.value() ) \u2262 null );\n	};\n	let w := _dialogue_window(\n		"colour_picker",\n		p.get( "title", "Choose Colour" ),\n		VBox(\n			gap: 6,\n			Label(\n				text: p.get( "label", "Colour:" ),\n				("for"): input.id(),\n			),\n			input,\n		),\n		[ cancel, ok ],\n		p,\n	);\n	sync_ok();\n	input.on( "change", sync_ok );\n	ok.click( function () {\n		let parsed := _parse_colour_or_null( input.value() );\n		if ( parsed \u2262 null ) {\n			w.close(parsed);\n		}\n	} );\n	cancel.click( function () {\n		w.close(default_value);\n	} );\n	return w;\n}\n\nfunction colour_picker_window ( ... PairList p ) {\n	return _colour_picker_window(p);\n}\n\nfunction file_open ( ... PairList p ) {\n	_path_dialogue_unsupported();\n	if ( p.has("auto_result") ) {\n		return p.get("auto_result");\n	}\n	if ( __system__{deny_gui} ) {\n		return _tui_path_dialog( "File:", "", filename_completions, p );\n	}\n	return native_file_open(p);\n}\n\nfunction file_save ( ... PairList p ) {\n	_path_dialogue_unsupported();\n	if ( p.has("auto_result") ) {\n		return p.get("auto_result");\n	}\n	if ( __system__{deny_gui} ) {\n		return _tui_path_dialog( "File:", "", filename_completions, p );\n	}\n	return native_file_save(p);\n}\n\nfunction directory_open ( ... PairList p ) {\n	_path_dialogue_unsupported();\n	if ( p.has("auto_result") ) {\n		return p.get("auto_result");\n	}\n	if ( __system__{deny_gui} ) {\n		return _tui_path_dialog(\n			"Directory:",\n			"",\n			directory_completions,\n			p,\n		);\n	}\n	return native_directory_open(p);\n}\n\nfunction directory_save ( ... PairList p ) {\n	_path_dialogue_unsupported();\n	if ( p.has("auto_result") ) {\n		return p.get("auto_result");\n	}\n	if ( __system__{deny_gui} ) {\n		return _tui_path_dialog(\n			"Directory:",\n			"",\n			directory_completions,\n			p,\n		);\n	}\n	if ( native_directory_save \u2262 null ) {\n		let native_result := native_directory_save(p);\n		if ( native_result \u2262 null ) {\n			return native_result;\n		}\n		if ( _gui_backend() eq "electron-dom" ) {\n			return null;\n		}\n	}\n	return _path_dialog_window(\n		"directory_save",\n		"Save Directory",\n		"Directory:",\n		"",\n		p,\n	).call();\n}\n\nfunction colour_picker ( ... PairList p ) {\n	if ( p.has("auto_result") ) {\n		return parse_colour( _tui_string( p.get("auto_result") ) );\n	}\n	if ( __system__{deny_gui} ) {\n		return _tui_colour_dialog(p);\n	}\n	if ( native_colour_picker \u2262 null ) {\n		let native_result := native_colour_picker(p);\n		if ( native_result \u2262 null ) {\n			return parse_colour(native_result);\n		}\n		if ( _gui_backend() eq "browser-dom" ) {\n			return null;\n		}\n	}\n	if ( _gui_backend() eq "electron-dom" ) {\n		return _colour_picker_window(p).call();\n	}\n	return parse_colour( _colour_picker_window(p).call() );\n}\n';
        virtualFiles["/modules/std/uuid.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/uuid - Pure ZuzuScript UUID v1 generator.\n\n=head1 SYNOPSIS\n\n  from std/uuid import create_uuid, create_uuid_binary;\n\n  let text := create_uuid();\n  let raw := create_uuid_binary();\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module implements UUID version 1 generation using only\nZuzuScript code.\n\n=head1 EXPORTS\n\n=head2 Functions\n\n=over\n\n=item * C<create_uuid_binary()>\n\nParameters: none. Returns: C<BinaryString>. Returns a single UUID as 16\nraw bytes.\n\n=item * C<create_uuid()>\n\nParameters: none. Returns: C<String>. Returns a single UUID as\nlowercase hexadecimal text with hyphens in the usual C<8-4-4-4-12>\nlayout.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/uuid >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/math import Math;\nfrom std/string import substr;\nfrom std/string/base64 import decode;\nfrom std/time import Time;\n\nlet _B64_ALPHABET := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";\nlet _HEX_ALPHABET := "0123456789abcdef";\n\nfunction _div_floor ( Number n, Number d ) {\n	return floor( n / d );\n}\n\nfunction _mod ( Number n, Number d ) {\n	return n - _div_floor( n, d ) * d;\n}\n\nfunction _rand_int ( Number max ) {\n	return floor( Math.rand(max) );\n}\n\nfunction _bytes_to_binary ( Array bytes ) {\n	let out := "";\n	let i := 0;\n	let n := bytes.length();\n\n	while ( i < n ) {\n		let b0 := bytes[i];\n		let b1 := null;\n		let b2 := null;\n		if ( i + 1 < n ) {\n			b1 := bytes[i + 1];\n		}\n		if ( i + 2 < n ) {\n			b2 := bytes[i + 2];\n		}\n\n		let c0 := _div_floor( b0, 4 );\n		let c1 := _mod( b0, 4 ) * 16;\n		let c2 := 64;\n		let c3 := 64;\n\n		if ( b1 \u2262 null ) {\n			c1 += _div_floor( b1, 16 );\n			c2 := _mod( b1, 16 ) * 4;\n			if ( b2 \u2262 null ) {\n				c2 += _div_floor( b2, 64 );\n				c3 := _mod( b2, 64 );\n			}\n		}\n\n		out _= substr( _B64_ALPHABET, c0, 1 );\n		out _= substr( _B64_ALPHABET, c1, 1 );\n		if ( c2 \u2261 64 ) {\n			out _= "=";\n		}\n		else {\n			out _= substr( _B64_ALPHABET, c2, 1 );\n		}\n		if ( c3 \u2261 64 ) {\n			out _= "=";\n		}\n		else {\n			out _= substr( _B64_ALPHABET, c3, 1 );\n		}\n\n		i += 3;\n	}\n\n	return decode(out);\n}\n\nfunction _timestamp_words () {\n	// Seconds between 1582-10-15 and 1970-01-01.\n	let epoch_offset := 12219292800;\n	let seconds := floor( new Time().epoch() ) + epoch_offset;\n	let ticks := _rand_int(10000000);\n\n	let words := [\n		_mod( seconds, 65536 ),\n		_mod( _div_floor( seconds, 65536 ), 65536 ),\n		_mod( _div_floor( seconds, 4294967296 ), 65536 ),\n		0,\n		0,\n	];\n\n	let scale := 10000000;\n	let i := 0;\n	let carry := 0;\n	while ( i < words.length() ) {\n		let product := words[i] * scale + carry;\n		words[i] := _mod( product, 65536 );\n		carry := _div_floor( product, 65536 );\n		i++;\n	}\n\n	let add_i := 0;\n	let add_carry := ticks;\n	while ( add_carry > 0 and add_i < words.length() ) {\n		let sum := words[add_i] + _mod( add_carry, 65536 );\n		words[add_i] := _mod( sum, 65536 );\n		add_carry := _div_floor( add_carry, 65536 ) + _div_floor( sum, 65536 );\n		add_i++;\n	}\n\n	return words;\n}\n\nfunction _create_uuid_bytes () {\n	let words := _timestamp_words();\n	let time_low := words[0] + words[1] * 65536;\n	let time_mid := words[2];\n	let time_hi_and_version := _mod( words[3], 4096 ) + 4096;\n\n	let clock_seq := _rand_int(16384);\n	let clock_seq_hi_and_reserved := _mod( _div_floor( clock_seq, 256 ), 64 ) + 128;\n	let clock_seq_low := _mod( clock_seq, 256 );\n\n	let node := [];\n	let j := 0;\n	while ( j < 6 ) {\n		node.push( _rand_int(256) );\n		j++;\n	}\n	// Multicast bit set means this is not an IEEE MAC address.\n	node[0] := node[0] | 1;\n\n	return [\n		_mod( _div_floor( time_low, 16777216 ), 256 ),\n		_mod( _div_floor( time_low, 65536 ), 256 ),\n		_mod( _div_floor( time_low, 256 ), 256 ),\n		_mod( time_low, 256 ),\n		_mod( _div_floor( time_mid, 256 ), 256 ),\n		_mod( time_mid, 256 ),\n		_mod( _div_floor( time_hi_and_version, 256 ), 256 ),\n		_mod( time_hi_and_version, 256 ),\n		clock_seq_hi_and_reserved,\n		clock_seq_low,\n		node[0],\n		node[1],\n		node[2],\n		node[3],\n		node[4],\n		node[5],\n	];\n}\n\nfunction _byte_to_hex ( Number b ) {\n	let hi := _div_floor( b, 16 );\n	let lo := _mod( b, 16 );\n	return substr( _HEX_ALPHABET, hi, 1 ) _ substr( _HEX_ALPHABET, lo, 1 );\n}\n\nfunction _bytes_to_uuid_text ( Array bytes ) {\n	let out := "";\n	let i := 0;\n	while ( i < 16 ) {\n		out _= _byte_to_hex( bytes[i] );\n		if ( i \u2261 3 or i \u2261 5 or i \u2261 7 or i \u2261 9 ) {\n			out _= "-";\n		}\n		i++;\n	}\n	return out;\n}\n\nfunction create_uuid_binary () {\n	return _bytes_to_binary( _create_uuid_bytes() );\n}\n\nfunction create_uuid () {\n	return _bytes_to_uuid_text( _create_uuid_bytes() );\n}\n';
        virtualFiles["/modules/std/dump.zzm"] = `=encoding utf8

=head1 NAME

std/dump - Structured value dumper for ZuzuScript.

=head1 SYNOPSIS

  from std/dump import Dumper;

  let text := Dumper.dump(
    { nums: [ 1, 2, 3 ] },
    { pretty: true, sort_keys: true }
  );

=head1 IMPLEMENTATION SUPPORT

This module is supported by all implementations of ZuzuScript.

=head1 DESCRIPTION

This module provides a pure-Zuzu C<Dumper> class which serializes
Zuzu values into code-like text.

If a value cannot be realistically dumped (for example a function),
C<Dumper> emits a warning and inserts C<null> in that location.

=head1 EXPORTS

=head2 Classes

=over

=item C<Dumper>

Pure-Zuzu structured value dumper.

=over

=item C<< Dumper.dump(value, options?) >>

Parameters: C<value> is any ZuzuScript value and C<options> is an
optional dictionary. Returns: C<String>. Serializes C<value> into
code-like text.

=back

=back

=head1 COPYRIGHT AND LICENCE

B<< std/dump >> is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under
the terms of either the Artistic License 1.0 or the GNU General Public
License version 2.

=cut

from std/internals import class_name, object_slots, ansi_esc, ref_id;
from std/string import join, substr;

let _ANSI_RESET := ansi_esc() _ "[0m";
let _ANSI_NUMBER := ansi_esc() _ "[33m";
let _ANSI_STRING := ansi_esc() _ "[32m";
let _ANSI_BOOL := ansi_esc() _ "[35m";
let _ANSI_NULL := ansi_esc() _ "[90m";
let _ANSI_PUNC := ansi_esc() _ "[36m";
let _ANSI_KEYWORD := ansi_esc() _ "[34m";

function _is_true (value) {
	return value ? true: false;
}

function _warn_unless_quiet ( String msg, Dict cfg ) {
	warn msg if not cfg{quiet};
}

function _indent_pad ( depth, cfg ) {
	return "" if not cfg{pretty};
	let out := "";
	let i := 0;
	while ( i < depth ) {
		out _= "  ";
		i++;
	}

	return out;
}

function _colourize ( String text, String tone, Dict cfg ) {
	return text if not cfg{colour};
	return tone _ text _ _ANSI_RESET;
}

function _punc ( String text, Dict cfg ) {
	return _colourize( text, _ANSI_PUNC, cfg );
}

function _quote ( String text, Dict cfg ) {
	let s := text;
	s := "" if s \u2261 null;
	let out := "";
	let i := 0;
	let n := length s;

	while ( i < n ) {
		let ch := substr( s, i, 1 );
		if ( ch \u2261 "\\\\" ) {
			out _= "\\\\\\\\";
		}
		else if ( ch \u2261 "\\"" ) {
			out _= "\\\\\\"";
		}
		else if ( ch \u2261 "\\n" ) {
			out _= "\\\\n";
		}
		else if ( ch \u2261 "\\r" ) {
			out _= "\\\\r";
		}
		else if ( ch \u2261 "\\t" ) {
			out _= "\\\\t";
		}
		else {
			out _= ch;
		}
		i++;
	}

	return _colourize( "\\"" _ out _ "\\"", _ANSI_STRING, cfg );
}

function _keys_for ( Dict d, Dict cfg ) {
	return cfg{sort_keys} ? d.sorted_keys(): d.keys();
}

function _null_literal ( Dict cfg ) {
	return _colourize( "null", _ANSI_NULL, cfg );
}

function _seen_check_and_mark ( value, String label, Dict cfg, Dict state ) {
	let id := ref_id(value);
	if ( id \u2262 null and state{seen}.exists(id) ) {
		_warn_unless_quiet( "Dumper: recursive " _ label _ " detected; dumping null", cfg );
		return true;
	}
	if ( id \u2262 null ) {
		state{seen}.set( id, true );
	}

	return false;
}

function _dump_value ( value, Dict cfg, Dict state, Number depth ) {
	if ( value instanceof Null ) {
		return _null_literal(cfg);
	}
	if ( value instanceof Boolean ) {
		return _colourize( value ? "true": "false", _ANSI_BOOL, cfg );
	}
	if ( value instanceof Number ) {
		return _colourize( "" _ value, _ANSI_NUMBER, cfg );
	}
	if ( value instanceof String ) {
		return _quote( value, cfg );
	}

	if ( value instanceof Array ) {
		return _null_literal(cfg) if _seen_check_and_mark( value, "array", cfg, state );
		if ( value.length() \u2261 0 ) {
			return _punc( "[", cfg ) _ _punc( "]", cfg );
		}
		let pretty := cfg{pretty};
		let sep := pretty ? _punc( ",\\n", cfg ): _punc(",", cfg );
		let parts := [];
		for ( let item in value ) {
			parts.push( _dump_value( item, cfg, state, depth + 1 ) );
		}
		if ( not pretty ) {
			return _punc( "[", cfg ) _ join( sep, parts ) _ _punc( "]", cfg );
		}
		let inner := [];
		for ( let p in parts ) {
			inner.push( _indent_pad( depth + 1, cfg ) _ p );
		}
		return _punc( "[\\n", cfg ) _ join( sep, inner ) _ _punc( "\\n", cfg ) _ _indent_pad( depth, cfg ) _
		    _punc( "]", cfg );
	}

	if ( value instanceof Dict ) {
		return _null_literal(cfg) if _seen_check_and_mark( value, "dict", cfg, state );
		let keys := _keys_for( value, cfg );
		if ( keys.length() \u2261 0 ) {
			return _punc( "{" , cfg ) _ _punc( "}", cfg );
		}
		let pretty := cfg{pretty};
		let sep := pretty ? _punc( ",\\n", cfg ): _punc(",", cfg );
		let colon := pretty ? _punc( ": ", cfg ): _punc(":", cfg );
		let entries := [];
		for ( let key in keys ) {
			let dumped := _dump_value( value.get(key), cfg, state, depth + 1 );
			entries.push( _quote( key, cfg ) _ colon _ dumped );
		}
		if ( not pretty ) {
			return _punc( "{" , cfg ) _ join( sep, entries ) _ _punc( "}", cfg );
		}
		let inner := [];
		for ( let e in entries ) {
			inner.push( _indent_pad( depth + 1, cfg ) _ e );
		}
		return _punc( "{\\n", cfg ) _ join( sep, inner ) _ _punc( "\\n", cfg ) _ _indent_pad( depth, cfg ) _
		    _punc( "}", cfg );
	}

	if ( value instanceof PairList ) {
		return _null_literal(cfg) if _seen_check_and_mark( value, "pairlist", cfg, state );
		if ( value.empty ) {
			return _punc( "{{" , cfg ) _ _punc( "}}", cfg );
		}
		let pretty := cfg{pretty};
		let sep := pretty ? _punc( ",\\n", cfg ): _punc(",", cfg );
		let colon := pretty ? _punc( ": ", cfg ): _punc(":", cfg );
		let entries := [];
		value.for_each_pair( function (p) {
			let dumped := _dump_value( p.value, cfg, state, depth + 1 );
			entries.push( _quote( p.key, cfg ) _ colon _ dumped );
		} );
		if ( not pretty ) {
			return _punc( "{{" , cfg ) _ join( sep, entries ) _ _punc( "}}", cfg );
		}
		let inner := [];
		for ( let e in entries ) {
			inner.push( _indent_pad( depth + 1, cfg ) _ e );
		}
		return _punc( "{{\\n", cfg ) _ join( sep, inner ) _ _punc( "\\n", cfg ) _ _indent_pad( depth, cfg ) _
		    _punc( "}}", cfg );
	}

	if ( value instanceof Set or value instanceof Bag ) {
		let is_set := value instanceof Set;
		return _null_literal(cfg)
			if _seen_check_and_mark( value, is_set ? "set" : "bag", cfg, state );
		let left := is_set ? "<<": "<<<";
		let right := is_set ? ">>": ">>>";
		let sep := cfg{pretty} ? _punc( ", ", cfg ): _punc(",", cfg );
		let items := [];
		for ( let item in value ) {
			items.push( _dump_value( item, cfg, state, depth + 1 ) );
		}
		return _punc( left, cfg ) _ join( sep, items ) _ _punc( right, cfg );
	}

	if ( value instanceof Pair ) {
		let pair_value := value{pair};
		if ( not( pair_value instanceof Array ) or pair_value.length() < 2 ) {
			_warn_unless_quiet( "Dumper: invalid Pair shape; using null", cfg );
			return _null_literal(cfg);
		}
		let first := _dump_value( pair_value[0], cfg, state, depth + 1 );
		let second := _dump_value( pair_value[1], cfg, state, depth + 1 );
		let body := _punc( "[", cfg ) _ first _ _punc(",", cfg ) _ second _ _punc( "]", cfg );
		let kw_new := _colourize( "new", _ANSI_KEYWORD, cfg );
		return kw_new _ " Pair" _ _punc("(", cfg ) _ "pair" _ _punc(":", cfg ) _ body _ _punc(")", cfg );
	}

	if (
		value instanceof Function or
		value instanceof Class or
		typeof value \u2261 "Regexp" or
		typeof value \u2261 "Method"
	) {
		let t := typeof value;
		_warn_unless_quiet( "Dumper: value of type '" _ t _ "' is not dumpable; using null", cfg, );
		return _null_literal(cfg);
	}
	return _null_literal(cfg) if _seen_check_and_mark( value, "object", cfg, state );
	let cname := class_name(value);
	let slots := object_slots(value);
	if ( cname \u2261 null or not( slots instanceof Dict ) ) {
		_warn_unless_quiet( "Dumper: object internals unavailable; dumping null", cfg );
		return _null_literal(cfg);
	}
	let keys := _keys_for( slots, cfg );
	let colon := cfg{pretty} ? _punc( ": ", cfg ): _punc(":", cfg );
	let args := [];
	for ( let key in keys ) {
		args.push( key _ colon _ _dump_value( slots.get(key), cfg, state, depth + 1 ) );
	}
	let kw_new := _colourize( "new", _ANSI_KEYWORD, cfg );
	if ( args.length() \u2261 0 ) {
		return kw_new _ " " _ cname _ _punc( "()", cfg );
	}
	if ( not cfg{pretty} ) {
		return kw_new _ " " _ cname _ _punc("(", cfg ) _ join( _punc(",", cfg ), args ) _ _punc(")", cfg );
	}
	let inner := [];
	for ( let arg in args ) {
		inner.push( _indent_pad( depth + 1, cfg ) _ arg );
	}
	return kw_new _ " " _ cname _ _punc( "(\\n", cfg ) _ join( _punc( ",\\n", cfg ), inner ) _ _punc( "\\n",
	    cfg ) _ _indent_pad( depth, cfg ) _ _punc(")", cfg );
}

class Dumper {

	static method dump ( value, options? ) {
		let cfg := { pretty: false, sort_keys: false, colour: false, quiet: false };
		if ( options instanceof Dict ) {
			cfg{pretty} := _is_true( options{pretty} ) if "pretty" in options;
			cfg{sort_keys} := _is_true( options{sort_keys} ) if "sort_keys" in options;
			cfg{colour} := _is_true( options{colour} ) if "colour" in options;
			cfg{quiet} := _is_true( options{quiet} ) if "quiet" in options;
		}
		return _dump_value( value, cfg, { seen: {} }, 0 );
	}

}
`;
        virtualFiles["/modules/std/data/cbor.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/data/cbor - CBOR encoding and decoding for ZuzuScript.\n\n=head1 SYNOPSIS\n\n  from std/data/cbor import CBOR, TaggedValue;\n\n  let codec := new CBOR();\n  let bytes := codec.encode({ answer: 42 });\n  let value := codec.decode(bytes);\n\n  // Decode CBOR maps to Zuzu PairLists instead of Dicts.\n  // This preserves key order and allows duplicate keys.\n  codec := new CBOR( pairlists: true );\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Node and\nElectron. It is partially supported by zuzu-js in the browser: in-memory\nCBOR encode/decode coverage passes, but file-backed load/dump coverage is\nunsupported because browser filesystem capability is unavailable.\n\n=head1 DESCRIPTION\n\nPure-Zuzu implementation of CBOR (RFC 8949).\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<< TaggedValue({ tag: Number, value: value }) >>\n\nConstructs a tagged CBOR value. Returns: C<TaggedValue>. Stores the CBOR\ntag number and associated value.\n\n=item C<< CBOR({ pairlists?: Boolean }) >>\n\nConstructs a CBOR codec. Returns: C<CBOR>. The C<pairlists> option makes\ndecoded maps return as C<PairList> values instead of C<Dict> values.\n\n=over\n\n=item C<< codec.encode(value) >>\n\nParameters: C<value> is any CBOR-encodable ZuzuScript value. Returns:\nC<BinaryString>. Encodes C<value> as CBOR bytes.\n\n=item C<< codec.encode_binarystring(value) >>\n\nAlias for C<codec.encode(value)>.\n\n=item C<< codec.decode(BinaryString raw) >>\n\nParameters: C<raw> is CBOR data. Returns: value. Decodes CBOR bytes into\nthe equivalent ZuzuScript value.\n\n=item C<< codec.decode_binarystring(BinaryString raw) >>\n\nAlias for C<codec.decode(raw)>.\n\n=item C<< codec.load(Path path) >>\n\nParameters: C<path> is a C<std/io> C<Path>. Returns: value. Reads CBOR\nbytes from C<path> and decodes them.\n\n=item C<< codec.dump(Path path, value) >>\n\nParameters: C<path> is a C<std/io> C<Path> and C<value> is any\nCBOR-encodable value. Returns: C<null>. Encodes C<value> and writes CBOR\nbytes to C<path>.\n\n=back\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/data/cbor >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/string import substr, index;\nfrom std/string/base64 import encode, decode;\nfrom std/time import Time;\n\n\nlet _B64_ALPHABET  := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";\n\n// Set to "PairList" to return CBOR objects as Zuzu PairLists.\nlet _DECODE_MAP_AS := "Dict";\n\nclass TaggedValue {\n	let Number tag;\n	let value;\n}\n\nfunction _div_floor ( Number n, Number d ) {\n	return floor( n / d ); // fix syntax highlighting\n}\n\nfunction _mod ( Number n, Number d ) {\n	return n - _div_floor( n, d ) * d;\n}\n\nfunction _bytes_to_binary ( Array bytes ) {\n	let out := "";\n	let i := 0;\n	let n := bytes.length();\n\n	while ( i < n ) {\n		let b0 := bytes[i];\n		let b1 := null;\n		let b2 := null;\n		if ( i + 1 < n ) {\n			b1 := bytes[i + 1];\n		}\n		if ( i + 2 < n ) {\n			b2 := bytes[i + 2];\n		}\n\n		let c0 := _div_floor( b0, 4 );\n		let c1 := _mod( b0, 4 ) * 16;\n		let c2 := 64;\n		let c3 := 64;\n\n		if ( b1 \u2262 null ) {\n			c1 += _div_floor( b1, 16 );\n			c2 := _mod( b1, 16 ) * 4;\n			if ( b2 \u2262 null ) {\n				c2 += _div_floor( b2, 64 );\n				c3 := _mod( b2, 64 );\n			}\n		}\n\n		out _= substr( _B64_ALPHABET, c0, 1 );\n		out _= substr( _B64_ALPHABET, c1, 1 );\n		if ( c2 \u2261 64 ) {\n			out _= "=";\n		}\n		else {\n			out _= substr( _B64_ALPHABET, c2, 1 );\n		}\n		if ( c3 \u2261 64 ) {\n			out _= "=";\n		}\n		else {\n			out _= substr( _B64_ALPHABET, c3, 1 );\n		}\n		i += 3;\n	}\n\n	return decode(out);\n}\n\nfunction _binary_to_bytes ( BinaryString raw ) {\n	let b64 := encode(raw);\n	let out := [];\n	let i := 0;\n	let n := length b64;\n\n	while ( i < n ) {\n		let c0 := index( _B64_ALPHABET, substr( b64, i, 1 ) );\n		let c1 := index( _B64_ALPHABET, substr( b64, i + 1, 1 ) );\n		let ch2 := substr( b64, i + 2, 1 );\n		let ch3 := substr( b64, i + 3, 1 );\n		let c2 := -1;\n		let c3 := -1;\n		if ( ch2 \u2262 "=" ) {\n			c2 := index( _B64_ALPHABET, ch2 );\n		}\n		if ( ch3 \u2262 "=" ) {\n			c3 := index( _B64_ALPHABET, ch3 );\n		}\n\n		out.push( c0 * 4 + _div_floor( c1, 16 ) );\n\n		if ( c2 >= 0 ) {\n			out.push( _mod( c1, 16 ) * 16 + _div_floor( c2, 4 ) );\n		}\n		if ( c3 >= 0 ) {\n			out.push( _mod( c2, 4 ) * 64 + c3 );\n		}\n\n		i += 4;\n	}\n\n	return out;\n}\n\nfunction _is_int ( value ) {\n	if ( not( value instanceof Number ) ) {\n		return false;\n	}\n\n	return _mod( value, 1 ) \u2261 0;\n}\n\nfunction _emit_uint ( Array out, Number major, Number n ) {\n	if ( n < 24 ) {\n		out.push( major * 32 + n );\n		return;\n	}\n	if ( n < 256 ) {\n		out.push( major * 32 + 24 );\n		out.push(n);\n		return;\n	}\n	if ( n < 65536 ) {\n		out.push( major * 32 + 25 );\n		out.push( _mod( _div_floor( n, 256 ), 256 ) );\n		out.push( _mod( n, 256 ) );\n		return;\n	}\n	if ( n < 4294967296 ) {\n		out.push( major * 32 + 26 );\n		out.push( _mod( _div_floor( n, 16777216 ), 256 ) );\n		out.push( _mod( _div_floor( n, 65536 ), 256 ) );\n		out.push( _mod( _div_floor( n, 256 ), 256 ) );\n		out.push( _mod( n, 256 ) );\n		return;\n	}\n\n	let hi := _div_floor( n, 4294967296 );\n	let lo := _mod( n, 4294967296 );\n	out.push( major * 32 + 27 );\n	out.push( _mod( _div_floor( hi, 16777216 ), 256 ) );\n	out.push( _mod( _div_floor( hi, 65536 ), 256 ) );\n	out.push( _mod( _div_floor( hi, 256 ), 256 ) );\n	out.push( _mod( hi, 256 ) );\n	out.push( _mod( _div_floor( lo, 16777216 ), 256 ) );\n	out.push( _mod( _div_floor( lo, 65536 ), 256 ) );\n	out.push( _mod( _div_floor( lo, 256 ), 256 ) );\n	out.push( _mod( lo, 256 ) );\n}\n\nfunction _encode_value ( Array out, value ) {\n	if ( value \u2261 null ) {\n		out.push(246);\n		return;\n	}\n	if ( value \u2261 true ) {\n		out.push(245);\n		return;\n	}\n	if ( value \u2261 false ) {\n		out.push(244);\n		return;\n	}\n\n	if ( value instanceof Number ) {\n		die "CBOR.encode currently supports only integer Number values" if not _is_int(value);\n		if ( value >= 0 ) {\n			_emit_uint( out, 0, value );\n		}\n		else {\n			_emit_uint( out, 1, -1 - value );\n		}\n		return;\n	}\n\n	if ( value instanceof BinaryString ) {\n		let b := _binary_to_bytes(value);\n		_emit_uint( out, 2, b.length() );\n		let i := 0;\n		while ( i < b.length() ) {\n			out.push( b[i] );\n			i++;\n		}\n		return;\n	}\n\n	if ( value instanceof String ) {\n		let b := _binary_to_bytes( to_binary(value) );\n		_emit_uint( out, 3, b.length() );\n		let i := 0;\n		while ( i < b.length() ) {\n			out.push( b[i] );\n			i++;\n		}\n		return;\n	}\n\n	if ( value instanceof Array ) {\n		_emit_uint( out, 4, value.length() );\n		let i := 0;\n		while ( i < value.length() ) {\n			_encode_value( out, value[i] );\n			i++;\n		}\n		return;\n	}\n\n	if ( value instanceof Set ) {\n		_emit_uint( out, 6, 258 );\n		_encode_value( out, value.sortstr() );\n		return;\n	}\n\n	if ( value instanceof Bag ) {\n		_encode_value( out, value.sortstr() );\n		return;\n	}\n\n	if ( value instanceof PairList ) {\n		let pairs := value.to_Array();\n		_emit_uint( out, 5, pairs.length() );\n		let i := 0;\n		while ( i < pairs.length() ) {\n			let pair := pairs[i]{pair};\n			_encode_value( out, pair[0] );\n			_encode_value( out, pair[1] );\n			i++;\n		}\n		return;\n	}\n\n	if ( value instanceof Dict ) {\n		let keys := value.sorted_keys();\n		_emit_uint( out, 5, keys.length() );\n		let i := 0;\n		while ( i < keys.length() ) {\n			let k := keys[i];\n			_encode_value( out, k );\n			_encode_value( out, value.get(k) );\n			i++;\n		}\n		return;\n	}\n\n	if ( value instanceof TaggedValue ) {\n		_emit_uint( out, 6, value { tag } );\n		_encode_value( out, value { value } );\n		return;\n	}\n	if ( value instanceof Time ) {\n		_emit_uint( out, 6, 0 );\n		_encode_value( out, value.epoch() );\n		return;\n	}\n\n	die `CBOR cannot encode value of type ${typeof value}`;\n}\n\nfunction _read_uint ( Array bytes, Number ai, Number pos ) {\n	if ( ai < 24 ) {\n		return [ ai, pos ];\n	}\n	if ( ai \u2261 24 ) {\n		return [ bytes[pos], pos + 1 ];\n	}\n	if ( ai \u2261 25 ) {\n		return [ bytes[pos] * 256 + bytes[pos + 1], pos + 2 ];\n	}\n	if ( ai \u2261 26 ) {\n		return [ bytes[pos] * 16777216 + bytes[pos + 1] * 65536 + bytes[pos + 2] * 256 + bytes[pos + 3], pos + 4 ];\n	}\n	if ( ai \u2261 27 ) {\n		let hi := bytes[pos] * 16777216 + bytes[pos + 1] * 65536 + bytes[pos + 2] * 256 + bytes[pos + 3];\n		let lo := bytes[pos + 4] * 16777216 + bytes[pos + 5] * 65536 + bytes[pos + 6] * 256 + bytes[pos + 7];\n		return [ hi * 4294967296 + lo, pos + 8 ];\n	}\n\n	die `Unsupported CBOR additional info: ${ai}`;\n}\n\nfunction _decode_at ( Array bytes, Number pos ) {\n	let head := bytes[pos];\n	let major := _div_floor( head, 32 );\n	let ai := _mod( head, 32 );\n	let parsed := _read_uint( bytes, ai, pos + 1 );\n	let arg := parsed[0];\n	let p := parsed[1];\n\n	if ( major \u2261 0 ) {\n		return [ arg, p ];\n	}\n	if ( major \u2261 1 ) {\n		return [ -1 - arg, p ];\n	}\n	if ( major \u2261 2 ) {\n		let chunk := [];\n		let i := 0;\n		while ( i < arg ) {\n			chunk.push( bytes[p + i] );\n			i++;\n		}\n		return [ _bytes_to_binary(chunk), p + arg ];\n	}\n	if ( major \u2261 3 ) {\n		let chunk := [];\n		let i := 0;\n		while ( i < arg ) {\n			chunk.push( bytes[p + i] );\n			i++;\n		}\n		return [ to_string( _bytes_to_binary(chunk) ), p + arg ];\n	}\n	if ( major \u2261 4 ) {\n		let arr := [];\n		let i := 0;\n		let q := p;\n		while ( i < arg ) {\n			let item := _decode_at( bytes, q );\n			arr.push( item[0] );\n			q := item[1];\n			i++;\n		}\n		return [ arr, q ];\n	}\n	if ( major \u2261 5 ) {\n		let d := _DECODE_MAP_AS eq "PairList" ? new PairList() : new Dict();\n		let i := 0;\n		let q := p;\n		while ( i < arg ) {\n			let k := _decode_at( bytes, q );\n			let v := _decode_at( bytes, k[1] );\n			d.add( k[0], v[0] ) unless _DECODE_MAP_AS eq "Dict" and d.exists( k[0] );\n			q := v[1];\n			i++;\n		}\n		return [ d, q ];\n	}\n	if ( major \u2261 6 ) {\n		let tagged := _decode_at( bytes, p );\n		if ( arg \u2261 0 and tagged[0] instanceof Number ) {\n			return [ new Time( tagged[0] ), tagged[1] ];\n		}\n		if ( arg \u2261 258 and tagged[0] instanceof Array ) {\n			return [ tagged[0].to_Set(), tagged[1] ];\n		}\n		return [ new TaggedValue( tag: arg, value: tagged[0] ), tagged[1] ];\n	}\n	if ( major \u2261 7 ) {\n		if ( ai \u2261 20 ) {\n			return [ false, pos + 1 ];\n		}\n		if ( ai \u2261 21 ) {\n			return [ true, pos + 1 ];\n		}\n		if ( ai \u2261 22 ) {\n			return [ null, pos + 1 ];\n		}\n		die `Unsupported CBOR simple/float value (ai=${ai})`;\n	}\n\n	die `Unsupported CBOR major type: ${major}`;\n}\n\nclass CBOR {\n	let pairlists := false;\n\n	method encode ( value ) {\n		let out := [];\n		_encode_value( out, value );\n		return _bytes_to_binary(out);\n	}\n\n	method encode_binarystring ( value ) {\n		return self.encode(value);\n	}\n\n	method decode ( BinaryString raw ) {\n		_DECODE_MAP_AS := pairlists ? "PairList" : "Dict";\n		let bytes := _binary_to_bytes(raw);\n		let parsed := _decode_at( bytes, 0 );\n		die "Trailing bytes after CBOR value" if parsed[1] < bytes.length();\n		return parsed[0];\n	}\n\n	method decode_binarystring ( BinaryString raw ) {\n		return self.decode(raw);\n	}\n\n	method load ( path ) {\n		from std/io import Path;\n		die "CBOR.load is denied by runtime policy" if __system__{deny_fs};\n		die "CBOR.load expects a std/io Path object" if not( path instanceof Path );\n		return self.decode( path.slurp() );\n	}\n\n	method dump ( path, value ) {\n		from std/io import Path;\n		die "CBOR.dump is denied by runtime policy" if __system__{deny_fs};\n		die "CBOR.dump expects a std/io Path object" if not( path instanceof Path );\n		path.spew( self.encode(value) );\n		return path;\n	}\n}\n';
        virtualFiles["/modules/std/data/kdl.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/data/kdl - KDL parsing and serialization for ZuzuScript.\n\n=head1 SYNOPSIS\n\n  from std/data/kdl import KDL;\n\n  let kdl := new KDL();\n  let doc := kdl.decode("""\n    package name="zuzu" { version "0.1.0" }\n  """);\n  let text := kdl.encode(doc);\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Node and\nElectron. It is partially supported by zuzu-js in the browser: in-memory\nKDL parsing and serialization coverage passes, but fixture and load/dump\ncoverage is unsupported because browser filesystem capability is\nunavailable.\n\n=head1 DESCRIPTION\n\nThis module provides a pure-Zuzu implementation of the KDL document\nmodel and parser, with a user-facing API modelled on C<std/data/json>.\n\n=head1 EXPORTS\n\nThe parser returns explicit KDL model objects rather than generic Dict\nand Array structures.\n\n=head2 C<KDLDocument>\n\nC<KDLDocument> represents a complete parsed KDL document.\n\nConstructor fields:\n\n=over\n\n=item * C<nodes>\n\nAn Array of top-level C<KDLNode> objects. Defaults to an empty Array.\n\n=back\n\nMethods:\n\n=over\n\n=item C<nodes()>\n\nParameters: none. Returns: C<Array>. Returns the Array of top-level\nC<KDLNode> objects.\n\n=item C<to_Iterator()>\n\nParameters: none. Returns: C<Function>. Returns an iterator over the\ndocument\'s top-level nodes.\n\n=back\n\n=head2 C<KDLNode>\n\nC<KDLNode> represents one KDL node.\n\nConstructor fields:\n\n=over\n\n=item * C<name>\n\nThe node name as a String.\n\n=item * C<type_annotation>\n\nThe node type annotation as a String, or C<null> when unannotated.\n\n=item * C<args>\n\nAn Array of unnamed argument C<KDLValue> objects. Defaults to an empty\nArray.\n\n=item * C<props>\n\nA C<PairList> mapping property names to C<KDLValue> objects. Defaults\nto an empty C<PairList>, and preserves duplicate property names.\n\n=item * C<children>\n\nAn Array of child C<KDLNode> objects. Defaults to an empty Array.\n\n=back\n\nMethods:\n\n=over\n\n=item C<name()>\n\nParameters: none. Returns: C<String>. Returns the node name.\n\n=item C<type_annotation()>\n\nParameters: none. Returns: C<String> or C<null>. Returns the node type\nannotation.\n\n=item C<args()>\n\nParameters: none. Returns: C<Array>. Returns the unnamed argument\nC<KDLValue> objects.\n\n=item C<props()>\n\nParameters: none. Returns: C<PairList>. Returns the named property\nC<KDLValue> objects.\n\n=item C<children()>\n\nParameters: none. Returns: C<Array>. Returns the child C<KDLNode>\nobjects.\n\n=item C<to_Iterator()>\n\nParameters: none. Returns: C<Function>. Returns an iterator over the\nnode\'s arguments followed by its child nodes.\n\n=back\n\n=head2 C<KDLValue>\n\nC<KDLValue> represents an unnamed argument or named property value.\n\nConstructor fields:\n\n=over\n\n=item * C<type>\n\nThe KDL value type: C<null>, C<boolean>, C<number>, or C<string>.\nSome conversion helpers may create opaque C<KDLValue> objects with\nother type names; those are not KDL primitives.\n\n=item * C<kind>\n\nFor numbers, one of C<integer>, C<float>, or C<string>. C<string> is\nused for KDL number keywords such as C<#inf> that do not have a native\nJSON-like numeric value.\n\n=item * C<value>\n\nThe raw native value.\n\n=item * C<type_annotation>\n\nThe value type annotation as a String, or C<null> when unannotated.\n\n=item * C<canonical_number>\n\nThe canonical numeric spelling used by canonical serialization, or\nC<null>.\n\n=back\n\nMethods:\n\n=over\n\n=item C<type()>\n\nParameters: none. Returns: C<String>. Returns the value type.\n\n=item C<kind()>\n\nParameters: none. Returns: C<String> or C<null>. Returns the numeric\nkind for number values.\n\n=item C<value()>\n\nParameters: none. Returns: value. Returns the raw native value.\n\n=item C<type_annotation()>\n\nParameters: none. Returns: C<String> or C<null>. Returns the value type\nannotation.\n\n=item C<canonical_number()>\n\nParameters: none. Returns: C<String> or C<null>. Returns the canonical\nnumeric spelling.\n\n=item C<is_null()>, C<is_boolean()>, C<is_number()>, C<is_string()>\n\nParameters: none. Returns: C<Boolean>. Predicate methods for the four\nKDL primitive value types.\n\n=item C<is_true()>, C<is_false()>\n\nParameters: none. Returns: C<Boolean>. Predicate methods for boolean\nC<#true> and C<#false> values.\n\n=item C<to_Number()>\n\nParameters: none. Returns: C<Number>. Returns the native number, or\nthrows when the value is not a finite native number.\n\n=item C<to_String()>\n\nParameters: none. Returns: C<String>. Coerces the value to a string.\n\n=item C<to_Boolean()>\n\nParameters: none. Returns: C<Boolean>. Coerces the value to a boolean.\n\n=item C<native_value()>\n\nParameters: none. Returns: value. Returns the raw native value, with KDL\nC<#null> represented as C<null>.\n\n=back\n\n=head2 C<KDL>\n\nC<KDL> is the codec class for KDL text.\n\n=over\n\n=item C<< codec.decode(String text) >>\n\nParameters: C<text> is KDL text. Returns: C<KDLDocument>. Parses KDL\ntext.\n\n=item C<< codec.decode_binarystring(BinaryString bytes) >>\n\nParameters: C<bytes> is UTF-8 KDL bytes. Returns: C<KDLDocument>.\nParses KDL bytes.\n\n=item C<< codec.encode(value) >>\n\nParameters: C<value> is a C<KDLDocument>, C<KDLNode>, or compatible\nvalue. Returns: C<String>. Serializes KDL data to text.\n\n=item C<< codec.encode_binarystring(value) >>\n\nParameters: C<value> is a C<KDLDocument>, C<KDLNode>, or compatible\nvalue. Returns: C<BinaryString>. Serializes KDL data to UTF-8 bytes.\n\n=item C<< codec.load(path) >>\n\nParameters: C<path> is a C<std/io> C<Path>. Returns: C<KDLDocument>.\nReads and parses a KDL file.\n\n=item C<< codec.dump(path, value) >>\n\nParameters: C<path> is a C<std/io> C<Path> and C<value> is KDL data.\nReturns: C<null>. Serializes and writes a KDL file.\n\n=back\n\n=head1 ZPATH\n\nC<KDLDocument>, C<KDLNode>, and C<KDLValue> objects can be queried with\nC<std/path/z>. A KDL document\'s top-level nodes are exposed as children.\nA KDL node exposes its arguments first, then its child nodes, as ZPath\nchildren. KDL properties are exposed as ZPath attributes.\n\n  from std/data/kdl import KDL;\n  from std/path/z import ZPath;\n\n  let doc := ( new KDL() ).decode( """\n  (pkg)package "zuzu" (email)"dev@example.test" version="0.1.0" {\n    foo "first"\n    bar "middle"\n    foo "second"\n    foo "third"\n  }\n  """ );\n\n  // The package node\'s first child is its first argument.\n  say( ( new ZPath( path: "/package/#0" ) ).first(doc) );       // zuzu\n\n  // Properties are attributes.\n  say( ( new ZPath( path: "/package/@version" ) ).first(doc) ); // 0.1.0\n\n  // Child nodes can be selected by name and zero-based occurrence.\n  say( ( new ZPath( path: "/package/foo#2/#0" ) ).first(doc) ); // third\n\n  // tag() exposes type annotations on nodes and values.\n  say( ( new ZPath( path: "tag(/package)" ) ).first(doc) );     // pkg\n  say( ( new ZPath( path: "tag(/package/#1)" ) ).first(doc) );  // email\n\n  // local-name() exposes the node name, like it does for XML elements.\n  say( ( new ZPath( path: "local-name(/package)" ) ).first(doc) );\n  say( ( new ZPath( path: "/package/foo#2/local-name()" ) ).first(doc) );\n\n=head1 COMPATIBILITY\n\nThe parser is recursive descent and covers the usual KDL 2.0 document\nmodel: nodes, arguments, properties, annotations, comments, slashdash,\nstrings, booleans, nulls, numbers, and children.\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/data/kdl >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/string import substr, index, chr, ord, sprint;\n\n\nfunction _kdl_starts_with ( String text, Number pos, String prefix ) {\n	return substr( text, pos, length prefix ) \u2261 prefix;\n}\n\nfunction _kdl_is_newline ( String ch ) {\n	return ch \u2261 "\\n" or ch \u2261 "\\r" or ch \u2261 chr(11)\n		or ch \u2261 chr(133) or ch \u2261 chr(8232) or ch \u2261 chr(8233);\n}\n\nfunction _kdl_is_ws ( String ch ) {\n	return false if ch \u2261 "";\n	let code := ord(ch);\n	return ch \u2261 " " or ch \u2261 "\\t" or ch \u2261 chr(12)\n		or code \u2261 160 or code \u2261 5760 or code \u2261 8239\n		or code \u2261 8287 or code \u2261 12288\n		or ( code >= 8192 and code <= 8202 );\n}\n\nfunction _kdl_is_line_space ( String ch ) {\n	return _kdl_is_ws(ch) or _kdl_is_newline(ch);\n}\n\nfunction _kdl_is_digit ( String ch ) {\n	return ch ~ /^[0-9]$/;\n}\n\nfunction _kdl_is_hex_digit ( String ch ) {\n	return ch ~ /^[0-9a-fA-F]$/;\n}\n\nfunction _kdl_hex_value ( String ch ) {\n	if ( _kdl_is_digit(ch) ) {\n		return ch + 0;\n	}\n	if ( index( "abcdef", ch ) >= 0 ) {\n		return 10 + index( "abcdef", ch );\n	}\n	if ( index( "ABCDEF", ch ) >= 0 ) {\n		return 10 + index( "ABCDEF", ch );\n	}\n	die `Invalid hexadecimal digit \'${ch}\'`;\n}\n\nfunction _kdl_from_hex ( String raw ) {\n	let n := 0;\n	let i := 0;\n	while ( i < length raw ) {\n		n := n * 16 + _kdl_hex_value( substr( raw, i, 1 ) );\n		i++;\n	}\n	return n;\n}\n\nfunction _kdl_clean_number ( String token ) {\n	let out := "";\n	let i := 0;\n	while ( i < length token ) {\n		let ch := substr( token, i, 1 );\n		out _= ch if ch \u2262 "_";\n		i++;\n	}\n	return out;\n}\n\nfunction _kdl_parse_radix ( String token, Number radix ) {\n	let sign := 1;\n	let i := 0;\n	if ( substr( token, 0, 1 ) \u2261 "-" ) {\n		sign := -1;\n		i := 1;\n	}\n	else if ( substr( token, 0, 1 ) \u2261 "+" ) {\n		i := 1;\n	}\n	i += 2;\n\n	let n := 0;\n	while ( i < length token ) {\n		let ch := substr( token, i, 1 );\n		if ( ch \u2262 "_" ) {\n			let v := radix \u2261 16 ? _kdl_hex_value(ch) : ch + 0;\n			die `Invalid digit \'${ch}\' for radix ${radix}` if v >= radix;\n			n := n * radix + v;\n		}\n		i++;\n	}\n	return sign * n;\n}\n\nfunction _kdl_strip_decimal_zeroes ( String raw ) {\n	let i := 0;\n	while ( i < length raw - 1 and substr( raw, i, 1 ) \u2261 "0" ) {\n		i++;\n	}\n	return substr( raw, i, length raw - i );\n}\n\nfunction _kdl_decimal_mul_add ( String raw, Number factor, Number add ) {\n	let out := "";\n	let carry := add;\n	let i := length raw - 1;\n	while ( i >= 0 ) {\n		let n := ( substr( raw, i, 1 ) + 0 ) * factor + carry;\n		out := "" _ ( n mod 10 ) _ out;\n		carry := floor( n / 10 );\n		i--;\n	}\n	while ( carry > 0 ) {\n		out := "" _ ( carry mod 10 ) _ out;\n		carry := floor( carry / 10 );\n	}\n	return _kdl_strip_decimal_zeroes(out);\n}\n\nfunction _kdl_decimal_from_radix ( String token, Number radix ) {\n	let sign := "";\n	let i := 0;\n	if ( substr( token, 0, 1 ) \u2261 "-" ) {\n		sign := "-";\n		i := 1;\n	}\n	else if ( substr( token, 0, 1 ) \u2261 "+" ) {\n		i := 1;\n	}\n	i += 2;\n\n	let out := "0";\n	while ( i < length token ) {\n		out := _kdl_decimal_mul_add(\n			out,\n			radix,\n			_kdl_hex_value( substr( token, i, 1 ) ),\n		);\n		i++;\n	}\n	return sign _ out if sign \u2262 "" and out \u2262 "0";\n	return out;\n}\n\nfunction _kdl_canonical_decimal_int ( String token ) {\n	let sign := "";\n	let i := 0;\n	if ( substr( token, 0, 1 ) \u2261 "-" ) {\n		sign := "-";\n		i := 1;\n	}\n	else if ( substr( token, 0, 1 ) \u2261 "+" ) {\n		i := 1;\n	}\n	let body := _kdl_strip_decimal_zeroes(\n		substr( token, i, length token - i )\n	);\n	return sign _ body if sign \u2262 "" and body \u2262 "0";\n	return body;\n}\n\nfunction _kdl_canonical_float ( String token ) {\n	let epos := index( token, "e" );\n	epos := index( token, "E" ) if epos < 0;\n	return token if epos < 0;\n\n	let mantissa := substr( token, 0, epos );\n	let exponent := substr( token, epos + 1, length token - epos - 1 );\n	if ( substr( exponent, 0, 1 ) \u2262 "+"\n		and substr( exponent, 0, 1 ) \u2262 "-"\n	) {\n		exponent := "+" _ exponent;\n	}\n	return mantissa _ "E" _ exponent;\n}\n\nfunction _kdl_find_multiline_close (\n	String text,\n	String close,\n	Number start,\n	Boolean raw,\n) {\n	let found := index( text, close, start );\n	while ( found >= 0 ) {\n		if ( raw or found = 0 or substr( text, found - 1, 1 ) \u2262 "\\\\" ) {\n			return found;\n		}\n		found := index( text, close, found + 1 );\n	}\n	return -1;\n}\n\nfunction _kdl_reserved_ident ( String text ) {\n	return text \u2261 "true" or text \u2261 "false" or text \u2261 "null"\n		or text \u2261 "inf" or text \u2261 "-inf" or text \u2261 "nan";\n}\n\nfunction _kdl_ident_break ( String ch ) {\n	return ch \u2261 "" or _kdl_is_line_space(ch)\n		or ch \u2261 "\\\\" or ch \u2261 "/" or ch \u2261 "(" or ch \u2261 ")"\n		or ch \u2261 "{" or ch \u2261 "}" or ch \u2261 ";" or ch \u2261 "["\n		or ch \u2261 "]" or ch \u2261 "\\"" or ch \u2261 "#" or ch \u2261 "=";\n}\n\nfunction _kdl_forbidden_codepoint ( Number code ) {\n	return code < 32 or code \u2261 127 or code \u2261 65279\n		or code \u2261 8206 or code \u2261 8207\n		or ( code >= 8234 and code <= 8238 )\n		or ( code >= 8294 and code <= 8297 );\n}\n\nfunction _kdl_is_plain_ident ( String text ) {\n	if ( text \u2261 "" or _kdl_reserved_ident(text) ) {\n		return false;\n	}\n	let first := substr( text, 0, 1 );\n	let second := substr( text, 1, 1 );\n	if ( _kdl_is_digit(first) ) {\n		return false;\n	}\n	if ( ( first \u2261 "+" or first \u2261 "-" ) and _kdl_is_digit(second) ) {\n		return false;\n	}\n	if ( first \u2261 "." and _kdl_is_digit(second) ) {\n		return false;\n	}\n	let i := 0;\n	while ( i < length text ) {\n		return false if _kdl_ident_break( substr( text, i, 1 ) );\n		i++;\n	}\n	return true;\n}\n\nfunction _kdl_escape_string ( String text ) {\n	let out := "";\n	let i := 0;\n	while ( i < length text ) {\n		let ch := substr( text, i, 1 );\n		if ( ch \u2261 "\\\\" ) { out _= "\\\\\\\\"; }\n		else if ( ch \u2261 "\\"" ) { out _= "\\\\\\""; }\n		else if ( ch \u2261 chr(8) ) { out _= "\\\\b"; }\n		else if ( ch \u2261 chr(12) ) { out _= "\\\\f"; }\n		else if ( ch \u2261 "\\n" ) { out _= "\\\\n"; }\n		else if ( ch \u2261 "\\r" ) { out _= "\\\\r"; }\n		else if ( ch \u2261 "\\t" ) { out _= "\\\\t"; }\n		else if ( ord(ch) < 32 ) {\n			out _= "\\\\u{" _ sprint( "%x", ord(ch) ) _ "}";\n		}\n		else { out _= ch; }\n		i++;\n	}\n	return out;\n}\n\nfunction _kdl_name ( String text ) {\n	return _kdl_is_plain_ident(text) ? text : `"${_kdl_escape_string(text)}"`;\n}\n\nfunction _kdl_indent ( Number level, Boolean canonical := false ) {\n	let out := "";\n	let i := 0;\n	let unit := canonical ? "    " : "\\t";\n	while ( i < level ) {\n		out _= unit;\n		i++;\n	}\n	return out;\n}\n\nfunction _kdl_canonical_props ( PairList props ) {\n	let latest := {};\n	for ( let pair in props.to_Array() ) {\n		let kv := pair{pair};\n		latest{(kv[0])} := kv[1];\n	}\n\n	let out := [];\n	for ( let key in latest.sorted_keys() ) {\n		out.push( [ key, latest{(key)} ] );\n	}\n	return out;\n}\n\nclass KDLValue {\n	let String type := "null";\n	let kind := null;\n	let value := null;\n	let type_annotation := null;\n	let canonical_number := null;\n\n	method type () { return type; }\n	method kind () { return kind; }\n	method value () { return value; }\n	method type_annotation () { return type_annotation; }\n	method canonical_number () { return canonical_number; }\n\n	method is_null () { return type \u2261 "null"; }\n	method is_boolean () { return type \u2261 "boolean"; }\n	method is_number () { return type \u2261 "number"; }\n	method is_string () { return type \u2261 "string"; }\n	method is_true () { return type \u2261 "boolean" and value; }\n	method is_false () { return type \u2261 "boolean" and not value; }\n\n	method to_Number () {\n		die "KDLValue is not a number" if type \u2262 "number";\n		die "KDL keyword number has no native numeric value" if kind \u2261 "string";\n		return value;\n	}\n\n	method to_String () {\n		return "" if type \u2261 "null";\n		return "" _ value;\n	}\n\n	method to_Boolean () {\n		if ( type \u2261 "boolean" ) { return value; }\n		if ( type \u2261 "null" ) { return false; }\n		if ( type \u2261 "number" ) {\n			return kind \u2262 "string" and value \u2262 0;\n		}\n		return value \u2262 "";\n	}\n\n	method native_value () {\n		return null if type \u2261 "null";\n		return value;\n	}\n}\n\nclass KDLNode {\n	let name := "";\n	let type_annotation := null;\n	let args := [];\n	let props := null;\n	let children := [];\n\n	method __build__ () {\n		props := new PairList() if props \u2261 null;\n		args := [] if args \u2261 null;\n		children := [] if children \u2261 null;\n	}\n\n	method name () { return name; }\n	method type_annotation () { return type_annotation; }\n	method args () { return args; }\n	method props () { return props; }\n	method children () { return children; }\n\n	method to_Iterator () {\n		let values := [];\n		for ( let arg in args ) {\n			values.push(arg);\n		}\n		for ( let child in children ) {\n			values.push(child);\n		}\n		return values.to_Iterator();\n	}\n}\n\nclass KDLDocument {\n	let nodes := [];\n\n	method __build__ () {\n		nodes := [] if nodes \u2261 null;\n	}\n\n	method nodes () { return nodes; }\n\n	method to_Iterator () {\n		return nodes.to_Iterator();\n	}\n}\n\nclass _KDLParser {\n	let String text := "";\n	let Number pos := 0;\n\n	method _eof () {\n		return pos >= length text;\n	}\n\n	method _peek () {\n		return "" if self._eof();\n		return substr( text, pos, 1 );\n	}\n\n	method _take () {\n		let ch := self._peek();\n		pos++;\n		return ch;\n	}\n\n	method _error ( String message ) {\n		die `KDL parse error at offset ${pos}: ${message}`;\n	}\n\n	method _skip_newline () {\n		if ( _kdl_starts_with( text, pos, "\\r\\n" ) ) {\n			pos += 2;\n			return true;\n		}\n		if ( _kdl_is_newline( self._peek() ) ) {\n			pos++;\n			return true;\n		}\n		return false;\n	}\n\n	method _skip_line_comment () {\n		return false if not _kdl_starts_with( text, pos, "//" );\n		pos += 2;\n		while ( not self._eof() and not _kdl_is_newline( self._peek() ) ) {\n			pos++;\n		}\n		self._skip_newline();\n		return true;\n	}\n\n	method _skip_block_comment () {\n		return false if not _kdl_starts_with( text, pos, "/*" );\n		pos += 2;\n		let depth := 1;\n		while ( depth > 0 ) {\n			self._error("Unterminated block comment") if self._eof();\n			if ( _kdl_starts_with( text, pos, "/*" ) ) {\n				depth++;\n				pos += 2;\n			}\n			else if ( _kdl_starts_with( text, pos, "*/" ) ) {\n				depth--;\n				pos += 2;\n			}\n			else {\n				pos++;\n			}\n		}\n		return true;\n	}\n\n	method _skip_line_space () {\n		let moved := false;\n		let keep := true;\n		while ( keep and not self._eof() ) {\n			keep := false;\n			if ( _kdl_is_ws( self._peek() ) ) {\n				pos++;\n				moved := true;\n				keep := true;\n			}\n			else if ( self._skip_newline() ) {\n				moved := true;\n				keep := true;\n			}\n			else if ( self._skip_line_comment() ) {\n				moved := true;\n				keep := true;\n			}\n			else if ( self._skip_block_comment() ) {\n				moved := true;\n				keep := true;\n			}\n			else if ( self._skip_escline() ) {\n				moved := true;\n				keep := true;\n			}\n		}\n		return moved;\n	}\n\n	method _skip_node_space () {\n		let moved := false;\n		let keep := true;\n		while ( keep and not self._eof() ) {\n			keep := false;\n			if ( _kdl_is_ws( self._peek() ) ) {\n				pos++;\n				moved := true;\n				keep := true;\n			}\n			else if ( self._skip_block_comment() ) {\n				moved := true;\n				keep := true;\n			}\n			else if ( self._skip_escline() ) {\n				moved := true;\n				keep := true;\n			}\n		}\n		return moved;\n	}\n\n	method _skip_escline () {\n		return false if self._peek() \u2262 "\\\\";\n		let save := pos;\n		pos++;\n		let keep := true;\n		while ( keep and not self._eof() ) {\n			keep := false;\n			while ( _kdl_is_ws( self._peek() ) ) {\n				pos++;\n				keep := true;\n			}\n			if ( self._skip_block_comment() ) {\n				keep := true;\n			}\n		}\n		if ( self._skip_line_comment() or self._skip_newline() or self._eof() ) {\n			return true;\n		}\n		pos := save;\n		return false;\n	}\n\n	method _parse_document () {\n		if ( _kdl_starts_with( text, pos, chr(65279) ) ) {\n			pos++;\n		}\n		let nodes := self._parse_nodes(false);\n		self._skip_line_space();\n		self._error("Unexpected trailing input") if not self._eof();\n		return new KDLDocument( nodes: nodes );\n	}\n\n	method _parse_nodes ( Boolean in_children ) {\n		let nodes := [];\n		while (true) {\n			self._skip_line_space();\n			if ( self._eof() ) {\n				return nodes;\n			}\n			if ( in_children and self._peek() \u2261 "}" ) {\n				return nodes;\n			}\n			if ( _kdl_starts_with( text, pos, "/-" ) ) {\n				self._consume_slashdash();\n				self._parse_node(true);\n			}\n			else {\n				let node := self._parse_node(false);\n				nodes.push(node) if node \u2262 null;\n			}\n		}\n		return nodes;\n	}\n\n	method _consume_slashdash () {\n		self._error("Expected slashdash") if not _kdl_starts_with( text, pos, "/-" );\n		pos += 2;\n		self._skip_line_space();\n	}\n\n	method _parse_type_annotation () {\n		return null if self._peek() \u2262 "(";\n		pos++;\n		self._skip_node_space();\n		let name := self._parse_string();\n		self._skip_node_space();\n		self._error("Expected \')\' after type annotation") if self._peek() \u2262 ")";\n		pos++;\n		self._skip_node_space();\n		return name;\n	}\n\n	method _parse_node ( Boolean discard ) {\n		let annotation := self._parse_type_annotation();\n		self._skip_node_space();\n		let name := self._parse_string();\n		let args := [];\n		let props := new PairList();\n		let children := [];\n		let slashdash_child_before_entry := false;\n\n		while (true) {\n			let had_space := self._skip_node_space();\n			if ( self._eof() ) {\n				return discard ? null : new KDLNode(\n					name: name,\n					type_annotation: annotation,\n					args: args,\n					props: props,\n					children: children,\n				);\n			}\n\n			let ch := self._peek();\n			if ( ch \u2261 ";" ) {\n				pos++;\n				return discard ? null : new KDLNode(\n					name: name,\n					type_annotation: annotation,\n					args: args,\n					props: props,\n					children: children,\n				);\n			}\n			if ( ch \u2261 "}" ) {\n				return discard ? null : new KDLNode(\n					name: name,\n					type_annotation: annotation,\n					args: args,\n					props: props,\n					children: children,\n				);\n			}\n			if ( _kdl_is_newline(ch) ) {\n				self._skip_newline();\n				return discard ? null : new KDLNode(\n					name: name,\n					type_annotation: annotation,\n					args: args,\n					props: props,\n					children: children,\n				);\n			}\n			if ( _kdl_starts_with( text, pos, "//" ) ) {\n				self._skip_line_comment();\n				return discard ? null : new KDLNode(\n					name: name,\n					type_annotation: annotation,\n					args: args,\n					props: props,\n					children: children,\n				);\n			}\n			if ( _kdl_starts_with( text, pos, "/-" ) ) {\n				self._consume_slashdash();\n				if ( self._peek() \u2261 "{" ) {\n					self._parse_children();\n					slashdash_child_before_entry := true;\n				}\n				else {\n					self._parse_entry(true, args, props);\n				}\n				next;\n			}\n			if ( ch \u2261 "{" ) {\n				self._error("Child block must be the final node field")\n					if children.length() > 0;\n				children := self._parse_children();\n				next;\n			}\n			self._error("Expected whitespace before node field")\n				if not had_space;\n			self._error("Child block must be the final node field")\n				if children.length() > 0;\n			self._error("Discarded child block must not precede node fields")\n				if slashdash_child_before_entry;\n			self._parse_entry(discard, args, props);\n		}\n	}\n\n	method _parse_children () {\n		self._error("Expected \'{\'") if self._peek() \u2262 "{";\n		pos++;\n		let kids := self._parse_nodes(true);\n		self._skip_line_space();\n		self._error("Expected \'}\' after child block") if self._peek() \u2262 "}";\n		pos++;\n		return kids;\n	}\n\n	method _parse_entry ( Boolean discard, Array args, PairList props ) {\n		if ( self._peek() \u2261 "(" ) {\n			let value := self._parse_value();\n			args.push(value) if not discard;\n			return;\n		}\n\n		if ( self._peek() \u2261 "#" or self._starts_number() ) {\n			let value := self._parse_value();\n			args.push(value) if not discard;\n			return;\n		}\n\n		let key := self._parse_string();\n		let after_key := pos;\n		self._skip_node_space();\n		if ( self._peek() \u2261 "=" ) {\n			pos++;\n			self._skip_node_space();\n			let value := self._parse_value();\n			props.add( key, value ) if not discard;\n			return;\n		}\n		pos := after_key;\n\n		let value := new KDLValue( type: "string", value: key );\n		args.push(value) if not discard;\n		return;\n	}\n\n	method _parse_value () {\n		let annotation := self._parse_type_annotation();\n		self._skip_node_space();\n\n		if ( self._peek() \u2261 "#" ) {\n			return self._parse_hash_value(annotation);\n		}\n		if ( self._starts_number() ) {\n			return self._parse_number(annotation);\n		}\n		return new KDLValue(\n			type: "string",\n			value: self._parse_string(),\n			type_annotation: annotation,\n		);\n	}\n\n	method _starts_number () {\n		let ch := self._peek();\n		let nxt := substr( text, pos + 1, 1 );\n		return _kdl_is_digit(ch)\n			or ( ( ch \u2261 "+" or ch \u2261 "-" ) and _kdl_is_digit(nxt) );\n	}\n\n	method _read_token () {\n		let start := pos;\n		while ( not self._eof() ) {\n			let ch := self._peek();\n			last if _kdl_ident_break(ch);\n			pos++;\n		}\n		return substr( text, start, pos - start );\n	}\n\n	method _parse_hash_value ( annotation ) {\n		if ( _kdl_starts_with( text, pos, "#true" ) ) {\n			pos += 5;\n			return new KDLValue(\n				type: "boolean",\n				value: true,\n				type_annotation: annotation,\n			);\n		}\n		if ( _kdl_starts_with( text, pos, "#false" ) ) {\n			pos += 6;\n			return new KDLValue(\n				type: "boolean",\n				value: false,\n				type_annotation: annotation,\n			);\n		}\n		if ( _kdl_starts_with( text, pos, "#null" ) ) {\n			pos += 5;\n			return new KDLValue(\n				type: "null",\n				value: null,\n				type_annotation: annotation,\n			);\n		}\n		if ( _kdl_starts_with( text, pos, "#inf" ) ) {\n			pos += 4;\n			return new KDLValue(\n				type: "number",\n				kind: "string",\n				value: "#inf",\n				type_annotation: annotation,\n			);\n		}\n		if ( _kdl_starts_with( text, pos, "#-inf" ) ) {\n			pos += 5;\n			return new KDLValue(\n				type: "number",\n				kind: "string",\n				value: "#-inf",\n				type_annotation: annotation,\n			);\n		}\n		if ( _kdl_starts_with( text, pos, "#nan" ) ) {\n			pos += 4;\n			return new KDLValue(\n				type: "number",\n				kind: "string",\n				value: "#nan",\n				type_annotation: annotation,\n			);\n		}\n		return new KDLValue(\n			type: "string",\n			value: self._parse_raw_string(),\n			type_annotation: annotation,\n		);\n	}\n\n	method _parse_number ( annotation ) {\n		let token := self._read_token();\n		self._error( `Invalid number \'${token}\'` )\n			if token ~ /^[+-]?0[xob]_/i or token ~ /\\._/;\n		let clean := _kdl_clean_number(token);\n		if ( clean ~ /^[+-]?0x[0-9a-fA-F]+$/ ) {\n			return new KDLValue(\n				type: "number",\n				kind: "integer",\n				value: _kdl_parse_radix( clean, 16 ),\n				canonical_number: _kdl_decimal_from_radix( clean, 16 ),\n				type_annotation: annotation,\n			);\n		}\n		if ( clean ~ /^[+-]?0o[0-7]+$/ ) {\n			return new KDLValue(\n				type: "number",\n				kind: "integer",\n				value: _kdl_parse_radix( clean, 8 ),\n				canonical_number: _kdl_decimal_from_radix( clean, 8 ),\n				type_annotation: annotation,\n			);\n		}\n		if ( clean ~ /^[+-]?0b[01]+$/ ) {\n			return new KDLValue(\n				type: "number",\n				kind: "integer",\n				value: _kdl_parse_radix( clean, 2 ),\n				canonical_number: _kdl_decimal_from_radix( clean, 2 ),\n				type_annotation: annotation,\n			);\n		}\n		if ( clean ~ /^[+-]?[0-9]+$/ ) {\n			return new KDLValue(\n				type: "number",\n				kind: "integer",\n				value: clean + 0,\n				canonical_number: _kdl_canonical_decimal_int(clean),\n				type_annotation: annotation,\n			);\n		}\n		if ( clean ~ /^[+-]?[0-9]+(\\.[0-9]+)?([eE][+-]?[0-9]+)?$/ ) {\n			return new KDLValue(\n				type: "number",\n				kind: "float",\n				value: clean + 0,\n				canonical_number: _kdl_canonical_float(clean),\n				type_annotation: annotation,\n			);\n		}\n		self._error( `Invalid number \'${token}\'` );\n	}\n\n	method _parse_string () {\n		if ( self._peek() \u2261 "#" ) {\n			return self._parse_raw_string();\n		}\n		if ( self._peek() \u2261 "\\"" ) {\n			return self._parse_quoted_string();\n		}\n		return self._parse_identifier_string();\n	}\n\n	method _parse_identifier_string () {\n		let ident := self._read_token();\n		self._error("Expected string") if ident \u2261 "";\n		self._error( `Reserved KDL identifier \'${ident}\'` )\n			if _kdl_reserved_ident(ident);\n		self._error( `Invalid KDL identifier \'${ident}\'` )\n			if substr( ident, 0, 1 ) \u2261 "."\n				and _kdl_is_digit( substr( ident, 1, 1 ) );\n		let i := 0;\n		while ( i < length ident ) {\n			let code := ord( substr( ident, i, 1 ) );\n			self._error( `Forbidden codepoint in KDL identifier \'${ident}\'` )\n				if _kdl_forbidden_codepoint(code);\n			i++;\n		}\n		return ident;\n	}\n\n	method _parse_quoted_string () {\n		if ( _kdl_starts_with( text, pos, "\\"\\"\\"" ) ) {\n			return self._parse_multiline_string( "", false );\n		}\n		pos++;\n		let out := "";\n		while ( not self._eof() ) {\n			let ch := self._take();\n			if ( ch \u2261 "\\"" ) {\n				return out;\n			}\n			if ( ch \u2261 "\\\\" ) {\n				out _= self._parse_escape();\n			}\n			else {\n				self._error("Newline in quoted string") if _kdl_is_newline(ch);\n				out _= ch;\n			}\n		}\n		self._error("Unterminated quoted string");\n	}\n\n	method _parse_escape () {\n		self._error("Unterminated string escape") if self._eof();\n		let ch := self._take();\n		if ( ch \u2261 "\\"" ) { return "\\""; }\n		if ( ch \u2261 "\\\\" ) { return "\\\\"; }\n		if ( ch \u2261 "b" ) { return chr(8); }\n		if ( ch \u2261 "f" ) { return chr(12); }\n		if ( ch \u2261 "n" ) { return "\\n"; }\n		if ( ch \u2261 "r" ) { return "\\r"; }\n		if ( ch \u2261 "s" ) { return " "; }\n		if ( ch \u2261 "t" ) { return "\\t"; }\n		if ( _kdl_is_line_space(ch) ) {\n			while ( _kdl_is_line_space(ch) ) {\n				if ( _kdl_is_newline(ch) ) {\n					self._skip_newline();\n				}\n				ch := self._peek();\n				pos++ if _kdl_is_ws(ch);\n			}\n			return "";\n		}\n		if ( ch \u2261 "u" ) {\n			self._error("Expected \'{\' in Unicode escape") if self._peek() \u2262 "{";\n			pos++;\n			let start := pos;\n			while ( not self._eof() and self._peek() \u2262 "}" ) {\n				self._error("Invalid Unicode escape") if not _kdl_is_hex_digit( self._peek() );\n				pos++;\n			}\n			self._error("Unterminated Unicode escape") if self._peek() \u2262 "}";\n			let raw := substr( text, start, pos - start );\n			self._error("Unicode escape must contain 1 to 6 hex digits")\n				if length raw < 1 or length raw > 6;\n			pos++;\n			let code := _kdl_from_hex(raw);\n			return chr(code);\n		}\n		self._error( `Invalid string escape \'\\\\${ch}\'` );\n	}\n\n	method _parse_raw_string () {\n		let hashes := "";\n		while ( self._peek() \u2261 "#" ) {\n			hashes _= "#";\n			pos++;\n		}\n		self._error("Expected raw string quotes") if self._peek() \u2262 "\\"";\n		if ( _kdl_starts_with( text, pos, "\\"\\"\\"" ) ) {\n			return self._parse_multiline_string( hashes, true );\n		}\n		pos++;\n		let close := "\\"" _ hashes;\n		let end := index( text, close, pos );\n		self._error("Unterminated raw string") if end < 0;\n		let out := substr( text, pos, end - pos );\n		self._error("Newline in raw string") if out ~ /[\\r\\n\\v]/;\n		pos := end + length close;\n		return out;\n	}\n\n	method _parse_multiline_string ( String hashes, Boolean raw ) {\n		pos += 3;\n		self._error("Expected newline after multiline string opener")\n			if not self._skip_newline();\n		let close := "\\"\\"\\"" _ hashes;\n		let end := _kdl_find_multiline_close( text, close, pos, raw );\n		self._error("Unterminated multiline string") if end < 0;\n		let body := substr( text, pos, end - pos );\n		pos := end + length close;\n\n		let last_nl := -1;\n		let i := length body - 1;\n		while ( i >= 0 and last_nl < 0 ) {\n			if ( substr( body, i, 1 ) \u2261 "\\n" ) {\n				last_nl := i;\n			}\n			i--;\n		}\n		return "" if last_nl < 0;\n			let content := substr( body, 0, last_nl );\n			let indent := substr( body, last_nl + 1, length body - last_nl - 1 );\n			if ( not raw ) {\n				let bs := 0;\n				while ( bs < length indent\n					and _kdl_is_ws( substr( indent, bs, 1 ) )\n				) {\n					bs++;\n				}\n				if ( bs < length indent and substr( indent, bs, 1 ) \u2261 "\\\\" ) {\n					let k := bs + 1;\n					let only_ws := true;\n					while ( k < length indent ) {\n						only_ws := false\n							if not _kdl_is_ws( substr( indent, k, 1 ) );\n						k++;\n					}\n					indent := substr( indent, 0, bs ) if only_ws;\n				}\n			}\n			if ( indent \u2261 "" ) {\n				let min_indent := null;\n				let scan := 0;\n				let scan_start := 0;\n				while ( scan <= length content ) {\n					if ( scan \u2261 length content\n						or substr( content, scan, 1 ) \u2261 "\\n"\n					) {\n						let raw_line := substr(\n							content,\n							scan_start,\n							scan - scan_start,\n						);\n						if ( not( raw_line ~ /^\\s*$/ ) ) {\n							let width := 0;\n							while ( width < length raw_line\n								and _kdl_is_ws( substr( raw_line, width, 1 ) )\n							) {\n								width++;\n							}\n							min_indent := width\n								if min_indent \u2261 null or width < min_indent;\n						}\n						scan_start := scan + 1;\n					}\n					scan++;\n				}\n				if ( min_indent \u2262 null and min_indent > 0 ) {\n					indent := "";\n					let si := 0;\n					while ( si < min_indent ) {\n						indent _= " ";\n						si++;\n					}\n				}\n			}\n			let out := "";\n		i := 0;\n		let line_start := 0;\n			let emitted := false;\n			let continued := false;\n			let last_line_continued_with_text := false;\n			while ( i <= length content ) {\n			if ( i \u2261 length content or substr( content, i, 1 ) \u2261 "\\n" ) {\n				let line := substr( content, line_start, i - line_start );\n				if ( line ~ /^\\s*$/ ) {\n					line := "";\n				}\n					else if ( continued ) {\n						if ( length indent > 0\n							and substr( line, 0, length indent ) \u2261 indent\n						) {\n							line := substr(\n								line,\n								length indent,\n								length line - length indent,\n							);\n						}\n					}\n					else if ( length indent > 0 and substr( line, 0, length indent ) \u2261 indent ) {\n						line := substr( line, length indent, length line - length indent );\n					}\n					else if ( length indent > 0 ) {\n						let k := 0;\n						while ( k < length line\n							and _kdl_is_ws( substr( line, k, 1 ) )\n						) {\n							k++;\n						}\n						let ok_escape_prefix := false;\n						if ( not raw and substr( line, k, 1 ) \u2261 "\\\\" ) {\n							k++;\n							ok_escape_prefix := true;\n							while ( k < length line ) {\n								ok_escape_prefix := false\n									if not _kdl_is_ws( substr( line, k, 1 ) );\n								k++;\n							}\n						}\n						self._error("Multiline string indentation mismatch")\n							if not ok_escape_prefix;\n					}\n\n				let line_continues := false;\n				if ( not raw ) {\n					let j := length line - 1;\n					while ( j >= 0 and _kdl_is_ws( substr( line, j, 1 ) ) ) {\n						j--;\n					}\n					if ( j >= 0 and substr( line, j, 1 ) \u2261 "\\\\" ) {\n						let slashes := 0;\n						while ( j - slashes >= 0\n							and substr( line, j - slashes, 1 ) \u2261 "\\\\"\n						) {\n							slashes++;\n						}\n						if ( slashes mod 2 = 1 ) {\n							line_continues := true;\n							line := substr( line, 0, j );\n						}\n					}\n				}\n				self._error("Invalid final multiline whitespace escape")\n					if line_continues and line \u2261 "" and indent \u2261 "";\n\n				out _= "\\n"\n					if emitted and not continued\n						and not ( line_continues and line \u2261 "" );\n				out _= raw ? line : self._unescape_multiline_line(line);\n				emitted := true;\n				continued := line_continues;\n				last_line_continued_with_text := line_continues and line \u2262 "";\n				line_start := i + 1;\n			}\n			i++;\n		}\n		self._error("Invalid final multiline whitespace escape")\n			if last_line_continued_with_text;\n		return out;\n	}\n\n	method _unescape_multiline_line ( String line ) {\n		let out := "";\n		let i := 0;\n		while ( i < length line ) {\n			let ch := substr( line, i, 1 );\n			if ( ch \u2262 "\\\\" ) {\n				out _= ch;\n				i++;\n				next;\n			}\n\n			i++;\n			self._error("Unterminated string escape") if i >= length line;\n			ch := substr( line, i, 1 );\n			if ( ch \u2261 "\\"" ) { out _= "\\""; }\n			else if ( ch \u2261 "\\\\" ) { out _= "\\\\"; }\n			else if ( ch \u2261 "b" ) { out _= chr(8); }\n			else if ( ch \u2261 "f" ) { out _= chr(12); }\n			else if ( ch \u2261 "n" ) { out _= "\\n"; }\n			else if ( ch \u2261 "r" ) { out _= "\\r"; }\n			else if ( ch \u2261 "s" ) { out _= " "; }\n			else if ( ch \u2261 "t" ) { out _= "\\t"; }\n			else if ( _kdl_is_ws(ch) ) {\n				while ( i < length line and _kdl_is_ws( substr( line, i, 1 ) ) ) {\n					i++;\n				}\n				i--;\n			}\n			else if ( ch \u2261 "u" ) {\n				self._error("Expected \'{\' in Unicode escape")\n					if substr( line, i + 1, 1 ) \u2262 "{";\n				i += 2;\n				let start := i;\n				while ( i < length line and substr( line, i, 1 ) \u2262 "}" ) {\n					self._error("Invalid Unicode escape")\n						if not _kdl_is_hex_digit( substr( line, i, 1 ) );\n					i++;\n				}\n				self._error("Unterminated Unicode escape")\n					if i >= length line;\n				let raw := substr( line, start, i - start );\n				self._error("Unicode escape must contain 1 to 6 hex digits")\n					if length raw < 1 or length raw > 6;\n				let code := _kdl_from_hex(raw);\n				out _= chr(code);\n			}\n			else {\n				self._error( `Invalid string escape \'\\\\${ch}\'` );\n			}\n			i++;\n		}\n		return out;\n	}\n}\n\nfunction _kdl_value ( value ) {\n	if ( value instanceof KDLValue ) {\n		return value;\n	}\n	if ( value \u2261 null ) {\n		return new KDLValue( type: "null", value: null );\n	}\n	if ( value instanceof Boolean ) {\n		return new KDLValue( type: "boolean", value: value );\n	}\n	if ( value instanceof Number ) {\n		return new KDLValue( type: "number", kind: "float", value: value );\n	}\n	return new KDLValue( type: "string", value: "" _ value );\n}\n\nfunction _kdl_encode_value ( value, Boolean canonical := false ) {\n	let v := _kdl_value(value);\n	let prefix := "";\n	if ( v.type_annotation() \u2262 null ) {\n		prefix := "(" _ _kdl_name( v.type_annotation() ) _ ")";\n	}\n	if ( v.is_null() ) { return prefix _ "#null"; }\n	if ( v.is_boolean() ) {\n		return prefix _ ( v.native_value() ? "#true" : "#false" );\n	}\n	if ( v.is_number() ) {\n		if ( canonical and v.canonical_number() \u2262 null ) {\n			return prefix _ v.canonical_number();\n		}\n		return prefix _ ( v.kind() \u2261 "string" ? v.value() : "" _ v.value() );\n	}\n	if ( v.is_string() ) {\n		if ( canonical and _kdl_is_plain_ident( v.native_value() ) ) {\n			return prefix _ v.native_value();\n		}\n		return prefix _ "\\"" _ _kdl_escape_string( v.native_value() ) _ "\\"";\n	}\n\n	let native := v.native_value();\n	try {\n		if ( native can "to_String" ) {\n			let text := native.to_String();\n			if ( canonical and _kdl_is_plain_ident(text) ) {\n				return prefix _ text;\n			}\n			return prefix _ "\\"" _ _kdl_escape_string(text) _ "\\"";\n		}\n	}\n	catch {\n	}\n\n	die `Cannot serialize KDLValue of type \'${v.type()}\'`;\n}\n\nfunction _kdl_encode_node (\n	KDLNode node,\n	Number level,\n	Boolean canonical := false,\n) {\n	let out := _kdl_indent( level, canonical );\n	if ( node.type_annotation() \u2262 null ) {\n		out _= "(" _ _kdl_name( node.type_annotation() ) _ ")";\n	}\n	out _= _kdl_name( node.name() );\n	for ( let arg in node.args() ) {\n		out _= " " _ _kdl_encode_value( arg, canonical );\n	}\n	if ( canonical ) {\n		for ( let kv in _kdl_canonical_props( node.props() ) ) {\n			out _= " " _ _kdl_name(kv[0]) _ "="\n				_ _kdl_encode_value( kv[1], canonical );\n		}\n	}\n	else {\n		for ( let pair in node.props().to_Array() ) {\n			let kv := pair{pair};\n			out _= " " _ _kdl_name(kv[0]) _ "="\n				_ _kdl_encode_value( kv[1], canonical );\n		}\n	}\n	if ( node.children().length() > 0 ) {\n		out _= " {\\n";\n		let i := 0;\n		while ( i < node.children().length() ) {\n			out _= _kdl_encode_node(\n				node.children()[i],\n				level + 1,\n				canonical,\n			);\n			out _= "\\n";\n			i++;\n		}\n		out _= _kdl_indent( level, canonical ) _ "}";\n	}\n	return out;\n}\n\nfunction _kdl_encode_document ( KDLDocument doc, Boolean canonical := false ) {\n	let out := "";\n	let i := 0;\n	while ( i < doc.nodes().length() ) {\n		out _= "\\n" if i > 0;\n		out _= _kdl_encode_node( doc.nodes()[i], 0, canonical );\n		i++;\n	}\n	out _= "\\n" if canonical;\n	return out;\n}\n\nclass KDL {\n	let Boolean canonical := false;\n\n	method decode ( String text ) {\n		return new _KDLParser( text: text, pos: 0 )._parse_document();\n	}\n\n	method decode_binarystring ( BinaryString raw ) {\n		return self.decode( to_string(raw) );\n	}\n\n	method encode ( value ) {\n		if ( value instanceof KDLDocument ) {\n			return _kdl_encode_document( value, canonical );\n		}\n		if ( value instanceof KDLNode ) {\n			return _kdl_encode_node( value, 0, canonical );\n		}\n		if ( value instanceof Array ) {\n			return _kdl_encode_document(\n				new KDLDocument( nodes: value ),\n				canonical,\n			);\n		}\n		die "KDL.encode expects a KDLDocument, KDLNode, or Array of KDLNode";\n	}\n\n	method encode_binarystring ( value ) {\n		return to_binary( self.encode(value) );\n	}\n\n	method load ( path ) {\n		from std/io import Path;\n		die "KDL.load is denied by runtime policy" if __system__{deny_fs};\n		die "KDL.load expects a std/io Path object" if not( path instanceof Path );\n		return self.decode_binarystring( path.slurp() );\n	}\n\n	method dump ( path, value ) {\n		from std/io import Path;\n		die "KDL.dump is denied by runtime policy" if __system__{deny_fs};\n		die "KDL.dump expects a std/io Path object" if not( path instanceof Path );\n		path.spew( self.encode_binarystring(value) );\n		return path;\n	}\n}\n';
        virtualFiles["/modules/std/data/kdl/json.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/data/kdl/json - JSON-in-KDL structure conversion.\n\n=head1 SYNOPSIS\n\n  from std/data/kdl import KDL;\n  from std/data/kdl/json import kdl_to_json, json_to_kdl;\n\n  let kdl_doc := ( new KDL() ).decode( """- foo=1 bar=#true""" );\n  let data := kdl_to_json(kdl_doc);\n  let roundtrip := json_to_kdl(data);\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module implements the JSON-in-KDL (JiK) mapping for parsed Zuzu\nobjects. C<kdl_to_json> accepts a C<KDLDocument> or C<KDLNode> and\nreturns native Zuzu data structures. C<json_to_kdl> accepts native\nJSON-like data structures and returns a C<KDLDocument>.\n\nC<kdl_to_json(value, pairlists: true)> maps object-like JiK nodes to\nC<PairList> values instead of C<Dict> values, preserving key order and\nduplicate keys.\n\n=head1 EXPORTS\n\n=head2 Functions\n\n=over\n\n=item C<< kdl_to_json(value, ... PairList opts) >>\n\nParameters: C<value> is a C<KDLDocument>, C<KDLNode>, or compatible KDL\nvalue and C<opts> may include C<pairlists>. Returns: value. Converts\nJSON-in-KDL structures into native JSON-like ZuzuScript data.\n\n=item C<< json_to_kdl(value) >>\n\nParameters: C<value> is a JSON-like ZuzuScript value. Returns:\nC<KDLDocument>. Converts native JSON-like data into JSON-in-KDL nodes.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/data/kdl/json >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/data/kdl import KDLDocument, KDLNode, KDLValue;\nfrom std/data/kdl/xml import xml_to_kdl;\nfrom std/time import Time;\n\n\nfunction _jik_has_props ( KDLNode node ) {\n	return node.props().to_Array().length() > 0;\n}\n\nfunction _jik_literal_value ( value ) {\n	die "JSON-in-KDL literal must be a KDLValue"\n		if not( value instanceof KDLValue );\n	if ( value.is_number() and value.kind() \u2261 "string" ) {\n		die "JSON-in-KDL does not support non-finite KDL number keywords";\n	}\n	return value.native_value();\n}\n\nfunction _jik_is_time_native ( value ) {\n	return value instanceof Time;\n}\n\nfunction _jik_pad2 ( value ) {\n	let text := "" _ value;\n	return length text < 2 ? "0" _ text : text;\n}\n\nfunction _jik_pad4 ( value ) {\n	let text := "" _ value;\n	while ( length text < 4 ) {\n		text := "0" _ text;\n	}\n	return text;\n}\n\nfunction _jik_time_text ( value ) {\n	return _jik_pad4( value.year() )\n		_ "-" _ _jik_pad2( value.mon() )\n		_ "-" _ _jik_pad2( value.day_of_month() )\n		_ "T" _ _jik_pad2( value.hour() )\n		_ ":" _ _jik_pad2( value.min() )\n		_ ":" _ _jik_pad2( value.sec() );\n}\n\nfunction _jik_value ( value ) {\n	if ( value instanceof KDLValue ) {\n		return value;\n	}\n	if ( value \u2261 null ) {\n		return new KDLValue( type: "null", value: null );\n	}\n\n	if ( value instanceof Boolean ) {\n		return new KDLValue( type: "boolean", value: value );\n	}\n	if ( value instanceof Number ) {\n		return new KDLValue( type: "number", kind: "float", value: value );\n	}\n	if ( value instanceof String or value instanceof BinaryString ) {\n		return new KDLValue( type: "string", value: "" _ value );\n	}\n	if ( _jik_is_time_native(value) ) {\n		return new KDLValue(\n			type: "string",\n			value: _jik_time_text(value),\n			type_annotation: "date-time",\n		);\n	}\n\n	return new KDLValue( type: typeof value, value: value );\n}\n\nfunction _jik_is_array_native ( value ) {\n	return value instanceof Array or value instanceof Set or value instanceof Bag;\n}\n\nfunction _jik_is_object_native ( value ) {\n	return value instanceof Dict or value instanceof PairList;\n}\n\nfunction _jik_is_kdl_native ( value ) {\n	return value instanceof KDLDocument or value instanceof KDLNode;\n}\n\nfunction _jik_is_xml_native ( value ) {\n	try {\n		if ( value can nodeType ) {\n			return true if value.nodeType() \u2262 null;\n		}\n	}\n	catch {\n	}\n\n	try {\n		return false if not( value can documentElement );\n		value.documentElement();\n		return true;\n	}\n	catch {\n	}\n\n	return false;\n}\n\nfunction _jik_is_opaque_literal_native ( value ) {\n	return not _jik_is_array_native(value)\n		and not _jik_is_object_native(value)\n		and not _jik_is_kdl_native(value)\n		and not _jik_is_xml_native(value);\n}\n\nfunction _jik_is_literal_native ( value ) {\n	return value \u2261 null\n		or value instanceof Boolean\n		or value instanceof Number\n		or value instanceof String\n		or value instanceof BinaryString\n		or _jik_is_time_native(value)\n		or value instanceof KDLValue\n		or _jik_is_opaque_literal_native(value);\n}\n\nfunction _jik_sorted_array ( value ) {\n	if ( value instanceof Set or value instanceof Bag ) {\n		return value.sortstr();\n	}\n	return value;\n}\n\nfunction _jik_pairs ( obj ) {\n	let out := [];\n	if ( obj instanceof PairList ) {\n		for ( let p in obj.to_Array() ) {\n			out.push( p{pair} );\n		}\n		return out;\n	}\n\n	for ( let key in obj.sorted_keys() ) {\n		out.push( [ key, obj.get(key) ] );\n	}\n	return out;\n}\n\nfunction _jik_native_to_node;\nfunction _jik_native_to_nodes;\n\nfunction _jik_xml_nodes ( value ) {\n	return xml_to_kdl(value).nodes();\n}\n\nfunction _jik_kdl_nodes ( value ) {\n	if ( value instanceof KDLDocument ) {\n		return value.nodes();\n	}\n	return [ value ];\n}\n\nfunction _jik_structural_nodes ( value, String name := "-" ) {\n	let nodes := _jik_is_kdl_native(value)\n		? _jik_kdl_nodes(value)\n		: _jik_xml_nodes(value);\n\n	if ( name \u2261 "-" ) {\n		return nodes.length() = 0 ? [ new KDLNode( name: name ) ] : nodes;\n	}\n	return [ new KDLNode( name: name, children: nodes ) ];\n}\n\nfunction _jik_make_array_node ( value, String name := "-" ) {\n	let items := _jik_sorted_array(value);\n	let all_literals := true;\n	for ( let item in items ) {\n		all_literals := false unless _jik_is_literal_native(item);\n	}\n\n	let annotate := items.length() < 2;\n	if ( all_literals ) {\n		return new KDLNode(\n			name: name,\n			type_annotation: annotate ? "array" : null,\n			args: items.map( fn item -> _jik_value(item) ),\n		);\n	}\n\n	let children := [];\n	for ( let item in items ) {\n		for ( let child in _jik_native_to_nodes( item, "-" ) ) {\n			children.push(child);\n		}\n	}\n\n	return new KDLNode(\n		name: name,\n		type_annotation: annotate ? "array" : null,\n		children: children,\n	);\n}\n\nfunction _jik_object_needs_annotation ( Array pairs, Boolean pairlist ) {\n	if ( pairs.length() = 0 ) {\n		return true;\n	}\n	if ( pairlist ) {\n		return pairs.all( fn pair -> pair[0] \u2261 "-" );\n	}\n	return pairs.length() = 1 and pairs[0][0] \u2261 "-"\n		and not _jik_is_literal_native( pairs[0][1] );\n}\n\nfunction _jik_make_object_node ( value, String name := "-" ) {\n	let pairs := _jik_pairs(value);\n	let pairlist := value instanceof PairList;\n	let props := new PairList();\n	let children := [];\n\n	if ( pairlist ) {\n		for ( let pair in pairs ) {\n			for ( let child in _jik_native_to_nodes( pair[1], pair[0] ) ) {\n				children.push(child);\n			}\n		}\n	}\n	else {\n		for ( let pair in pairs ) {\n			if ( _jik_is_literal_native( pair[1] ) ) {\n				props.add( pair[0], _jik_value( pair[1] ) );\n			}\n			else {\n				for ( let child in _jik_native_to_nodes( pair[1], pair[0] ) ) {\n					children.push(child);\n				}\n			}\n		}\n	}\n\n	return new KDLNode(\n		name: name,\n		type_annotation: _jik_object_needs_annotation( pairs, pairlist )\n			? "object"\n			: null,\n		props: props,\n		children: children,\n	);\n}\n\nfunction _jik_native_to_node ( value, String name := "-" ) {\n	if ( _jik_is_literal_native(value) ) {\n		return new KDLNode( name: name, args: [ _jik_value(value) ] );\n	}\n	if ( _jik_is_array_native(value) ) {\n		return _jik_make_array_node( value, name );\n	}\n	if ( _jik_is_object_native(value) ) {\n		return _jik_make_object_node( value, name );\n	}\n	if ( _jik_is_kdl_native(value) or _jik_is_xml_native(value) ) {\n		let nodes := _jik_structural_nodes( value, name );\n		return nodes.length() = 1 ? nodes[0] : new KDLNode(\n			name: name,\n			children: nodes,\n		);\n	}\n	die `Cannot convert ${typeof value} to JSON-in-KDL`;\n}\n\nfunction _jik_native_to_nodes ( value, String name := "-" ) {\n	if ( _jik_is_kdl_native(value) or _jik_is_xml_native(value) ) {\n		return _jik_structural_nodes( value, name );\n	}\n	return [ _jik_native_to_node( value, name ) ];\n}\n\nfunction _jik_node_has_only_dash_children ( KDLNode node ) {\n	return node.children().all( fn child -> child.name() \u2261 "-" );\n}\n\nfunction _jik_node_kind ( KDLNode node ) {\n	let annotation := node.type_annotation();\n	if ( annotation \u2261 "array" or annotation \u2261 "object" ) {\n		return annotation;\n	}\n	if ( _jik_has_props(node) ) {\n		return "object";\n	}\n	if ( node.children().length() > 0 ) {\n		if ( _jik_node_has_only_dash_children(node) ) {\n			return "array";\n		}\n		return "object";\n	}\n	if ( node.args().length() = 1 ) {\n		return "literal";\n	}\n	if ( node.args().length() > 1 ) {\n		return "array";\n	}\n	die "Empty JSON-in-KDL node must be annotated as array or object";\n}\n\nfunction _jik_node_to_native;\n\nfunction _jik_array_from_node ( KDLNode node, PairList opts ) {\n	die "JSON-in-KDL array node cannot contain properties"\n		if _jik_has_props(node);\n	die "Empty JSON-in-KDL array node must be annotated as array"\n		if node.args().length() = 0\n			and node.children().length() = 0\n			and node.type_annotation() \u2262 "array";\n	die "JSON-in-KDL array child nodes must be named \'-\'"\n		unless _jik_node_has_only_dash_children(node);\n\n	let out := [];\n	for ( let arg in node.args() ) {\n		out.push( _jik_literal_value(arg) );\n	}\n	for ( let child in node.children() ) {\n		out.push( _jik_node_to_native( child, opts ) );\n	}\n	return out;\n}\n\nfunction _jik_store_object_item ( obj, String key, value, Boolean pairlists ) {\n	if ( pairlists ) {\n		obj.add( key, value );\n		return;\n	}\n	die `Duplicate JSON-in-KDL object key \'${key}\'` if obj.exists(key);\n	obj.set( key, value );\n}\n\nfunction _jik_object_from_node ( KDLNode node, PairList opts ) {\n	die "JSON-in-KDL object node cannot contain unnamed arguments"\n		if node.args().length() > 0;\n	die "Empty JSON-in-KDL object node must be annotated as object"\n		if not _jik_has_props(node)\n			and node.children().length() = 0\n			and node.type_annotation() \u2262 "object";\n\n	let pairlists := opts.get( "pairlists", false );\n	let out := pairlists ? new PairList() : {};\n\n	for ( let pair in node.props().to_Array() ) {\n		let kv := pair{pair};\n		_jik_store_object_item(\n			out,\n			kv[0],\n			_jik_literal_value( kv[1] ),\n			pairlists,\n		);\n	}\n	for ( let child in node.children() ) {\n		_jik_store_object_item(\n			out,\n			child.name(),\n			_jik_node_to_native( child, opts ),\n			pairlists,\n		);\n	}\n	return out;\n}\n\nfunction _jik_node_to_native ( KDLNode node, PairList opts ) {\n	let kind := _jik_node_kind(node);\n	if ( kind \u2261 "literal" ) {\n		die "JSON-in-KDL literal node must contain one argument only"\n			if node.args().length() \u2262 1\n				or _jik_has_props(node)\n				or node.children().length() > 0;\n		return _jik_literal_value( node.args()[0] );\n	}\n	if ( kind \u2261 "array" ) {\n		return _jik_array_from_node( node, opts );\n	}\n	if ( kind \u2261 "object" ) {\n		return _jik_object_from_node( node, opts );\n	}\n	die `Unknown JSON-in-KDL node kind \'${kind}\'`;\n}\n\nfunction kdl_to_json ( value, ... PairList opts ) {\n	if ( value instanceof KDLNode ) {\n		return _jik_node_to_native( value, opts );\n	}\n	if ( value instanceof KDLDocument ) {\n		die "JSON-in-KDL document must contain exactly one top-level node"\n			if value.nodes().length() \u2262 1;\n		return _jik_node_to_native( value.nodes()[0], opts );\n	}\n	die "kdl_to_json expects a KDLDocument or KDLNode";\n}\n\nfunction json_to_kdl ( value ) {\n	if ( value instanceof KDLDocument ) {\n		return value;\n	}\n	if ( value instanceof KDLNode ) {\n		return value;\n	}\n	return new KDLDocument( nodes: [ _jik_native_to_node(value) ] );\n}\n';
        virtualFiles["/modules/std/data/kdl/xml.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/data/kdl/xml - XML-in-KDL structure conversion.\n\n=head1 SYNOPSIS\n\n  from std/data/kdl import KDL;\n  from std/data/kdl/xml import kdl_to_xml, xml_to_kdl;\n  from std/data/xml import XML;\n\n  let kdl_doc := ( new KDL() ).decode(\n    "a href=\\"http://example.com\\" \\"here\'s a link\\""\n  );\n  let xml_doc := kdl_to_xml(kdl_doc);\n  let roundtrip := xml_to_kdl(xml_doc);\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module implements the XML-in-KDL (XiK) mapping for parsed Zuzu\nobjects. C<kdl_to_xml> accepts a C<KDLDocument> or C<KDLNode> and\nreturns an C<XMLDocument>. C<xml_to_kdl> accepts an C<XMLDocument> or\nC<XMLNode> and returns a C<KDLDocument>.\n\n=head1 EXPORTS\n\n=head2 Functions\n\n=over\n\n=item C<< kdl_to_xml(value) >>\n\nParameters: C<value> is a C<KDLDocument>, C<KDLNode>, or compatible KDL\nvalue. Returns: C<XMLDocument>. Converts XML-in-KDL structures into an\nXML document.\n\n=item C<< xml_to_kdl(value) >>\n\nParameters: C<value> is an C<XMLDocument>, C<XMLNode>, or compatible XML\nvalue. Returns: C<KDLDocument>. Converts XML data into XML-in-KDL nodes.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/data/kdl/xml >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/data/kdl import KDLDocument, KDLNode, KDLValue;\nfrom std/data/xml import XML;\nfrom std/data/xml/escape import escape_xml;\nfrom std/string import index, substr;\n\nfunction _xik_starts_with ( String text, String prefix ) {\n	return substr( text, 0, length prefix ) \u2261 prefix;\n}\n\nfunction _xik_has_props ( KDLNode node ) {\n	return node.props().to_Array().length() > 0;\n}\n\nfunction _xik_string_value ( value, String context ) {\n	die `${context} must be a KDLValue` if not( value instanceof KDLValue );\n	die `${context} must be a string value` if not value.is_string();\n	return value.native_value();\n}\n\nfunction _xik_single_string_arg ( KDLNode node, String context ) {\n	die `${context} must contain one string argument`\n		if node.args().length() \u2262 1;\n	return _xik_string_value( node.args()[0], context );\n}\n\nfunction _xik_no_props_or_children ( KDLNode node, String context ) {\n	die `${context} cannot contain properties` if _xik_has_props(node);\n	die `${context} cannot contain children`\n		if node.children().length() > 0;\n}\n\nfunction _xik_attr_text ( PairList props ) {\n	let out := "";\n	for ( let pair in props.to_Array() ) {\n		let kv := pair{pair};\n		let key := kv[0];\n		let value := _xik_string_value(\n			kv[1],\n			`XML-in-KDL attribute \'${key}\'`,\n		);\n		out _= ` ${key}="${escape_xml(value)}"`;\n	}\n	return out;\n}\n\nfunction _xik_comment_text ( KDLNode node ) {\n	_xik_no_props_or_children( node, "XML-in-KDL comment node" );\n	let text := _xik_single_string_arg( node, "XML-in-KDL comment node" );\n	die "XML-in-KDL comment cannot contain \'--\'" if index( text, "--" ) >= 0;\n	die "XML-in-KDL comment cannot end with \'-\'"\n		if length text > 0 and substr( text, length text - 1, 1 ) \u2261 "-";\n	return "<!--" _ text _ "-->";\n}\n\nfunction _xik_doctype_text ( KDLNode node ) {\n	_xik_no_props_or_children( node, "XML-in-KDL doctype node" );\n	let text := _xik_single_string_arg( node, "XML-in-KDL doctype node" );\n	die "XML-in-KDL doctype cannot contain \'>\'" if index( text, ">" ) >= 0;\n	return "<!DOCTYPE " _ text _ ">";\n}\n\nfunction _xik_pi_text ( KDLNode node ) {\n	die "XML-in-KDL processing instruction cannot contain children"\n		if node.children().length() > 0;\n\n	let target := substr( node.name(), 1, length node.name() - 1 );\n	die "XML-in-KDL processing instruction has an empty target"\n		if target \u2261 "";\n\n	let content := "";\n	if ( node.args().length() > 0 ) {\n		_xik_no_props_or_children(\n			node,\n			"XML-in-KDL unstructured processing instruction",\n		);\n		content := _xik_single_string_arg(\n			node,\n			"XML-in-KDL unstructured processing instruction",\n		);\n	}\n	else {\n		content := _xik_attr_text( node.props() );\n		content := substr( content, 1, length content - 1 )\n			if length content > 0;\n	}\n\n	die "XML-in-KDL processing instruction cannot contain \'?>\'"\n		if index( content, "?>" ) >= 0;\n\n	return content \u2261 "" ? `<?${target}?>` : `<?${target} ${content}?>`;\n}\n\nfunction _xik_text_node_text ( KDLNode node ) {\n	_xik_no_props_or_children( node, "XML-in-KDL text node" );\n	return escape_xml( _xik_single_string_arg( node, "XML-in-KDL text node" ) );\n}\n\nfunction _xik_node_text;\n\nfunction _xik_element_text ( KDLNode node ) {\n	die `XML-in-KDL element \'${node.name()}\' cannot have type annotations`\n		if node.type_annotation() \u2262 null;\n\n	let args := node.args();\n	let children := node.children();\n	die `XML-in-KDL element \'${node.name()}\' cannot contain multiple arguments`\n		if args.length() > 1;\n	die `XML-in-KDL element \'${node.name()}\' cannot mix text argument and children`\n		if args.length() > 0 and children.length() > 0;\n\n	let attrs := _xik_attr_text( node.props() );\n	if ( args.length() = 0 and children.length() = 0 ) {\n		return `<${node.name()}${attrs}/>`;\n	}\n\n	let body := "";\n	if ( args.length() = 1 ) {\n		body := escape_xml(\n			_xik_string_value(\n				args[0],\n				`XML-in-KDL element \'${node.name()}\' text argument`,\n			),\n		);\n	}\n	else {\n		for ( let child in children ) {\n			body _= _xik_node_text(child);\n		}\n	}\n\n	return `<${node.name()}${attrs}>${body}</${node.name()}>`;\n}\n\nfunction _xik_node_text ( KDLNode node ) {\n	let name := node.name();\n	if ( name \u2261 "-" ) {\n		return _xik_text_node_text(node);\n	}\n	if ( name \u2261 "!" ) {\n		return _xik_comment_text(node);\n	}\n	if ( name \u2261 "!doctype" ) {\n		return _xik_doctype_text(node);\n	}\n	if ( _xik_starts_with( name, "?" ) ) {\n		return _xik_pi_text(node);\n	}\n	return _xik_element_text(node);\n}\n\nfunction _xik_is_element_node ( KDLNode node ) {\n	let name := node.name();\n	return name \u2262 "-" and name \u2262 "!" and name \u2262 "!doctype"\n		and not _xik_starts_with( name, "?" );\n}\n\nfunction kdl_to_xml ( value ) {\n	let nodes;\n	if ( value instanceof KDLDocument ) {\n		nodes := value.nodes();\n	}\n	else if ( value instanceof KDLNode ) {\n		nodes := [ value ];\n	}\n	else {\n		die "kdl_to_xml expects a KDLDocument or KDLNode";\n	}\n\n	let element_count := 0;\n	let out := "";\n	for ( let node in nodes ) {\n		element_count++ if _xik_is_element_node(node);\n		out _= _xik_node_text(node);\n	}\n\n	die "XML-in-KDL document must contain exactly one top-level element"\n		if element_count \u2262 1;\n\n	return XML.parse(out);\n}\n\nfunction _xik_kdl_value ( String text ) {\n	return new KDLValue( type: "string", value: text );\n}\n\nfunction _xik_xml_attrs_to_kdl ( xml_node ) {\n	let props := new PairList();\n	for ( let attr in xml_node.attributes() ) {\n		props.add( attr.nodeName(), _xik_kdl_value( attr.nodeValue() ) );\n	}\n	return props;\n}\n\nfunction _xik_xml_text_to_kdl ( xml_node ) {\n	return new KDLNode(\n		name: "-",\n		args: [ _xik_kdl_value( xml_node.nodeValue() ?: "" ) ],\n	);\n}\n\nfunction _xik_xml_comment_to_kdl ( xml_node ) {\n	return new KDLNode(\n		name: "!",\n		args: [ _xik_kdl_value( xml_node.nodeValue() ?: "" ) ],\n	);\n}\n\nfunction _xik_xml_node_to_kdl;\n\nfunction _xik_xml_pi_to_kdl ( xml_node ) {\n	return new KDLNode(\n		name: "?" _ xml_node.nodeName(),\n		args: [ _xik_kdl_value( xml_node.nodeValue() ?: "" ) ],\n	);\n}\n\nfunction _xik_xml_doctype_to_kdl ( xml_node ) {\n	return new KDLNode(\n		name: "!doctype",\n		args: [ _xik_kdl_value( xml_node.nodeValue() or? xml_node.nodeName() ) ],\n	);\n}\n\nfunction _xik_xml_element_to_kdl ( xml_node ) {\n	let child_nodes := xml_node.childNodes();\n	let text_only := child_nodes.length() > 0;\n	let text := "";\n\n	for ( let child in child_nodes ) {\n		let kind := 0 + child.nodeType();\n		if ( kind = 3 or kind = 4 ) {\n			text _= child.nodeValue() ?: "";\n		}\n		else {\n			text_only := false;\n		}\n	}\n\n	if ( text_only ) {\n		return new KDLNode(\n			name: xml_node.nodeName(),\n			props: _xik_xml_attrs_to_kdl(xml_node),\n			args: [ _xik_kdl_value(text) ],\n		);\n	}\n\n	let children := [];\n	for ( let child in child_nodes ) {\n		let kdl_child := _xik_xml_node_to_kdl(child);\n		children.push(kdl_child) if kdl_child \u2262 null;\n	}\n\n	return new KDLNode(\n		name: xml_node.nodeName(),\n		props: _xik_xml_attrs_to_kdl(xml_node),\n		children: children,\n	);\n}\n\nfunction _xik_xml_node_to_kdl ( xml_node ) {\n	switch ( 0 + xml_node.nodeType() ) {\n		case 1:\n			return _xik_xml_element_to_kdl(xml_node);\n		case 3, 4:\n			return _xik_xml_text_to_kdl(xml_node);\n		case 7:\n			return _xik_xml_pi_to_kdl(xml_node);\n		case 8:\n			return _xik_xml_comment_to_kdl(xml_node);\n		case 10:\n			return _xik_xml_doctype_to_kdl(xml_node);\n	}\n	return null;\n}\n\nfunction _xik_xml_document_nodes ( xml_doc ) {\n	let raw_nodes := null;\n	try {\n		raw_nodes := xml_doc.childNodes();\n	}\n	catch {\n		try {\n			raw_nodes := xml_doc.findnodes("/node()");\n		}\n		catch {\n			let root := xml_doc.documentElement();\n			raw_nodes := root \u2261 null ? [] : [ root ];\n		}\n	}\n\n	if ( raw_nodes.length() = 0 ) {\n		let root := xml_doc.documentElement();\n		raw_nodes := root \u2261 null ? [] : [ root ];\n	}\n\n	let nodes := [];\n	for ( let raw in raw_nodes ) {\n		let node := _xik_xml_node_to_kdl(raw);\n		nodes.push(node) if node \u2262 null;\n	}\n	return nodes;\n}\n\nfunction xml_to_kdl ( value ) {\n	let node_type := null;\n	try {\n		node_type := 0 + value.nodeType();\n	}\n	catch {\n	}\n\n	if ( node_type \u2262 null ) {\n		if ( node_type = 9 ) {\n			return new KDLDocument( nodes: _xik_xml_document_nodes(value) );\n		}\n\n		let node := _xik_xml_node_to_kdl(value);\n		die "xml_to_kdl cannot convert this XML node type" if node \u2261 null;\n		return new KDLDocument( nodes: [ node ] );\n	}\n\n	try {\n		value.documentElement();\n		return new KDLDocument( nodes: _xik_xml_document_nodes(value) );\n	}\n	catch {\n		die "xml_to_kdl expects an XMLDocument or XMLNode";\n	}\n}\n';
        virtualFiles["/modules/std/path/jsonpointer.zzm"] = `=encoding utf8

=head1 NAME

std/path/jsonpointer - RFC 6901 JSON Pointer selectors.

=head1 SYNOPSIS

  from std/path/jsonpointer import JSONPointer;

  let data := {
    users: [
      { name: "Ada" },
      { name: "Bob" },
    ],
  };

  let pointer := new JSONPointer( path: "/users/0/name" );
  say( pointer.first(data) );

=head1 IMPLEMENTATION SUPPORT

This module is supported by all implementations of ZuzuScript.

=head1 DESCRIPTION

C<JSONPointer> implements JSON Pointer as defined by RFC 6901. It
provides the same path API shape as C<std/path/simple> and C<std/path/z>:
C<get>, C<select>, C<query>, C<first>, C<exists>, assignment methods,
reference methods, and lexical path-operator registration via C<use>.

Syntactically valid pointers that do not resolve return no matches for
read APIs.

=head1 EXPORTS

=head2 Classes

=over

=item C<< JSONPointer({ path: String }) >>

Constructs a JSON Pointer selector. Returns: C<JSONPointer>.

=over

=item C<< JSONPointer.use() >>

Parameters: none. Returns: C<null>. Makes this path class the lexical
implementation for C<@>, C<@@>, and C<@?>.

=item C<< pointer.expression() >>

Parameters: none. Returns: C<String>. Returns the original pointer
expression.

=item C<< pointer.get(value) >>, C<< pointer.select(value) >>,
C<< pointer.query(value) >>

Parameters: C<value> is the query root. Returns: C<Array>. Evaluates the
pointer and returns selected values.

=item C<< pointer.first(value, fallback?) >>

Parameters: C<value> is the query root and C<fallback> is optional.
Returns: value. Returns the selected value, or C<fallback>/C<null> when
there is no match.

=item C<< pointer.exists(value) >>

Parameters: C<value> is the query root. Returns: C<Boolean>. Returns
true when the pointer resolves to a concrete value.

=item C<< pointer.assign_first(target, value, op := ":=", weak := false) >>

Parameters: C<target> is the query root, C<value> is the assignment
value, C<op> is an assignment operator, and C<weak> is accepted for path
API compatibility. Returns: value. Updates the selected location.

=item C<< pointer.assign_all(target, value, op := ":=", weak := false) >>

Parameters: same as C<assign_first>. Returns: value. Updates the
selected location when it exists.

=item C<< pointer.assign_maybe(target, value, op := ":=", weak := false) >>

Parameters: same as C<assign_first>. Returns: C<Boolean>. Updates the
selected location when it exists.

=item C<< pointer.ref_first(target) >>

Parameters: C<target> is the query root. Returns: C<Function>. Returns a
reference-like getter/setter for the selected location.

=item C<< pointer.ref_all(target) >>

Parameters: C<target> is the query root. Returns: C<Array>. Returns a
single reference-like getter/setter when the pointer resolves, otherwise
an empty array.

=item C<< pointer.ref_maybe(target) >>

Parameters: C<target> is the query root. Returns: C<Function> or
C<null>. Returns a reference-like getter/setter when the pointer
resolves.

=back

=back

=head2 Functions

=over

=item C<< extract_pointer_from_url(url) >>

Parameters: C<url> is a C<String>. Returns: C<Dict>. Splits a URL into
C<baseurl> and C<pointer>. If the URL contains C<#>, C<baseurl> is the
text before C<#> and C<pointer> is the URI-fragment percent-decoded JSON
Pointer. If the URL has no C<#>, C<baseurl> is the full URL and
C<pointer> is C<null>.

=back

=head1 SEE ALSO

Specification: L<https://www.rfc-editor.org/rfc/rfc6901>.

=head1 COPYRIGHT AND LICENCE

B<< std/path/jsonpointer >> is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under
the terms of either the Artistic License 1.0 or the GNU General Public
License version 2.

=cut

from std/string import index, ord, replace, substr;
from std/string/base64 import decode as _base64_decode;

let _B64_ALPHABET := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	_ "abcdefghijklmnopqrstuvwxyz0123456789+/";

function _jsonpointer_div_floor ( Number n, Number d ) {
	return floor( n / d );
}

function _jsonpointer_mod ( Number n, Number d ) {
	return n - _jsonpointer_div_floor( n, d ) * d;
}

function _jsonpointer_bytes_to_binary ( Array bytes ) {
	let out := "";
	let i := 0;
	let n := bytes.length();

	while ( i < n ) {
		let b0 := bytes[i];
		let b1 := null;
		let b2 := null;
		if ( i + 1 < n ) {
			b1 := bytes[i + 1];
		}
		if ( i + 2 < n ) {
			b2 := bytes[i + 2];
		}

		let c0 := _jsonpointer_div_floor( b0, 4 );
		let c1 := _jsonpointer_mod( b0, 4 ) * 16;
		let c2 := 64;
		let c3 := 64;

		if ( not( b1 == null ) ) {
			c1 += _jsonpointer_div_floor( b1, 16 );
			c2 := _jsonpointer_mod( b1, 16 ) * 4;
			if ( not( b2 == null ) ) {
				c2 += _jsonpointer_div_floor( b2, 64 );
				c3 := _jsonpointer_mod( b2, 64 );
			}
		}

		out _= substr( _B64_ALPHABET, c0, 1 );
		out _= substr( _B64_ALPHABET, c1, 1 );
		out _= c2 == 64 ? "=" : substr( _B64_ALPHABET, c2, 1 );
		out _= c3 == 64 ? "=" : substr( _B64_ALPHABET, c3, 1 );
		i += 3;
	}

	return _base64_decode(out);
}

function _jsonpointer_hex_value ( String ch ) {
	if ( ch ~ /[0-9]/ ) {
		return 0 + ch;
	}

	let lower := lc(ch);
	return 10 + index( "abcdef", lower );
}

function _jsonpointer_percent_decode ( String text ) {
	let bytes := [];
	let i := 0;
	let n := length text;

	while ( i < n ) {
		let ch := substr( text, i, 1 );
		if (
			ch \u2261 "%"
			and i + 2 < n
			and substr( text, i + 1, 1 ) ~ /[0-9A-Fa-f]/
			and substr( text, i + 2, 1 ) ~ /[0-9A-Fa-f]/
		) {
			bytes.push(
				_jsonpointer_hex_value( substr( text, i + 1, 1 ) ) * 16
				+ _jsonpointer_hex_value( substr( text, i + 2, 1 ) ),
			);
			i += 3;
			next;
		}

		let code := ord(ch);
		die "JSONPointer URL fragment contains non-ASCII literal character"
			if code > 127;
		bytes.push(code);
		i++;
	}

	return to_string( _jsonpointer_bytes_to_binary(bytes) );
}

function _jsonpointer_decode_token ( String raw ) {
	let out := replace( raw, "~1", "/", "g" );
	out := replace( out, "~0", "~", "g" );
	return out;
}

function _jsonpointer_parse ( String raw ) {
	die "JSONPointer parse error: pointer must be empty or start with '/'"
		if raw \u2262 "" and substr( raw, 0, 1 ) \u2262 "/";

	let steps := [];
	return steps if raw \u2261 "";

	let i := 1;
	let start := 1;
	let n := length raw;

	while ( i <= n ) {
		if ( i \u2261 n or substr( raw, i, 1 ) \u2261 "/" ) {
			let token := substr( raw, start, i - start );
			let j := 0;
			while ( j < length token ) {
				if ( substr( token, j, 1 ) \u2261 "~" ) {
					die "JSONPointer parse error: invalid '~' escape"
						if j + 1 >= length token;
					let esc := substr( token, j + 1, 1 );
					die "JSONPointer parse error: invalid '~' escape"
						if esc \u2262 "0" and esc \u2262 "1";
					j += 2;
					next;
				}
				j++;
			}
			steps.push( _jsonpointer_decode_token(token) );
			start := i + 1;
		}
		i++;
	}

	return steps;
}

function extract_pointer_from_url ( String url ) {
	let hash := index( url, "#" );
	if ( hash < 0 ) {
		return {
			baseurl: url,
			pointer: null,
		};
	}

	let pointer := _jsonpointer_percent_decode( substr( url, hash + 1 ) );
	_jsonpointer_parse(pointer);

	return {
		baseurl: substr( url, 0, hash ),
		pointer: pointer,
	};
}

class JSONPointer {
	let String path;
	let Array _steps := [];

	static method use () {
		from std/internals import setupperprop;
		setupperprop( 1, "paths", self );
	}

	method __build__ () {
		_steps := _jsonpointer_parse(path);
	}

	method expression () {
		return path;
	}

	method _node ( value, parent, key ) {
		return {
			value: value,
			parent: parent,
			key: key,
		};
	}

	method _evaluate_nodes ( value ) {
		let current := [ self._node( value, null, null ) ];

		for ( let step in _steps ) {
			let next_nodes := [];

			for ( let node in current ) {
				let v := node{value};

				if ( v instanceof Dict ) {
					if ( v.exists(step) ) {
						next_nodes.push( self._node( v.get(step), node, step ) );
					}
					next;
				}

				if ( v instanceof PairList ) {
					let found := v.get_all(step);
					if ( found.length() \u2261 1 ) {
						next_nodes.push( self._node( found[0], node, step ) );
					}
					next;
				}

				if ( v instanceof Array ) {
					if ( step ~ /^(0|[1-9][0-9]*)$/ ) {
						let idx := int(step);
						if ( idx < v.length() ) {
							next_nodes.push( self._node( v[idx], node, idx ) );
						}
					}
					next;
				}
			}

			current := next_nodes;
		}

		return current;
	}

	method _evaluate ( value ) {
		return self._evaluate_nodes(value).map( fn n -> n{value} );
	}

	method get ( value ) {
		return self._evaluate(value);
	}

	method select ( value ) {
		return self._evaluate(value);
	}

	method query ( value ) {
		return self._evaluate(value);
	}

	method first ( value, fallback? ) {
		let out := self._evaluate(value);
		return out.length() \u2261 0 ? fallback : out[0];
	}

	method exists ( value ) {
		return self._evaluate(value).length() > 0;
	}

	method _ref_for_node ( Dict node ) {
		let parent := node{parent};
		die "JSONPointer assignment target has no parent node"
			if parent \u2261 null;

		let container := parent{value};
		let key := node{key};

		if ( container instanceof Array ) {
			die "JSONPointer assignment expects numeric array index"
				if not( key instanceof Number );
			return \\ container[key];
		}

		if ( container instanceof Dict ) {
			die "JSONPointer assignment expects string dict key"
				if not( key instanceof String );
			return \\ container{(key)};
		}

		if ( container instanceof PairList ) {
			die "JSONPointer assignment expects string pairlist key"
				if not( key instanceof String );
			return \\ container{(key)};
		}

		die "JSONPointer assignment target container '"
			_ typeof container
			_ "' is not assignable";
	}

	method _apply_assignment_ref ( ref, value, op := ":=", weak := false ) {
		die "JSONPointer weak assignment is not supported"
			if weak;

		if ( op \u2261 ":=" ) {
			return ref(value);
		}

		let current := ref();

		if ( op \u2261 "+=" ) {
			current += value;
		}
		else if ( op \u2261 "-=" ) {
			current -= value;
		}
		else if ( op \u2261 "*=" or op \u2261 "\xD7=" ) {
			current *= value;
		}
		else if ( op \u2261 "/=" or op \u2261 "\xF7=" ) {
			current /= value;
		}
		else if ( op \u2261 "**=" ) {
			current **= value;
		}
		else if ( op \u2261 "_=" ) {
			current _= value;
		}
		else if ( op \u2261 "?:=" ) {
			current ?:= value;
		}
		else if ( op \u2261 "~=" ) {
			current ~= value[0] -> value[1](m);
		}
		else {
			die \`Unsupported path assignment operator '\${op}'\`;
		}

		ref(current);
		return current;
	}

	method _assign_all_result ( value, op, last_result ) {
		return op \u2261 "~=" ? last_result : value;
	}

	method assign_first ( target, value, op := ":=", weak := false ) {
		let nodes := self._evaluate_nodes(target);
		die "JSONPointer assignment found no matches"
			if nodes.length() \u2261 0;
		return self._apply_assignment_ref(
			self._ref_for_node( nodes[0] ),
			value,
			op,
			weak,
		);
	}

	method assign_all ( target, value, op := ":=", weak := false ) {
		let nodes := self._evaluate_nodes(target);
		if ( nodes.length() \u2261 0 ) {
			return self._assign_all_result( value, op, value );
		}

		let last_result := value;
		for ( let node in nodes ) {
			last_result := self._apply_assignment_ref(
				self._ref_for_node(node),
				value,
				op,
				weak,
			);
		}

		return self._assign_all_result( value, op, last_result );
	}

	method assign_maybe ( target, value, op := ":=", weak := false ) {
		let nodes := self._evaluate_nodes(target);
		if ( nodes.length() \u2261 0 ) {
			return false;
		}

		self._apply_assignment_ref(
			self._ref_for_node( nodes[0] ),
			value,
			op,
			weak,
		);
		return true;
	}

	method ref_first ( target ) {
		let nodes := self._evaluate_nodes(target);
		die "JSONPointer assignment found no matches"
			if nodes.length() \u2261 0;
		return self._ref_for_node( nodes[0] );
	}

	method ref_all ( target ) {
		let out := [];
		for ( let node in self._evaluate_nodes(target) ) {
			out.push( self._ref_for_node(node) );
		}
		return out;
	}

	method ref_maybe ( target ) {
		let nodes := self._evaluate_nodes(target);
		return nodes.length() \u2261 0 ? null : self._ref_for_node( nodes[0] );
	}
}
`;
        virtualFiles["/modules/std/data/json/schema.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/data/json/schema - JSON Schema 2020-12 validation.\n\n=head1 SYNOPSIS\n\n  from std/data/json/schema import\n    JSONSchema,\n    RequiredPropertyError,\n    TypeMismatchError,\n    validate,\n    valid;\n\n  let person_schema := {\n    type: "object",\n    required: [ "name" ],\n    properties: {\n      name: { type: "string" },\n      age:  { type: "integer", minimum: 0 },\n    },\n  };\n\n  say( valid( person_schema, { name: "Ada", age: 37 } ) );\n\n  let result := validate( person_schema, { age: -1 } );\n  for ( let error in result.errors() ) {\n    if ( error instanceof RequiredPropertyError ) {\n      say( error.instanceLocation() _ ": " _ error.error() );\n    }\n  }\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis Pure Zuzu module is supported by all implementations of ZuzuScript.\nNetwork reference loading needs C<std/net/http>, so it is available only in\nruntimes that provide that module.\n\n=head1 DESCRIPTION\n\nI<std/data/json/schema> validates native Zuzu values against JSON Schema\n2020-12 schemas. It is intended for already-decoded JSON data: schemas and\ninstances are normally C<Dict>, C<Array>, strings, numbers, booleans, and\nC<null>.\n\nThe validator also accepts some native collection types where the JSON model\nhas a clear equivalent. C<PairList> is treated as an object and preserves\nduplicate keys for keywords that need to inspect them. C<Set> and C<Bag> are\ntreated as array-like values when order is not important, though ordered\ntuple validation is meaningful only for C<Array>.\n\nValidation can be requested in two forms. Boolean validation short-circuits\nafter the first failure and returns C<true> or C<false>. Full validation\ncollects errors and returns a C<ValidationResult> whose errors are proper\nZuzu objects with methods such as C<keywordLocation()>,\nC<instanceLocation()>, and C<error()>.\n\n=head1 EXPORTS\n\n=head2 Functions\n\n=over\n\n=item C<< valid( schema, instance, options := {} ) >>\n\nReturns C<true> when C<instance> satisfies C<schema>, otherwise C<false>.\nThis mode is the cheapest validation mode and stops as soon as a failure is\nknown.\n\n=item C<< validate( schema, instance, options := {} ) >>\n\nReturns a C<ValidationResult>. This mode attempts to collect every\nindependent validation error it can find.\n\n=back\n\n=head2 Classes\n\n=over\n\n=item C<JSONSchema>\n\nCompiled schema wrapper. Construct with C<< new JSONSchema( schema: ... ) >>\nor pass C<options> as a named field.\n\nCommon methods:\n\n=over\n\n=item C<< is_valid( instance ) >>\n\nBoolean validation with short-circuiting.\n\n=item C<< validate( instance ) >>\n\nFull validation returning a C<ValidationResult>.\n\n=back\n\n=item C<ValidationResult>\n\nThe structured result returned by C<validate>. C<valid()> returns the boolean\nstatus. C<errors()> returns an array of C<ValidationError> objects.\nC<to_Dict()> converts to a Basic-style output shape.\n\n=item C<ValidationError>\n\nBase class for validation errors. The canonical methods are\nC<keywordLocation()>, C<absoluteKeywordLocation()>, C<instanceLocation()>,\nC<error()>, C<keyword()>, C<details()>, and C<to_Dict()>.\n\nErrors are grouped under C<MissingValueError>, C<UnexpectedValueError>, and\nC<WrongValueError>. The module exports specific subclasses for individual\nkeywords such as C<RequiredPropertyError>, C<TypeMismatchError>,\nC<MaximumError>, C<PatternError>, C<AdditionalPropertiesError>,\nC<OneOfError>, and C<ReferenceResolutionError>.\n\n=item C<SubschemaError>\n\nError class used for the message C<A subschema had errors.>. Its\nC<suberrors()> method returns weak links to the errors produced inside the\nsubschema.\n\n=item C<SchemaRegistry>\n\nRegistry for schema resources, anchors, and references. It is usually\nmanaged by C<JSONSchema>, but may be supplied in C<options> when several\nschemas share references.\n\n=item C<HTTPResourceLoader>\n\nReference loader for HTTP and HTTPS resources. It is used only when supplied\ndirectly or when C<allow_network> is true.\n\n=item C<FormatRegistry>\n\nRegistry of C<format> validators. A custom registry may be passed with the\nC<formats> or C<format_registry> option.\n\n=item C<RelativeJSONPointer>\n\nParser and evaluator for Relative JSON Pointers. This class is exported\nbecause JSON Schema uses the syntax for the C<relative-json-pointer> format\nand because it is useful with schema-adjacent data tools.\n\n=back\n\n=head1 OPTIONS\n\nThe C<options> value may be a C<Dict> or C<PairList>.\n\n=over\n\n=item C<base_uri>\n\nBase URI used when registering the root schema and resolving relative\nreferences.\n\n=item C<registry>\n\nA C<SchemaRegistry> to use for C<$ref> and C<$dynamicRef>.\n\n=item C<loader>\n\nA callable or object with a C<load(uri)> method used to fetch missing schema\nresources.\n\n=item C<allow_network>\n\nWhen true and no loader is supplied, C<JSONSchema> creates an\nC<HTTPResourceLoader>.\n\n=item C<formats> or C<format_registry>\n\nA C<FormatRegistry> used for C<format> checks.\n\n=item C<format_assert>\n\nWhen false, C<format> is treated as an annotation and does not make\nvalidation fail.\n\n=item C<unknown_format>\n\nControls unknown formats. The default is C<fail>; C<ignore> treats unknown\nformats as annotations.\n\n=back\n\n=head1 KNOWN OPTIONAL FIXTURE GAPS\n\nThe validator covers all required JSON Schema draft 2020-12 fixture files\nand many optional fixture files. The following optional fixture files are not\nyet promoted to the expected-passing set.\n\n=over\n\n=item F<optional/cross-draft.json>\n\nReferences into older schema drafts are resolved, but draft-specific\nvalidation semantics for referenced historic drafts are not yet applied.\n\n=item F<optional/float-overflow.json>\n\nVery large numeric values still use the host numeric model, so overflow and\nprecision edge cases for C<multipleOf> are not fully handled.\n\n=item F<optional/ecmascript-regex.json>\n\nThe JavaScript runtime passes this fixture, but the Perl and Rust runtimes do\nnot yet emulate enough ECMAScript regular-expression semantics.\n\n=item F<optional/format/duration.json>\n\nThe C<duration> format checker accepts basic duration shapes, but does not\nyet implement the full RFC 3339 duration grammar.\n\n=item F<optional/format/hostname.json>\n\nHostname validation is intentionally conservative and does not yet fully\nvalidate A-label, Punycode, and IDNA edge cases.\n\n=item F<optional/format/idn-hostname.json>\n\nInternationalized hostname validation does not yet implement the full IDNA\nUnicode category, normalization, and bidirectional-text rules.\n\n=item F<optional/format/ipv6.json>\n\nIPv6 validation is still simplified and misses some invalid compression and\ngroup-length edge cases.\n\n=item F<optional/format/time.json>\n\nTime validation handles common RFC 3339 forms, but still has some leap-second\nand timezone-offset edge cases.\n\n=item F<optional/format/uri.json>\n\nURI validation is stricter than a plain string check, but still accepts some\ninvalid authority, userinfo, character, and port cases.\n\n=back\n\n=head1 PORTABILITY\n\nThe module is pure ZuzuScript. Behaviour that depends on regular expression\ndetails or HTTP support may vary with the host runtime.\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/data/json/schema >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/data/json/schema/core import HTTPResourceLoader, SchemaRegistry;\nfrom std/data/json/schema/format import FormatRegistry;\nfrom std/data/json/schema/output import\n	AdditionalItemsError,\n	AdditionalPropertiesError,\n	AllOfError,\n	AnyOfError,\n	ConstMismatchError,\n	ContentEncodingError,\n	ContentMediaTypeError,\n	DependentRequiredPropertyError,\n	EnumMismatchError,\n	ExclusiveMaximumError,\n	ExclusiveMinimumError,\n	FalseSchemaError,\n	FormatError,\n	IfThenElseError,\n	MaxContainsError,\n	MaximumError,\n	MaxItemsError,\n	MaxLengthError,\n	MaxPropertiesError,\n	MinContainsError,\n	MinimumError,\n	MinItemsError,\n	MinLengthError,\n	MinPropertiesError,\n	MissingValueError,\n	MultipleOfError,\n	NotMatchedError,\n	OneOfError,\n	PatternError,\n	PropertyNamesError,\n	ReferenceResolutionError,\n	RequiredPropertyError,\n	SubschemaError,\n	TypeMismatchError,\n	UnevaluatedItemsError,\n	UnevaluatedPropertiesError,\n	UnexpectedValueError,\n	UniqueItemsError,\n	UnknownFormatError,\n	ValidationError,\n	ValidationResult,\n	WrongValueError;\nfrom std/data/json/schema/relative_pointer import RelativeJSONPointer;\nfrom std/data/json/schema/validation import JSONSchema, validate, valid;\n';
        virtualFiles["/modules/std/data/json/schema/core.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/data/json/schema/core - JSON Schema resources and reference registry.\n\n=head1 SYNOPSIS\n\n  from std/data/json/schema/core import SchemaRegistry;\n\n  let registry := new SchemaRegistry();\n  registry.register( address_schema, "https://example.test/address" );\n\n  let subschema := registry.resolve(\n    "https://example.test/address#/properties/postcode",\n  );\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis Pure Zuzu module is supported by all implementations of ZuzuScript.\nC<HTTPResourceLoader> requires C<std/net/http> and dies at construction time\nwhen that module is unavailable.\n\n=head1 DESCRIPTION\n\nThis module contains the resource and reference support used by\nI<std/data/json/schema>. It registers schemas under base URIs, indexes\nC<$id>, C<$anchor>, and C<$dynamicAnchor>, and resolves references to either\nwhole resources or JSON Pointer fragments.\n\nMost callers should use C<JSONSchema> from I<std/data/json/schema>. Import\nthis module directly when schemas need to share a registry or when reference\nloading needs to be customised.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<SchemaRegistry>\n\nStores schema resources and resolves references.\n\n=over\n\n=item C<< register( schema, uri := "" ) >>\n\nRegisters C<schema> at C<uri>, indexes nested C<$id> values and anchors, and\nreturns the registry.\n\n=item C<< set_loader( loader ) >>\n\nSets the loader used for missing resources. A loader may be a callable or an\nobject with a C<load(uri)> method. Loaded strings are decoded as JSON before\nbeing registered.\n\n=item C<< resolve( ref, base := "" ) >>\n\nResolves C<ref> against C<base>. Empty fragments return the resource.\nAnchor fragments use the registry\'s anchor index. Pointer fragments are\nresolved with I<std/path/jsonpointer>. Failure to find a resource or target\nthrows an exception.\n\n=back\n\n=item C<HTTPResourceLoader>\n\nSimple HTTP and HTTPS loader. C<load(uri)> fetches C<uri> with\nC<std/net/http> and returns the response content after requiring a successful\nresponse.\n\n=back\n\n=head2 Functions\n\n=over\n\n=item C<< jschema_uri_resolve( base, ref ) >>\n\nResolves the URI reference C<ref> against C<base> for the subset of URI\nresolution needed by this validator.\n\n=item C<< jschema_url_split( url ) >>\n\nReturns a C<Dict> with C<baseurl> and C<fragment>. C<fragment> is C<null>\nwhen C<url> has no C<#>.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/data/json/schema/core >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/data/json import JSON;\nfrom std/internals import ref_id;\nfrom std/net/http try import UserAgent as _HTTPUserAgent;\nfrom std/path/jsonpointer import JSONPointer;\nfrom std/string import index, join, ord, split, substr;\nfrom std/string/base64 import decode as _base64_decode;\nfrom std/data/json/schema/model import\n	jschema_is_object,\n	jschema_object_entries,\n	jschema_object_get,\n	jschema_object_has;\n\nfunction jschema_url_split ( String url ) {\n	let hash := index( url, "#" );\n	if ( hash < 0 ) {\n		return {\n			baseurl: url,\n			fragment: null,\n		};\n	}\n	return {\n		baseurl: substr( url, 0, hash ),\n		fragment: substr( url, hash + 1 ),\n	};\n}\n\nlet _JSCHEMA_B64_ALPHABET := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"\n	_ "abcdefghijklmnopqrstuvwxyz0123456789+/";\n\nfunction _jschema_div_floor ( Number n, Number d ) {\n	return floor( n / d );\n}\n\nfunction _jschema_mod ( Number n, Number d ) {\n	return n - _jschema_div_floor( n, d ) * d;\n}\n\nfunction _jschema_bytes_to_binary ( Array bytes ) {\n	let out := "";\n	let i := 0;\n	let n := bytes.length();\n\n	while ( i < n ) {\n		let b0 := bytes[i];\n		let b1 := null;\n		let b2 := null;\n		if ( i + 1 < n ) {\n			b1 := bytes[i + 1];\n		}\n		if ( i + 2 < n ) {\n			b2 := bytes[i + 2];\n		}\n\n		let c0 := _jschema_div_floor( b0, 4 );\n		let c1 := _jschema_mod( b0, 4 ) * 16;\n		let c2 := 64;\n		let c3 := 64;\n\n		if ( not( b1 == null ) ) {\n			c1 += _jschema_div_floor( b1, 16 );\n			c2 := _jschema_mod( b1, 16 ) * 4;\n			if ( not( b2 == null ) ) {\n				c2 += _jschema_div_floor( b2, 64 );\n				c3 := _jschema_mod( b2, 64 );\n			}\n		}\n\n		out _= substr( _JSCHEMA_B64_ALPHABET, c0, 1 );\n		out _= substr( _JSCHEMA_B64_ALPHABET, c1, 1 );\n		out _= c2 == 64 ? "=" : substr( _JSCHEMA_B64_ALPHABET, c2, 1 );\n		out _= c3 == 64 ? "=" : substr( _JSCHEMA_B64_ALPHABET, c3, 1 );\n		i += 3;\n	}\n\n	return _base64_decode(out);\n}\n\nfunction _jschema_hex_value ( String ch ) {\n	if ( ch ~ /[0-9]/ ) {\n		return 0 + ch;\n	}\n\n	return 10 + index( "abcdef", lc(ch) );\n}\n\nfunction jschema_percent_decode ( String text ) {\n	let bytes := [];\n	let i := 0;\n	let n := length text;\n\n	while ( i < n ) {\n		let ch := substr( text, i, 1 );\n		if (\n			ch \u2261 "%"\n			and i + 2 < n\n			and substr( text, i + 1, 1 ) ~ /[0-9A-Fa-f]/\n			and substr( text, i + 2, 1 ) ~ /[0-9A-Fa-f]/\n		) {\n			bytes.push(\n				_jschema_hex_value( substr( text, i + 1, 1 ) ) * 16\n				+ _jschema_hex_value( substr( text, i + 2, 1 ) ),\n			);\n			i += 3;\n			next;\n		}\n\n		let code := ord(ch);\n		die "JSON Schema URI fragment contains non-ASCII literal character"\n			if code > 127;\n		bytes.push(code);\n		i++;\n	}\n\n	return to_string( _jschema_bytes_to_binary(bytes) );\n}\n\nfunction _jschema_uri_query_split ( String uri ) {\n	let query := index( uri, "?" );\n	if ( query < 0 ) {\n		return {\n			path: uri,\n			query: "",\n		};\n	}\n	return {\n		path: substr( uri, 0, query ),\n		query: substr( uri, query ),\n	};\n}\n\nfunction _jschema_uri_parts ( String uri ) {\n	let m := uri ~ /^([A-Za-z][A-Za-z0-9+.-]*:\\/\\/[^\\/?#]*)(.*)$/;\n	if ( m ) {\n		return {\n			prefix: m[1],\n			path_query: m[2],\n		};\n	}\n\n	m := uri ~ /^([A-Za-z][A-Za-z0-9+.-]*:)(.*)$/;\n	if ( m ) {\n		return {\n			prefix: m[1],\n			path_query: m[2],\n		};\n	}\n\n	return {\n		prefix: "",\n		path_query: uri,\n	};\n}\n\nfunction _jschema_remove_dot_segments ( String path ) {\n	let absolute := length path > 0 and substr( path, 0, 1 ) eq "/";\n	let trailing := length path > 1 and substr( path, length path - 1, 1 ) eq "/";\n	let out := [];\n\n	for ( let segment in split( path, "/" ) ) {\n		if ( segment eq "" or segment eq "." ) {\n			next;\n		}\n		if ( segment eq ".." ) {\n			if (\n				out.length() > 0\n				and out[out.length() - 1] ne ".."\n			) {\n				out.pop();\n			}\n			else if ( not absolute ) {\n				out.push(segment);\n			}\n			next;\n		}\n		out.push(segment);\n	}\n\n	let result := join( "/", out );\n	if ( absolute ) {\n		result := "/" _ result;\n	}\n	if ( trailing and result ne "/" ) {\n		result _= "/";\n	}\n	if ( result eq "" and absolute ) {\n		return "/";\n	}\n	return result;\n}\n\nfunction jschema_uri_resolve ( String base, String ref ) {\n	let split_ref := jschema_url_split(ref);\n	let ref_base := split_ref{baseurl};\n	let fragment := split_ref{fragment} \u2261 null\n		? ""\n		: "#" _ split_ref{fragment};\n\n	if ( ref ~ /^[A-Za-z][A-Za-z0-9+.-]*:/ ) {\n		let absolute_parts := _jschema_uri_parts(ref_base);\n		let absolute_query := _jschema_uri_query_split(\n			absolute_parts{path_query},\n		);\n		return absolute_parts{prefix}\n			_ _jschema_remove_dot_segments(absolute_query{path})\n			_ absolute_query{query}\n			_ fragment;\n	}\n	if ( substr( ref, 0, 1 ) eq "#" ) {\n		return jschema_url_split(base){baseurl} _ ref;\n	}\n	if ( base eq "" ) {\n		return ref;\n	}\n\n	let split_base := jschema_url_split(base){baseurl};\n	if ( ref_base eq "" ) {\n		return split_base _ fragment;\n	}\n\n	let base_parts := _jschema_uri_parts(split_base);\n	let base_query := _jschema_uri_query_split(base_parts{path_query});\n	let ref_query := _jschema_uri_query_split(ref_base);\n\n	if ( substr( ref_base, 0, 1 ) eq "?" ) {\n		return base_parts{prefix} _ base_query{path} _ ref_base _ fragment;\n	}\n\n	if ( substr( ref_query{path}, 0, 1 ) eq "/" ) {\n		return base_parts{prefix}\n			_ _jschema_remove_dot_segments(ref_query{path})\n			_ ref_query{query}\n			_ fragment;\n	}\n\n	let slash := -1;\n	let i := 0;\n	while ( i < length base_query{path} ) {\n		if ( substr( base_query{path}, i, 1 ) eq "/" ) {\n			slash := i;\n		}\n		i++;\n	}\n\n	let base_dir := slash >= 0 ? substr( base_query{path}, 0, slash + 1 ) : "";\n	return base_parts{prefix}\n		_ _jschema_remove_dot_segments( base_dir _ ref_query{path} )\n		_ ref_query{query}\n		_ fragment;\n}\n\nclass HTTPResourceLoader {\n	let _ua := null;\n\n	method __build__ () {\n		die "std/net/http UserAgent is unavailable in this runtime"\n			if _HTTPUserAgent \u2261 null;\n		_ua := new _HTTPUserAgent();\n	}\n\n	method load ( String uri ) {\n		die `JSON Schema network loader only supports HTTP(S): ${uri}`\n			unless uri ~ /^https?:/;\n		return _ua.get(uri).expect_success().content();\n	}\n}\n\nclass SchemaRegistry {\n	let _resources := {};\n	let _anchors := {};\n	let _dynamic_anchors := {};\n	let _schema_bases := [];\n	let _loader := null;\n	let Boolean allow_network := false;\n	let _json := null;\n\n	method __build__ () {\n		_json := new JSON();\n	}\n\n	method set_loader ( loader ) {\n		_loader := loader;\n		return self;\n	}\n\n	method register ( schema, String uri := "" ) {\n		_resources.set( uri, schema );\n		self._index_schema( schema, uri );\n		return self;\n	}\n\n	method _index_subschema ( schema, String base ) {\n		if ( jschema_is_object(schema) ) {\n			self._index_schema( schema, base );\n		}\n	}\n\n	method _index_subschema_array ( value, String base ) {\n		if ( not( value instanceof Array ) ) {\n			return;\n		}\n		for ( let item in value ) {\n			self._index_subschema( item, base );\n		}\n	}\n\n	method _index_subschema_map ( value, String base ) {\n		if ( not jschema_is_object(value) ) {\n			return;\n		}\n		for ( let entry in jschema_object_entries(value) ) {\n			self._index_subschema( entry[1], base );\n		}\n	}\n\n	method _index_schema ( schema, String base ) {\n		if ( not jschema_is_object(schema) ) {\n			return;\n		}\n		let current_base := base;\n\n		if (\n			jschema_object_has( schema, "$id" )\n			and jschema_object_get( schema, "$id" ) instanceof String\n		) {\n			current_base := jschema_uri_resolve(\n				current_base,\n				jschema_object_get( schema, "$id" ),\n			);\n			_resources.set( current_base, schema );\n		}\n		_schema_bases.push( {\n			id: ref_id(schema),\n			base: current_base,\n		} );\n		if (\n			jschema_object_has( schema, "$anchor" )\n			and jschema_object_get( schema, "$anchor" ) instanceof String\n		) {\n			_anchors.set(\n				current_base _ "#" _ jschema_object_get( schema, "$anchor" ),\n				schema,\n			);\n		}\n		if (\n			jschema_object_has( schema, "$dynamicAnchor" )\n			and jschema_object_get( schema, "$dynamicAnchor" ) instanceof String\n		) {\n			_anchors.set(\n				current_base _ "#" _ jschema_object_get( schema, "$dynamicAnchor" ),\n				schema,\n			);\n			_dynamic_anchors.set(\n				current_base _ "#" _ jschema_object_get( schema, "$dynamicAnchor" ),\n				schema,\n			);\n		}\n\n		self._index_subschema_map( jschema_object_get( schema, "$defs" ), current_base );\n		self._index_subschema_map( jschema_object_get( schema, "definitions" ), current_base );\n		self._index_subschema_map( jschema_object_get( schema, "properties" ), current_base );\n		self._index_subschema_map( jschema_object_get( schema, "patternProperties" ), current_base );\n		self._index_subschema_map( jschema_object_get( schema, "dependentSchemas" ), current_base );\n\n		if ( jschema_is_object( jschema_object_get( schema, "dependencies" ) ) ) {\n			for ( let entry in jschema_object_entries( jschema_object_get( schema, "dependencies" ) ) ) {\n				self._index_subschema( entry[1], current_base );\n			}\n		}\n\n		self._index_subschema_array( jschema_object_get( schema, "allOf" ), current_base );\n		self._index_subschema_array( jschema_object_get( schema, "anyOf" ), current_base );\n		self._index_subschema_array( jschema_object_get( schema, "oneOf" ), current_base );\n		self._index_subschema_array( jschema_object_get( schema, "prefixItems" ), current_base );\n\n		self._index_subschema( jschema_object_get( schema, "not" ), current_base );\n		self._index_subschema( jschema_object_get( schema, "if" ), current_base );\n		self._index_subschema( jschema_object_get( schema, "then" ), current_base );\n		self._index_subschema( jschema_object_get( schema, "else" ), current_base );\n		self._index_subschema( jschema_object_get( schema, "items" ), current_base );\n		self._index_subschema( jschema_object_get( schema, "contains" ), current_base );\n		self._index_subschema( jschema_object_get( schema, "additionalProperties" ), current_base );\n		self._index_subschema( jschema_object_get( schema, "unevaluatedItems" ), current_base );\n		self._index_subschema( jschema_object_get( schema, "unevaluatedProperties" ), current_base );\n		self._index_subschema( jschema_object_get( schema, "propertyNames" ), current_base );\n		self._index_subschema( jschema_object_get( schema, "contentSchema" ), current_base );\n	}\n\n	method _load_resource ( String uri ) {\n		if ( _loader \u2261 null ) {\n			return null;\n		}\n\n		let loaded;\n		if ( _loader can load ) {\n			loaded := _loader.load(uri);\n		}\n		else {\n			loaded := _loader(uri);\n		}\n		if ( loaded instanceof String ) {\n			loaded := _json.decode(loaded);\n		}\n		else if ( loaded instanceof BinaryString ) {\n			loaded := _json.decode_binarystring(loaded);\n		}\n		self.register( loaded, uri );\n		return loaded;\n	}\n\n	method resolve_info ( String ref, String base := "" ) {\n		let absolute_uri := jschema_uri_resolve( base, ref );\n		let split := jschema_url_split(absolute_uri);\n		let resource_uri := split{baseurl};\n		let fragment := split{fragment} \u2261 null\n			? null\n			: jschema_percent_decode(split{fragment});\n\n		let resource := _resources.exists(resource_uri)\n			? _resources.get(resource_uri)\n			: self._load_resource(resource_uri);\n		if ( resource \u2261 null ) {\n			die `JSON Schema reference not found: ${absolute_uri}`;\n		}\n\n		let target := resource;\n		if ( fragment \u2262 null and fragment ne "" ) {\n			let anchor_uri := resource_uri _ "#" _ fragment;\n			if ( _anchors.exists(anchor_uri) ) {\n				target := _anchors.get(anchor_uri);\n			}\n			else {\n				die `JSON Schema reference fragment is not a JSON Pointer: ${absolute_uri}`\n					unless substr( fragment, 0, 1 ) eq "/";\n\n				target := new JSONPointer( path: fragment ).first( resource, null );\n				die `JSON Schema reference target not found: ${absolute_uri}`\n					if target \u2261 null;\n			}\n		}\n\n		return {\n			target: target,\n			absolute_uri: absolute_uri,\n			resource_uri: resource_uri,\n			fragment: fragment,\n		};\n	}\n\n	method resolve ( String ref, String base := "" ) {\n		return self.resolve_info( ref, base ){target};\n	}\n\n	method dynamic_anchor ( String resource_uri, String name ) {\n		let key := resource_uri _ "#" _ name;\n		return _dynamic_anchors.exists(key)\n			? _dynamic_anchors.get(key)\n			: null;\n	}\n\n	method has_dynamic_anchor ( String resource_uri, String name ) {\n		return _dynamic_anchors.exists( resource_uri _ "#" _ name );\n	}\n\n	method schema_base ( schema, fallback := null ) {\n		let id := ref_id(schema);\n		for ( let entry in _schema_bases ) {\n			if ( entry{id} \u2261 id ) {\n				return entry{base};\n			}\n		}\n		return fallback;\n	}\n}\n';
        virtualFiles["/modules/std/data/json/schema/format.zzm"] = `=encoding utf8

=head1 NAME

std/data/json/schema/format - JSON Schema format validators.

=head1 SYNOPSIS

  from std/data/json/schema/format import FormatRegistry;

  let formats := new FormatRegistry();
  formats.register( "slug", fn value -> value ~ /^[a-z0-9-]+$/ );

  say( formats.check( "slug", "release-2026" ) );

=head1 IMPLEMENTATION SUPPORT

This Pure Zuzu module is supported by all implementations of ZuzuScript.

=head1 DESCRIPTION

I<std/data/json/schema/format> provides the C<format> registry used by the
JSON Schema validator. A registry maps format names to callables. A callable
receives the instance value and returns true when the value satisfies the
format.

The default registry includes validators for the standard JSON Schema
formats: C<date-time>, C<date>, C<time>, C<duration>, C<email>,
C<idn-email>, C<hostname>, C<idn-hostname>, C<ipv4>, C<ipv6>, C<uri>,
C<uri-reference>, C<iri>, C<iri-reference>, C<uuid>, C<json-pointer>,
C<relative-json-pointer>, and C<regex>.

Format checking is controlled by the validator. By default C<format> is
annotation-only; pass C<< format_assert: true >> to C<JSONSchema> to make it
assertive.

=head1 EXPORTS

=head2 Classes

=over

=item C<FormatRegistry>

Registry of named format validators.

=over

=item C<< register( name, validator ) >>

Registers C<validator> under C<name> and returns the registry. The validator
may be any callable value.

=item C<< has( name ) >>

Returns true when a validator has been registered for C<name>.

=item C<< check( name, value ) >>

Returns the result of the named validator. Unknown names return C<false>;
the higher-level validator decides whether an unknown format is ignored or
reported as an error.

=back

=back

=head1 PORTABILITY

Some validators rely on the host runtime's regular expression engine. The
validators are intentionally conservative and do not attempt full RFC-grade
parsing for every format.

=head1 COPYRIGHT AND LICENCE

B<< std/data/json/schema/format >> is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under
the terms of either the Artistic License 1.0 or the GNU General Public
License version 2.

=cut

from std/internals import to_Regexp_with_flags;
from std/path/jsonpointer import JSONPointer;
from std/data/json/schema/relative_pointer import valid_relative_json_pointer;
from std/string import index, ord, substr, split;

function _fmt_ipv4_ok;
function _fmt_ipv6_ok;
function _fmt_uri_reference_ok;
function _fmt_regex_hex;

function _fmt_regex ( String pattern ) {
	return fn value -> value instanceof String
		and value ~ to_Regexp_with_flags(pattern, "u");
}

function _fmt_date_parts_ok ( String value ) {
	let m := value ~ /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/;
	if ( not m ) { return false; }
	let month := int(m[2]);
	let day := int(m[3]);
	if ( month < 1 or month > 12 ) { return false; }
	let max := 31;
	if ( month in [ 4, 6, 9, 11 ] ) {
		max := 30;
	}
	else if ( month == 2 ) {
		let year := int(m[1]);
		let leap := ( year mod 400 == 0 )
			or ( year mod 4 == 0 and year mod 100 != 0 );
		max := leap ? 29 : 28;
	}
	return day >= 1 and day <= max;
}

function _fmt_time_ok ( String value ) {
	let m := value ~ /^([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\\.[0-9]+)?(?:[Zz]|([+-])([0-9]{2}):([0-9]{2}))$/;
	if ( not m ) { return false; }
	let hour := int(m[1]);
	let minute := int(m[2]);
	let second := int(m[3]);
	let has_offset := m[4] instanceof String and m[4] ne "";
	if ( hour > 23 or minute > 59 ) { return false; }
	if ( second > 60 ) { return false; }
	if ( has_offset ) {
		if ( int(m[5]) > 23 or int(m[6]) > 59 ) { return false; }
	}
	if ( second == 60 and minute != 59 ) { return false; }
	if ( second == 60 and not has_offset and hour != 23 ) { return false; }
	return true;
}

function _fmt_date_time_ok ( value ) {
	if ( not( value instanceof String ) ) { return false; }
	let m := value ~ /^([0-9]{4}-[0-9]{2}-[0-9]{2})[Tt]([0-9]{2}:[0-9]{2}:[0-9]{2}(?:\\.[0-9]+)?(?:[Zz]|[+-][0-9]{2}:[0-9]{2}))$/;
	return m and _fmt_date_parts_ok(m[1]) and _fmt_time_ok(m[2]);
}

function _fmt_date_ok ( value ) {
	return value instanceof String and _fmt_date_parts_ok(value);
}

function _fmt_time_value_ok ( value ) {
	return value instanceof String and _fmt_time_ok(value);
}

function _fmt_duration_ok ( value ) {
	return value instanceof String
		and length value > 1
		and value ~ /^P[0-9YMWDTHS.,+-]+$/;
}

function _fmt_hostname_ok ( value ) {
	if ( not( value instanceof String ) ) { return false; }
	if ( length value > 253 ) { return false; }
	if ( value eq "" ) { return false; }
	for ( let label in split( value, "." ) ) {
		if ( label eq "" or length label > 63 ) { return false; }
		if ( not( label ~ /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/ ) ) {
			return false;
		}
	}
	return true;
}

function _fmt_email_ok ( value ) {
	if ( not( value instanceof String ) ) { return false; }
	let address;
	try {
		from std/mail import Address;
		address := Address.parse(value);
	}
	catch {
		return false;
	}
	if ( address.display_name() \u2262 null ) { return false; }
	let domain := address.domain();
	if ( substr( domain, 0, 1 ) eq "[" ) {
		let inner := substr( domain, 1, length domain - 2 );
		if ( substr( inner, 0, 5 ) eq "IPv6:" ) {
			return _fmt_ipv6_ok( substr( inner, 5 ) );
		}
		return _fmt_ipv4_ok(inner);
	}
	return _fmt_hostname_ok(domain);
}

function _fmt_idn_hostname_ok ( value ) {
	if ( not( value instanceof String ) ) { return false; }
	if ( length value > 253 ) { return false; }
	if ( value eq "" or value ~ /\\s/ ) { return false; }
	for ( let label in split( value, "." ) ) {
		if ( label eq "" or length label > 63 ) { return false; }
		if ( substr( label, 0, 1 ) eq "-" ) { return false; }
		if ( substr( label, length label - 1, 1 ) eq "-" ) { return false; }
	}
	return true;
}

function _fmt_idn_email_ok ( value ) {
	if ( not( value instanceof String ) ) { return false; }
	let m := value ~ /^([^@\\s]+)@([^@\\s]+)$/;
	return m and _fmt_idn_hostname_ok(m[2]);
}

function _fmt_ipv4_ok ( value ) {
	if ( not( value instanceof String ) ) { return false; }
	if ( value ~ /[\\r\\n]/ ) { return false; }
	if ( value eq "" or substr( value, 0, 1 ) eq "." ) { return false; }
	if ( substr( value, length value - 1, 1 ) eq "." ) { return false; }
	let parts := split( value, "." );
	if ( parts.length() != 4 ) { return false; }
	for ( let part in parts ) {
		if ( not( part ~ /^(0|[1-9][0-9]*)$/ ) ) { return false; }
		let n := int(part);
		if ( n > 255 ) { return false; }
	}
	return true;
}

function _fmt_ipv6_ok ( value ) {
	if ( not( value instanceof String ) ) { return false; }
	if ( not( value ~ /^[0-9A-Fa-f:.]+$/ ) ) { return false; }
	if ( value ~ /::/ ) { return true; }
	return split( value, ":" ).length() == 8;
}

function _fmt_uri_ok ( value ) {
	return value instanceof String
		and value ~ /^[A-Za-z][A-Za-z0-9+.-]*:[^\\s]*$/
		and _fmt_uri_reference_ok(value);
}

function _fmt_uri_chars_ok ( String value, Boolean allow_non_ascii ) {
	if ( value ~ /[\\s\\\\]/ ) { return false; }
	let i := 0;
	while ( i < length value ) {
		let ch := substr( value, i, 1 );
		let cp := ord(ch);
		if ( ch eq "%" ) {
			if ( not _fmt_regex_hex( value, i + 1, 2 ) ) {
				return false;
			}
			i += 3;
			next;
		}
		if ( not allow_non_ascii and cp > 127 ) {
			return false;
		}
		i++;
	}
	return true;
}

function _fmt_uri_reference_ok ( value ) {
	return value instanceof String and _fmt_uri_chars_ok( value, false );
}

function _fmt_last_index ( String value, String needle ) {
	let found := -1;
	let i := 0;
	while ( i < length value ) {
		if ( substr( value, i, length needle ) eq needle ) {
			found := i;
		}
		i++;
	}
	return found;
}

function _fmt_authority_from_iri ( String value ) {
	let scheme := index( value, ":" );
	if ( scheme < 0 or substr( value, scheme + 1, 2 ) ne "//" ) {
		return null;
	}
	let start := scheme + 3;
	let end := start;
	while ( end < length value ) {
		let ch := substr( value, end, 1 );
		if ( ch eq "/" or ch eq "?" or ch eq "#" ) {
			last;
		}
		end++;
	}
	return substr( value, start, end - start );
}

function _fmt_colon_count ( String value ) {
	let count := 0;
	let i := 0;
	while ( i < length value ) {
		if ( substr( value, i, 1 ) eq ":" ) {
			count++;
		}
		i++;
	}
	return count;
}

function _fmt_iri_authority_ok ( String authority ) {
	if ( authority eq "" or authority ~ /[\\s\\\\]/ ) { return false; }
	let hostport := authority;
	let at := _fmt_last_index( authority, "@" );
	if ( at >= 0 ) {
		hostport := substr( authority, at + 1 );
	}
	if ( hostport eq "" ) { return false; }
	if ( substr( hostport, 0, 1 ) eq "[" ) {
		let close := index( hostport, "]" );
		if ( close < 0 ) { return false; }
		let literal := substr( hostport, 1, close - 1 );
		let rest := substr( hostport, close + 1 );
		if ( not _fmt_ipv6_ok(literal) ) { return false; }
		return rest eq "" or rest ~ /^:[0-9]+$/;
	}
	return _fmt_colon_count(hostport) <= 1;
}

function _fmt_iri_ok ( value ) {
	if ( not( value instanceof String ) ) { return false; }
	if ( not _fmt_uri_chars_ok( value, true ) ) { return false; }
	if ( not( value ~ /^[A-Za-z][A-Za-z0-9+.-]*:/ ) ) { return false; }
	let authority := _fmt_authority_from_iri(value);
	return authority \u2261 null or _fmt_iri_authority_ok(authority);
}

function _fmt_iri_reference_ok ( value ) {
	if ( not( value instanceof String ) ) { return false; }
	if ( not _fmt_uri_chars_ok( value, true ) ) { return false; }
	if ( value ~ /^[A-Za-z][A-Za-z0-9+.-]*:/ ) {
		return _fmt_iri_ok(value);
	}
	if ( substr( value, 0, 2 ) eq "//" ) {
		let authority := _fmt_authority_from_iri( "x:" _ value );
		return authority \u2262 null and _fmt_iri_authority_ok(authority);
	}
	return true;
}

function _fmt_regex_hex ( String value, Number start, Number count ) {
	if ( start + count > length value ) {
		return false;
	}
	let i := start;
	while ( i < start + count ) {
		if ( not( substr( value, i, 1 ) ~ /[0-9A-Fa-f]/ ) ) {
			return false;
		}
		i++;
	}
	return true;
}

function _fmt_regex_escape_ok ( String value, Number slash, Boolean in_class ) {
	if ( slash + 1 >= length value ) {
		return {
			ok: false,
			next: slash + 1,
		};
	}

	let esc := substr( value, slash + 1, 1 );
	if ( esc ~ /[fnrtv0bBdDsSwW]/ ) {
		return {
			ok: true,
			next: slash + 2,
		};
	}
	if ( esc eq "c" ) {
		return {
			ok: slash + 2 < length value
				and substr( value, slash + 2, 1 ) ~ /[A-Za-z]/,
			next: slash + 3,
		};
	}
	if ( esc eq "x" ) {
		return {
			ok: _fmt_regex_hex( value, slash + 2, 2 ),
			next: slash + 4,
		};
	}
	if ( esc eq "u" ) {
		if ( slash + 2 < length value and substr( value, slash + 2, 1 ) eq "{" ) {
			let i := slash + 3;
			let digits := 0;
			while ( i < length value and substr( value, i, 1 ) ne "}" ) {
				if ( not( substr( value, i, 1 ) ~ /[0-9A-Fa-f]/ ) ) {
					return {
						ok: false,
						next: i + 1,
					};
				}
				digits++;
				i++;
			}
			return {
				ok: i < length value and digits > 0,
				next: i + 1,
			};
		}
		return {
			ok: _fmt_regex_hex( value, slash + 2, 4 ),
			next: slash + 6,
		};
	}
	if ( esc eq "p" or esc eq "P" ) {
		let open := slash + 2;
		if ( open >= length value or substr( value, open, 1 ) ne "{" ) {
			return {
				ok: false,
				next: open,
			};
		}
		let close := open + 1;
		while ( close < length value and substr( value, close, 1 ) ne "}" ) {
			close++;
		}
		return {
			ok: close < length value and close > open + 1,
			next: close + 1,
		};
	}
	if ( esc ~ /[A-Za-z]/ ) {
		return {
			ok: false,
			next: slash + 2,
		};
	}

	return {
		ok: true,
		next: slash + 2,
	};
}

function _fmt_json_pointer_ok ( value ) {
	if ( not( value instanceof String ) ) { return false; }
	try {
		new JSONPointer( path: value );
		return true;
	}
	catch {
		return false;
	}
}

function _fmt_regex_ok ( value ) {
	if ( not( value instanceof String ) ) { return false; }
	let parens := 0;
	let in_class := false;
	let class_items := 0;
	let i := 0;

	while ( i < length value ) {
		let ch := substr( value, i, 1 );
		if ( ch eq "\\\\" ) {
			let escaped := _fmt_regex_escape_ok( value, i, in_class );
			if ( not escaped{ok} ) {
				return false;
			}
			if ( in_class ) {
				class_items++;
			}
			i := escaped{next};
			next;
		}
		if ( in_class ) {
			if ( ch eq "]" and class_items > 0 ) {
				in_class := false;
			}
			else {
				class_items++;
			}
			i++;
			next;
		}
		if ( ch eq "[" ) {
			in_class := true;
			class_items := 0;
		}
		else if ( ch eq "]" ) {
			return false;
		}
		else if ( ch eq "(" ) {
			parens++;
		}
		else if ( ch eq ")" ) {
			if ( parens == 0 ) {
				return false;
			}
			parens--;
		}
		i++;
	}

	if ( in_class or parens != 0 ) {
		return false;
	}

	try {
		to_Regexp_with_flags(value, "u");
		return true;
	}
	catch {
		return false;
	}
}

function _fmt_uri_template_ok ( value ) {
	if ( not( value instanceof String ) ) { return false; }
	let depth := 0;
	let expr := "";
	let i := 0;
	while ( i < length value ) {
		let ch := substr( value, i, 1 );
		if ( ch eq "{" ) {
			if ( depth != 0 ) { return false; }
			depth := 1;
			expr := "";
		}
		else if ( ch eq "}" ) {
			if ( depth != 1 or expr eq "" ) { return false; }
			if ( not( expr ~ /^[+#./;?&]?[A-Za-z0-9_][A-Za-z0-9_.%]*(?::[1-9][0-9]{0,3})?$/ ) ) {
				return false;
			}
			depth := 0;
		}
		else if ( depth == 1 ) {
			expr _= ch;
		}
		i++;
	}
	return depth == 0;
}

class FormatRegistry {
	let _validators := {};

	method __build__ () {
		self.register( "date-time", _fmt_date_time_ok );
		self.register( "date", _fmt_date_ok );
		self.register( "time", _fmt_time_value_ok );
		self.register( "duration", _fmt_duration_ok );
		self.register( "email", _fmt_email_ok );
		self.register( "idn-email", _fmt_idn_email_ok );
		self.register( "hostname", _fmt_hostname_ok );
		self.register( "idn-hostname", _fmt_idn_hostname_ok );
		self.register( "ipv4", _fmt_ipv4_ok );
		self.register( "ipv6", _fmt_ipv6_ok );
		self.register( "uri", _fmt_uri_ok );
		self.register( "uri-reference", _fmt_uri_reference_ok );
		self.register( "iri", _fmt_iri_ok );
		self.register( "iri-reference", _fmt_iri_reference_ok );
		self.register( "uuid", _fmt_regex(
			"^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$",
		) );
		self.register( "json-pointer", _fmt_json_pointer_ok );
		self.register(
			"relative-json-pointer",
			fn v -> v instanceof String and valid_relative_json_pointer(v),
		);
		self.register( "regex", _fmt_regex_ok );
		self.register( "uri-template", _fmt_uri_template_ok );
	}

	method register ( String name, validator ) {
		_validators.set( name, validator );
		return self;
	}

	method has ( String name ) {
		return _validators.exists(name);
	}

	method check ( String name, value ) {
		if ( not self.has(name) ) { return false; }
		return _validators.get(name)(value);
	}
}
`;
        virtualFiles["/modules/std/data/json/schema/model.zzm"] = `=encoding utf8

=head1 NAME

std/data/json/schema/model - JSON value projection helpers.

=head1 SYNOPSIS

  from std/data/json/schema/model import
    jschema_is_object,
    jschema_object_get,
    jschema_type_name;

  if ( jschema_is_object(value) ) {
    say( jschema_object_get( value, "title", "(untitled)" ) );
  }

  say( jschema_type_name(value) );

=head1 IMPLEMENTATION SUPPORT

This Pure Zuzu module is supported by all implementations of ZuzuScript.

=head1 DESCRIPTION

This module adapts native Zuzu collection types to the JSON data model used
by the JSON Schema validator. It is mostly an implementation helper, but its
functions are exported so related schema tools can share the same treatment
of objects, arrays, and pointer locations.

C<Dict> and C<PairList> are object-like. C<PairList> preserves duplicate
keys through C<jschema_object_get_all> and C<jschema_object_entries>. C<Array>
is ordered array-like. C<Set> and C<Bag> are unordered array-like; they can
be used for array keywords where order does not matter.

=head1 EXPORTS

=head2 Functions

=over

=item C<< jschema_is_object( value ) >>

Returns true for C<Dict> and C<PairList>.

=item C<< jschema_is_ordered_array( value ) >>

Returns true for C<Array>.

=item C<< jschema_is_unordered_array( value ) >>

Returns true for C<Set> and C<Bag>.

=item C<< jschema_is_arrayish( value ) >>

Returns true for ordered and unordered array-like values.

=item C<< jschema_type_name( value ) >>

Returns the JSON Schema type name for C<value>: C<null>, C<boolean>,
C<number>, C<string>, C<array>, C<object>, or C<unknown>.

=item C<< jschema_type_matches( value, expected ) >>

Returns true when C<value> matches the JSON Schema type named by
C<expected>. C<integer> is accepted for numbers with no fractional part.

=item C<< jschema_object_has( object, key ) >>

Returns true when an object-like value contains C<key>.

=item C<< jschema_object_get( object, key, fallback := null ) >>

Returns the value for C<key>, or C<fallback> when it is missing.

=item C<< jschema_object_get_all( object, key ) >>

Returns all values for C<key>. For C<Dict>, the result has either one value
or none. For C<PairList>, duplicate keys are preserved.

=item C<< jschema_object_keys( object ) >>

Returns object keys, preserving the underlying collection's key behaviour.

=item C<< jschema_object_unique_keys( object ) >>

Returns object keys with duplicates removed.

=item C<< jschema_object_entries( object ) >>

Returns an array of C<[ key, value ]> pairs.

=item C<< jschema_array_items( value ) >>

Returns the array items for an array-like value. Unordered collections are
converted with C<to_Array()>.

=item C<< jschema_array_length( value ) >>

Returns the length of an array-like value, or zero for other values.

=item C<< jschema_pointer_escape( token ) >>

Escapes a JSON Pointer token by replacing C<~> and C</>.

=item C<< jschema_pointer_join( base, step ) >>

Appends C<step> to a JSON Pointer path.

=item C<< jschema_deep_equal( left, right ) >>

Compares two values using ZuzuScript equality. The validator uses this for
C<const>, C<enum>, and uniqueness checks.

=back

=head1 COPYRIGHT AND LICENCE

B<< std/data/json/schema/model >> is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under
the terms of either the Artistic License 1.0 or the GNU General Public
License version 2.

=cut

from std/string import replace;

function jschema_is_object ( value ) {
	return value instanceof Dict or value instanceof PairList;
}

function jschema_is_ordered_array ( value ) {
	return value instanceof Array;
}

function jschema_is_unordered_array ( value ) {
	return value instanceof Set or value instanceof Bag;
}

function jschema_is_arrayish ( value ) {
	return jschema_is_ordered_array(value)
		or jschema_is_unordered_array(value);
}

function jschema_type_name ( value ) {
	if ( value \u2261 null ) { return "null"; }
	if ( value instanceof Boolean ) { return "boolean"; }
	if ( value instanceof Number ) { return "number"; }
	if ( value instanceof String or value instanceof BinaryString ) {
		return "string";
	}
	if ( jschema_is_arrayish(value) ) { return "array"; }
	if ( jschema_is_object(value) ) { return "object"; }
	return "unknown";
}

function jschema_type_matches ( value, String expected ) {
	switch ( expected : eq ) {
		case "null":    return value \u2261 null;
		case "boolean": return value instanceof Boolean;
		case "number":  return value instanceof Number;
		case "integer": return value instanceof Number and floor(value) == value;
		case "string":
			return value instanceof String or value instanceof BinaryString;
		case "array":   return jschema_is_arrayish(value);
		case "object":  return jschema_is_object(value);
	}
	return false;
}

function jschema_object_has ( object, String key ) {
	if ( object instanceof Dict or object instanceof PairList ) {
		for ( let existing in object.keys() ) {
			if ( existing eq key ) { return true; }
		}
	}
	return false;
}

function jschema_object_get ( object, String key, fallback := null ) {
	if ( object instanceof Dict or object instanceof PairList ) {
		return jschema_object_has(object, key) ? object.get(key) : fallback;
	}
	return fallback;
}

function jschema_object_get_all ( object, String key ) {
	if ( object instanceof Dict ) {
		return jschema_object_has(object, key) ? [ object.get(key) ] : [];
	}
	if ( object instanceof PairList ) {
		return object.get_all(key);
	}
	return [];
}

function jschema_object_keys ( object ) {
	if ( object instanceof Dict or object instanceof PairList ) {
		return object.keys();
	}
	return [];
}

function jschema_object_unique_keys ( object ) {
	let out := [];
	for ( let key in jschema_object_keys(object) ) {
		if ( not( key in out ) ) {
			out.push(key);
		}
	}
	return out;
}

function jschema_object_entries ( object ) {
	let out := [];
	if ( object instanceof Dict ) {
		for ( let key in object.keys() ) {
			out.push( [ key, object.get(key) ] );
		}
	}
	else if ( object instanceof PairList ) {
		for ( let pair in object.to_Array() ) {
			out.push( [ pair.key, pair.value ] );
		}
	}
	return out;
}

function jschema_array_items ( value ) {
	if ( value instanceof Array ) { return value; }
	if ( value instanceof Set or value instanceof Bag ) {
		return value.to_Array();
	}
	return [];
}

function jschema_array_length ( value ) {
	if ( jschema_is_arrayish(value) ) { return value.length(); }
	return 0;
}

function jschema_pointer_escape ( String token ) {
	return token
		\u25B7 replace( ^^, "~", "~0", "g" )
		\u25B7 replace( ^^, "/", "~1", "g" );
}

function jschema_pointer_join ( String base, step ) {
	return base _ "/" _ jschema_pointer_escape("" _ step);
}

function jschema_deep_equal ( left, right ) {
	return left == right;
}
`;
        virtualFiles["/modules/std/data/json/schema/output.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/data/json/schema/output - JSON Schema validation output objects.\n\n=head1 SYNOPSIS\n\n  from std/data/json/schema import\n    RequiredPropertyError,\n    TypeMismatchError,\n    validate;\n\n  let result := validate( schema, instance );\n\n  if ( not result.valid() ) {\n    for ( let error in result.errors() ) {\n      say( error.keywordLocation() _ " " _ error.error() );\n      if ( error instanceof TypeMismatchError ) {\n        say( "type problem" );\n      }\n    }\n  }\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module defines the object output model for JSON Schema validation. It\nis modelled on the Basic output shape from JSON Schema Core, but each error\nis a real Zuzu object instead of a plain C<Dict>. The class hierarchy lets\ncallers use C<instanceof> to distinguish broad categories and precise\nkeyword failures.\n\nThe hierarchy starts with C<ValidationError>. Most keyword failures are\ngrouped under C<MissingValueError>, C<UnexpectedValueError>, or\nC<WrongValueError>. Applicator keywords can also produce C<SubschemaError>,\nwhose children are stored as weak links to avoid retaining a whole validation\ntree only through parent summary errors.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<ValidationResult>\n\nStructured result returned by C<validate>.\n\n=over\n\n=item C<valid()>\n\nReturns the boolean validation status.\n\n=item C<errors()>\n\nReturns an array of C<ValidationError> objects.\n\n=item C<to_Dict()>\n\nReturns a Basic-style C<Dict>. Errors are converted with their own\nC<to_Dict()> method.\n\n=back\n\n=item C<ValidationError>\n\nBase class for all validation errors.\n\nMethods:\n\n=over\n\n=item C<keywordLocation()>\n\nJSON Pointer location of the failing keyword inside the schema.\n\n=item C<absoluteKeywordLocation()>\n\nAbsolute keyword URI when known, otherwise C<null>.\n\n=item C<instanceLocation()>\n\nJSON Pointer location of the failing instance value.\n\n=item C<error()>\n\nHuman-readable error message.\n\n=item C<keyword()>\n\nThe keyword that produced the error, when known.\n\n=item C<details()>\n\nKeyword-specific structured detail, when present.\n\n=item C<to_Dict()>\n\nConverts the error to a Basic-style C<Dict>.\n\n=back\n\nSnake-case aliases are provided for the location methods:\nC<keyword_location()>, C<absolute_keyword_location()>, and\nC<instance_location()>.\n\n=item C<MissingValueError>\n\nBase class for failures where a required value is absent. Subclasses are\nC<RequiredPropertyError>, C<DependentRequiredPropertyError>,\nC<MinItemsError>, C<MinPropertiesError>, and C<MinContainsError>.\n\n=item C<UnexpectedValueError>\n\nBase class for failures where a value is present but not allowed.\nSubclasses are C<AdditionalPropertiesError>,\nC<UnevaluatedPropertiesError>, C<AdditionalItemsError>,\nC<UnevaluatedItemsError>, C<MaxItemsError>, C<MaxPropertiesError>,\nC<MaxContainsError>, and C<NotMatchedError>.\n\n=item C<WrongValueError>\n\nBase class for failures where a value is present but does not meet a\nconstraint. Subclasses are C<FalseSchemaError>, C<TypeMismatchError>,\nC<EnumMismatchError>, C<ConstMismatchError>, C<MultipleOfError>,\nC<MinimumError>, C<MaximumError>, C<ExclusiveMinimumError>,\nC<ExclusiveMaximumError>, C<MinLengthError>, C<MaxLengthError>,\nC<PatternError>, C<FormatError>, C<UnknownFormatError>,\nC<UniqueItemsError>, C<PropertyNamesError>, C<ContentEncodingError>,\nC<ContentMediaTypeError>, C<AllOfError>, C<AnyOfError>, C<OneOfError>, and\nC<IfThenElseError>.\n\n=item C<SubschemaError>\n\nSummary error for the message C<A subschema had errors.>. The\nC<suberrors()> method returns live child errors that are still reachable.\nChildren are added with C<add_suberror(error)> and\nC<add_suberrors(errors)>.\n\n=item C<ReferenceResolutionError>\n\nError class for failures while resolving C<$ref> or C<$dynamicRef>.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/data/json/schema/output >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nclass ValidationError {\n	let String keywordLocation;\n	let absoluteKeywordLocation := null;\n	let String instanceLocation;\n	let String error;\n	let keyword := null;\n	let details := null;\n\n	method keywordLocation () { return keywordLocation; }\n	method absoluteKeywordLocation () { return absoluteKeywordLocation; }\n	method instanceLocation () { return instanceLocation; }\n	method error () { return error; }\n	method keyword () { return keyword; }\n	method details () { return details; }\n\n	method keyword_location () { return keywordLocation; }\n	method absolute_keyword_location () { return absoluteKeywordLocation; }\n	method instance_location () { return instanceLocation; }\n\n	method to_Dict () {\n		let out := {\n			keywordLocation: keywordLocation,\n			instanceLocation: instanceLocation,\n			error: error,\n		};\n		if ( absoluteKeywordLocation \u2262 null ) {\n			out{absoluteKeywordLocation} := absoluteKeywordLocation;\n		}\n		return out;\n	}\n}\n\nclass MissingValueError extends ValidationError;\nclass UnexpectedValueError extends ValidationError;\nclass WrongValueError extends ValidationError;\n\nclass SubschemaError extends ValidationError {\n	let _suberrors := [];\n\n	method add_suberror ( child_error ) {\n		_suberrors.push_weak(child_error);\n		return child_error;\n	}\n\n	method add_suberrors ( errors ) {\n		for ( let child_error in errors ) {\n			self.add_suberror(child_error);\n		}\n		return self;\n	}\n\n	method suberrors () {\n		return _suberrors.grep( fn e -> e \u2262 null );\n	}\n}\n\nclass FalseSchemaError extends WrongValueError;\n\nclass RequiredPropertyError extends MissingValueError;\nclass DependentRequiredPropertyError extends MissingValueError;\nclass MinItemsError extends MissingValueError;\nclass MinPropertiesError extends MissingValueError;\nclass MinContainsError extends MissingValueError;\n\nclass AdditionalPropertiesError extends UnexpectedValueError;\nclass UnevaluatedPropertiesError extends UnexpectedValueError;\nclass AdditionalItemsError extends UnexpectedValueError;\nclass UnevaluatedItemsError extends UnexpectedValueError;\nclass MaxItemsError extends UnexpectedValueError;\nclass MaxPropertiesError extends UnexpectedValueError;\nclass MaxContainsError extends UnexpectedValueError;\nclass NotMatchedError extends UnexpectedValueError;\n\nclass TypeMismatchError extends WrongValueError;\nclass EnumMismatchError extends WrongValueError;\nclass ConstMismatchError extends WrongValueError;\nclass MultipleOfError extends WrongValueError;\nclass MinimumError extends WrongValueError;\nclass MaximumError extends WrongValueError;\nclass ExclusiveMinimumError extends WrongValueError;\nclass ExclusiveMaximumError extends WrongValueError;\nclass MinLengthError extends WrongValueError;\nclass MaxLengthError extends WrongValueError;\nclass PatternError extends WrongValueError;\nclass FormatError extends WrongValueError;\nclass UnknownFormatError extends FormatError;\nclass UniqueItemsError extends WrongValueError;\nclass PropertyNamesError extends WrongValueError;\nclass ContentEncodingError extends WrongValueError;\nclass ContentMediaTypeError extends WrongValueError;\nclass AllOfError extends WrongValueError;\nclass AnyOfError extends WrongValueError;\nclass OneOfError extends WrongValueError;\nclass IfThenElseError extends WrongValueError;\n\nclass ReferenceResolutionError extends ValidationError;\n\nclass ValidationResult {\n	let Boolean valid := true;\n	let Array errors := [];\n\n	method valid () { return valid; }\n	method errors () { return errors; }\n\n	method to_Dict () {\n		let out := { valid: valid };\n		if ( not valid ) {\n			out{errors} := errors.map( fn e -> e.to_Dict() );\n		}\n		return out;\n	}\n}\n';
        virtualFiles["/modules/std/data/json/schema/relative_pointer.zzm"] = `=encoding utf8

=head1 NAME

std/data/json/schema/relative_pointer - Relative JSON Pointer parser.

=head1 SYNOPSIS

  from std/data/json/schema/relative_pointer import RelativeJSONPointer;

  let doc := {
    people: [
      { name: "Ada" },
      { name: "Grace" },
    ],
  };

  let pointer := new RelativeJSONPointer( path: "1/name" );
  say( pointer.first( doc, "/people/0/age", "(missing)" ) );

=head1 IMPLEMENTATION SUPPORT

This Pure Zuzu module is supported by all implementations of ZuzuScript.

=head1 DESCRIPTION

Relative JSON Pointer describes a target by starting from a context location,
climbing zero or more levels, optionally shifting an array index, and then
optionally applying a normal JSON Pointer suffix. JSON Schema uses the
syntax for the C<relative-json-pointer> format.

This module evaluates relative pointers against a root document and a
context pointer. The context pointer must itself be a JSON Pointer string.

=head1 EXPORTS

=head2 Classes

=over

=item C<RelativeJSONPointer>

Construct with C<< new RelativeJSONPointer( path: "0/foo" ) >>. Invalid
syntax throws during construction.

Methods:

=over

=item C<expression()>

Returns the original pointer expression.

=item C<up()>

Returns the number of levels the pointer climbs from the context location.

=item C<index_change()>

Returns the array-index offset, or C<null> when none was supplied.

=item C<pointer()>

Returns the JSON Pointer suffix, or C<null> for a C<#> key request.

=item C<key_request()>

Returns true for C<#> pointers that request the key or array index at the
target location.

=item C<< target_pointer( context_pointer := "" ) >>

Returns the absolute JSON Pointer reached by climbing and applying any index
offset, before the suffix is applied.

=item C<< evaluate( root, context_pointer := "" ) >>

Evaluates the relative pointer. Normal pointers return the same array of
matches as I<std/path/jsonpointer>'s C<query>. C<#> key requests return the
key or index string directly, or C<null> when the request names the document
root.

=item C<< get( root, context_pointer := "" ) >>

Alias for C<evaluate>.

=item C<< first( root, context_pointer := "", fallback := null ) >>

Returns the first matched value, or C<fallback> when no value is found. For
C<#> key requests, C<fallback> is returned only when the key request returns
C<null>.

=item C<< exists( root, context_pointer := "" ) >>

Returns true when evaluation finds a value. For C<#> key requests, the
document root key is treated as absent.

=back

=back

=head2 Functions

=over

=item C<< valid_relative_json_pointer( text ) >>

Returns true when C<text> parses as a Relative JSON Pointer.

=back

=head1 COPYRIGHT AND LICENCE

B<< std/data/json/schema/relative_pointer >> is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under
the terms of either the Artistic License 1.0 or the GNU General Public
License version 2.

=cut

from std/path/jsonpointer import JSONPointer;
from std/data/json/schema/model import jschema_pointer_join;
from std/string import replace, split, substr;

function _rjp_decode_token ( String raw ) {
	return raw
		\u25B7 replace( ^^, "~1", "/", "g" )
		\u25B7 replace( ^^, "~0", "~", "g" );
}

function _rjp_tokens ( String pointer ) {
	if ( pointer ne "" and substr( pointer, 0, 1 ) ne "/" ) {
		die "Relative JSON Pointer context path must be a JSON Pointer";
	}
	if ( pointer eq "" ) {
		return [];
	}

	let raw := split( substr( pointer, 1 ), "/" );
	let out := [];
	for ( let token in raw ) {
		out.push( _rjp_decode_token(token) );
	}
	return out;
}

function _rjp_pointer_from_tokens ( Array tokens ) {
	let out := "";
	for ( let token in tokens ) {
		out := jschema_pointer_join( out, token );
	}
	return out;
}

class RelativeJSONPointer {
	let String path;
	let Number up := 0;
	let index_change := null;
	let pointer := null;
	let Boolean key_request := false;

	method __build__ () {
		let i := 0;
		let n := length path;
		if ( n == 0 ) {
			die "Relative JSON Pointer parse error: empty pointer";
		}
		if ( not( substr( path, 0, 1 ) ~ /[0-9]/ ) ) {
			die "Relative JSON Pointer parse error: missing non-negative integer";
		}
		if ( n > 1 and substr( path, 0, 1 ) eq "0" and substr( path, 1, 1 ) ~ /[0-9]/ ) {
			die "Relative JSON Pointer parse error: leading zero";
		}
		while ( i < n and substr( path, i, 1 ) ~ /[0-9]/ ) {
			i++;
		}
		up := int( substr( path, 0, i ) );

		if ( i < n and substr( path, i, 1 ) ~ /[+-]/ ) {
			let sign := substr( path, i, 1 );
			i++;
			let start := i;
			if ( i >= n or not( substr( path, i, 1 ) ~ /[0-9]/ ) ) {
				die "Relative JSON Pointer parse error: missing index offset";
			}
			while ( i < n and substr( path, i, 1 ) ~ /[0-9]/ ) {
				i++;
			}
			let offset := int( substr( path, start, i - start ) );
			index_change := sign eq "-" ? 0 - offset : offset;
		}

		if ( i == n ) {
			pointer := "";
			return;
		}

		if ( substr( path, i, 1 ) eq "#" ) {
			if ( i + 1 \u2262 n ) {
				die "Relative JSON Pointer parse error: trailing text after '#'";
			}
			key_request := true;
			return;
		}

		let rest := substr( path, i );
		new JSONPointer( path: rest );
		pointer := rest;
	}

	method expression () { return path; }
	method pointer () { return pointer; }
	method up () { return up; }
	method index_change () { return index_change; }
	method key_request () { return key_request; }

	method target_pointer ( String context_pointer := "" ) {
		let tokens := _rjp_tokens(context_pointer);
		if ( up > tokens.length() ) {
			die "Relative JSON Pointer climbs above the document root";
		}

		let target_len := tokens.length() - up;
		let target := [];
		let i := 0;
		while ( i < target_len ) {
			target.push(tokens[i]);
			i++;
		}

		if ( index_change \u2262 null ) {
			if (
				target.length() == 0
				or not( target[target.length() - 1] ~ /^(0|[1-9][0-9]*)$/ )
			) {
				die "Relative JSON Pointer index manipulation needs an array index";
			}
			let idx := int( target[target.length() - 1] ) + index_change;
			if ( idx < 0 ) {
				die "Relative JSON Pointer index manipulation produced negative index";
			}
			target[target.length() - 1] := "" _ idx;
		}

		return _rjp_pointer_from_tokens(target);
	}

	method evaluate ( root, String context_pointer := "" ) {
		if ( key_request ) {
			let tokens := _rjp_tokens(context_pointer);
			if ( up > tokens.length() ) {
				die "Relative JSON Pointer climbs above the document root";
			}
			if ( tokens.length() == up ) {
				return null;
			}
			return tokens[ tokens.length() - up - 1 ];
		}

		let base := self.target_pointer(context_pointer);
		let full := base;
		if ( pointer \u2262 null and pointer ne "" ) {
			let suffix := pointer;
			full := base eq "" ? suffix : base _ suffix;
		}
		return new JSONPointer( path: full ).query(root);
	}

	method get ( root, String context_pointer := "" ) {
		return self.evaluate( root, context_pointer );
	}

	method first ( root, String context_pointer := "", fallback := null ) {
		if ( key_request ) {
			let key := self.evaluate( root, context_pointer );
			return key \u2261 null ? fallback : key;
		}
		let out := self.evaluate( root, context_pointer );
		return out.length() == 0 ? fallback : out[0];
	}

	method exists ( root, String context_pointer := "" ) {
		if ( key_request ) {
			return self.evaluate( root, context_pointer ) \u2262 null;
		}
		return self.evaluate( root, context_pointer ).length() > 0;
	}
}

function valid_relative_json_pointer ( String text ) {
	try {
		new RelativeJSONPointer( path: text );
		return true;
	}
	catch {
		return false;
	}
}
`;
        virtualFiles["/modules/std/data/json/schema/validation.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/data/json/schema/validation - JSON Schema 2020-12 evaluator.\n\n=head1 SYNOPSIS\n\n  from std/data/json/schema/validation import JSONSchema, validate, valid;\n\n  let schema := new JSONSchema(\n    schema: {\n      type: "array",\n      items: { type: "integer" },\n    },\n  );\n\n  say( schema.is_valid([ 1, 2, 3 ]) );\n\n  let result := validate( { minimum: 10 }, 4 );\n  say( result.errors()[0].error() );\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis Pure Zuzu module is supported by all implementations of ZuzuScript.\nNetwork loading requires C<std/net/http> through\nI<std/data/json/schema/core>.\n\n=head1 DESCRIPTION\n\nThis module contains the JSON Schema 2020-12 evaluator. It is normally used\nthrough the facade module I<std/data/json/schema>, which re-exports the\npublic API and the error classes.\n\nThe evaluator supports boolean schemas, object schemas, references,\napplicators, object and array validation, numeric and string constraints,\ndependent keywords, content keywords, and format validation. It validates\ndecoded Zuzu values and uses I<std/data/json/schema/model> to project native\nC<PairList>, C<Set>, and C<Bag> values into the JSON data model where that\nis meaningful.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<JSONSchema>\n\nCompiled schema wrapper. Construct with C<< new JSONSchema( schema: ... ) >>.\nPass C<options> as a named field when configuration is needed.\n\n=over\n\n=item C<< is_valid( instance ) >>\n\nReturns C<true> or C<false>. This mode stops after the first failure.\n\n=item C<< validate( instance ) >>\n\nReturns a C<ValidationResult> and collects independent failures as\nC<ValidationError> objects.\n\n=back\n\n=back\n\n=head2 Functions\n\n=over\n\n=item C<< valid( schema, instance, options := {} ) >>\n\nConstructs a temporary C<JSONSchema> and returns\nC<< is_valid(instance) >>.\n\n=item C<< validate( schema, instance, options := {} ) >>\n\nConstructs a temporary C<JSONSchema> and returns\nC<< validate(instance) >>.\n\n=back\n\n=head1 OPTIONS\n\nC<options> may be a C<Dict> or C<PairList>.\n\n=over\n\n=item C<base_uri>\n\nBase URI for the root schema.\n\n=item C<registry>\n\nC<SchemaRegistry> used for references. If omitted, a new registry is\ncreated and the root schema is registered in it.\n\n=item C<loader>\n\nCallable or object with C<load(uri)> used to load missing referenced\nresources. A string result is decoded as JSON.\n\n=item C<allow_network>\n\nWhen true and C<loader> is not supplied, uses C<HTTPResourceLoader>.\n\n=item C<formats> or C<format_registry>\n\nC<FormatRegistry> used for C<format> checks.\n\n=item C<format_assert>\n\nBoolean. Defaults to false. When false, C<format> never makes validation\nfail.\n\n=item C<unknown_format>\n\nDefaults to C<ignore>. Use C<fail> to report unknown asserted formats.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/data/json/schema/validation >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/internals import to_Regexp_with_flags;\nfrom std/string import join, substr;\nfrom std/data/json/schema/core import\n	HTTPResourceLoader,\n	SchemaRegistry,\n	jschema_uri_resolve,\n	jschema_url_split;\nfrom std/data/json/schema/format import FormatRegistry;\nfrom std/data/json/schema/model import\n	jschema_array_items,\n	jschema_array_length,\n	jschema_deep_equal,\n	jschema_is_arrayish,\n	jschema_is_object,\n	jschema_is_ordered_array,\n	jschema_is_unordered_array,\n	jschema_object_entries,\n	jschema_object_get,\n	jschema_object_get_all,\n	jschema_object_has,\n	jschema_object_keys,\n	jschema_object_unique_keys,\n	jschema_pointer_join,\n	jschema_type_matches,\n	jschema_type_name;\nfrom std/data/json/schema/output import\n	AdditionalItemsError,\n	AdditionalPropertiesError,\n	AllOfError,\n	AnyOfError,\n	ConstMismatchError,\n	ContentEncodingError,\n	ContentMediaTypeError,\n	DependentRequiredPropertyError,\n	EnumMismatchError,\n	ExclusiveMaximumError,\n	ExclusiveMinimumError,\n	FalseSchemaError,\n	FormatError,\n	IfThenElseError,\n	MaxContainsError,\n	MaximumError,\n	MaxItemsError,\n	MaxLengthError,\n	MaxPropertiesError,\n	MinContainsError,\n	MinimumError,\n	MinItemsError,\n	MinLengthError,\n	MinPropertiesError,\n	MultipleOfError,\n	NotMatchedError,\n	OneOfError,\n	PatternError,\n	PropertyNamesError,\n	ReferenceResolutionError,\n	RequiredPropertyError,\n	SubschemaError,\n	TypeMismatchError,\n	UnevaluatedItemsError,\n	UnevaluatedPropertiesError,\n	UnexpectedValueError,\n	UniqueItemsError,\n	UnknownFormatError,\n	ValidationResult;\n\nfunction _jschema_opt ( options, String key, fallback := null ) {\n	if ( options \u2261 null ) {\n		return fallback;\n	}\n	if ( options instanceof Dict ) {\n		return options.exists(key) ? options.get(key) : fallback;\n	}\n	if ( options instanceof PairList ) {\n		return options.has(key) ? options.get(key) : fallback;\n	}\n	return fallback;\n}\n\nfunction _jschema_add_unique ( Array out, value ) {\n	if ( not( value in out ) ) {\n		out.push(value);\n	}\n	return out;\n}\n\nfunction _jschema_validation_vocab_enabled ( schema, registry, String base_uri ) {\n	if (\n		not jschema_is_object(schema)\n		or not jschema_object_has( schema, "$schema" )\n		or not( jschema_object_get( schema, "$schema" ) instanceof String )\n	) {\n		return true;\n	}\n\n	let metaschema;\n	try {\n		metaschema := registry.resolve(\n			jschema_object_get( schema, "$schema" ),\n			base_uri,\n		);\n	}\n	catch {\n		return true;\n	}\n\n	if (\n		jschema_is_object(metaschema)\n		and jschema_object_has( metaschema, "$vocabulary" )\n		and jschema_is_object( jschema_object_get( metaschema, "$vocabulary" ) )\n	) {\n		let vocabulary := jschema_object_get( metaschema, "$vocabulary" );\n		let validation_uri := "https://json-schema.org/draft/2020-12/vocab/validation";\n		if (\n			jschema_object_has( vocabulary, validation_uri )\n			and jschema_object_get( vocabulary, validation_uri ) instanceof Boolean\n		) {\n			return jschema_object_get( vocabulary, validation_uri );\n		}\n		return false;\n	}\n\n	return true;\n}\n\nfunction _jschema_format_assertion_vocab_enabled ( schema, registry, String base_uri, Boolean fallback ) {\n	if (\n		not jschema_is_object(schema)\n		or not jschema_object_has( schema, "$schema" )\n		or not( jschema_object_get( schema, "$schema" ) instanceof String )\n	) {\n		return fallback;\n	}\n\n	let metaschema;\n	try {\n		metaschema := registry.resolve(\n			jschema_object_get( schema, "$schema" ),\n			base_uri,\n		);\n	}\n	catch {\n		return fallback;\n	}\n\n	if (\n		jschema_is_object(metaschema)\n		and jschema_object_has( metaschema, "$vocabulary" )\n		and jschema_is_object( jschema_object_get( metaschema, "$vocabulary" ) )\n	) {\n		let vocabulary := jschema_object_get( metaschema, "$vocabulary" );\n		let format_assertion_uri := "https://json-schema.org/draft/2020-12/vocab/format-assertion";\n		if ( jschema_object_has( vocabulary, format_assertion_uri ) ) {\n			return true;\n		}\n	}\n\n	return fallback;\n}\n\nclass _EvalResult {\n	let Boolean valid := true;\n	let Array errors := [];\n	let Array evaluatedProperties := [];\n	let Array evaluatedItems := [];\n\n	method add_error ( error ) {\n		valid := false;\n		if ( error \u2262 null ) {\n			errors.push(error);\n		}\n		return error;\n	}\n\n	method merge ( other ) {\n		if ( not other.valid() ) {\n			valid := false;\n		}\n		for ( let error in other.errors() ) {\n			errors.push(error);\n		}\n		for ( let prop in other.evaluatedProperties() ) {\n			_jschema_add_unique( evaluatedProperties, prop );\n		}\n		for ( let item in other.evaluatedItems() ) {\n			_jschema_add_unique( evaluatedItems, item );\n		}\n		return self;\n	}\n\n	method mark_property ( prop ) {\n		_jschema_add_unique( evaluatedProperties, prop );\n	}\n\n	method mark_item ( item ) {\n		_jschema_add_unique( evaluatedItems, item );\n	}\n\n	method valid () { return valid; }\n	method errors () { return errors; }\n	method evaluatedProperties () { return evaluatedProperties; }\n	method evaluatedItems () { return evaluatedItems; }\n}\n\nfunction _jschema_regexp ( String pattern ) {\n	return to_Regexp_with_flags(pattern, "u");\n}\n\nclass _SchemaEvaluator {\n	let registry;\n	let formats;\n	let Boolean collect := true;\n	let Boolean format_assert := false;\n	let String unknown_format := "ignore";\n	let Boolean validation_enabled := true;\n	let Array dynamic_scope := [];\n\n	method error (\n		Klass,\n		String keyword_location,\n		String instance_location,\n		String message,\n		keyword := null,\n		details := null,\n	) {\n		if ( not collect ) {\n			return null;\n		}\n		return new Klass(\n			keywordLocation: keyword_location,\n			instanceLocation: instance_location,\n			error: message,\n			keyword: keyword,\n			details: details,\n		);\n	}\n\n	method _subschema_error (\n		String keyword_location,\n		String instance_location,\n		Array child_errors,\n		keyword := null,\n	) {\n		if ( not collect ) {\n			return null;\n		}\n		return new SubschemaError(\n			keywordLocation: keyword_location,\n			instanceLocation: instance_location,\n			error: "A subschema had errors.",\n			keyword: keyword,\n		).add_suberrors(child_errors);\n	}\n\n	method _invalid (\n		_EvalResult result,\n		Klass,\n		String keyword_location,\n		String instance_location,\n		String message,\n		keyword := null,\n		details := null,\n	) {\n		result.add_error(\n			self.error(\n				Klass,\n				keyword_location,\n				instance_location,\n				message,\n				keyword,\n				details,\n			),\n		);\n		return result;\n	}\n\n	method _child (\n		schema,\n		instance,\n		String keyword_location,\n		String instance_location,\n		String base_uri,\n	) {\n		return self.evaluate(\n			schema,\n			instance,\n			keyword_location,\n			instance_location,\n			base_uri,\n		);\n	}\n\n	method _finish ( _EvalResult result, Boolean pushed_scope ) {\n		if ( pushed_scope ) {\n			dynamic_scope.pop();\n		}\n		return result;\n	}\n\n	method _dynamic_target ( ref_info ) {\n		let fragment := ref_info{fragment};\n		if (\n			fragment \u2261 null\n			or fragment eq ""\n			or substr( fragment, 0, 1 ) eq "/"\n			or not registry.has_dynamic_anchor( ref_info{resource_uri}, fragment )\n		) {\n			return ref_info{target};\n		}\n\n		for ( let resource_uri in dynamic_scope ) {\n			let target := registry.dynamic_anchor( resource_uri, fragment );\n			if ( target \u2262 null ) {\n				return target;\n			}\n		}\n\n		return ref_info{target};\n	}\n\n	method evaluate (\n		schema,\n		instance,\n		String keyword_location := "",\n		String instance_location := "",\n		String base_uri := "",\n	) {\n		let result := new _EvalResult();\n		let current_base_uri := base_uri;\n\n		if ( schema instanceof Boolean ) {\n			if ( schema ) {\n				return result;\n			}\n			return self._invalid(\n				result,\n				FalseSchemaError,\n				keyword_location,\n				instance_location,\n				"Boolean false schema does not allow any value.",\n				"false",\n			);\n		}\n\n		if ( not jschema_is_object(schema) ) {\n			return result;\n		}\n\n		let registered_base := registry.schema_base(schema, null);\n		if ( registered_base \u2262 null ) {\n			current_base_uri := registered_base;\n		}\n		else if (\n			jschema_object_has( schema, "$id" )\n			and jschema_object_get( schema, "$id" ) instanceof String\n		) {\n			current_base_uri := jschema_uri_resolve(\n				current_base_uri,\n				jschema_object_get( schema, "$id" ),\n			);\n		}\n\n		let scope_resource := jschema_url_split(current_base_uri){baseurl};\n		dynamic_scope.push(scope_resource);\n		let pushed_scope := true;\n\n		if ( jschema_object_has( schema, "$ref" ) ) {\n			let ref := jschema_object_get( schema, "$ref" );\n			if ( ref instanceof String ) {\n				try {\n					let ref_info := registry.resolve_info( ref, current_base_uri );\n					let child := self._child(\n						ref_info{target},\n						instance,\n						jschema_pointer_join( keyword_location, "$ref" ),\n						instance_location,\n						ref_info{resource_uri},\n					);\n					result.merge(child);\n					if ( not child.valid() ) {\n						result.add_error( self._subschema_error(\n							jschema_pointer_join( keyword_location, "$ref" ),\n							instance_location,\n							child.errors(),\n							"$ref",\n						) );\n						if ( not collect ) { return self._finish( result, pushed_scope ); }\n					}\n				}\n				catch ( Exception e ) {\n					self._invalid(\n						result,\n						ReferenceResolutionError,\n						jschema_pointer_join( keyword_location, "$ref" ),\n						instance_location,\n						e{message},\n						"$ref",\n					);\n					if ( not collect ) { return self._finish( result, pushed_scope ); }\n				}\n			}\n		}\n\n		if ( jschema_object_has( schema, "$dynamicRef" ) ) {\n			let ref := jschema_object_get( schema, "$dynamicRef" );\n			if ( ref instanceof String ) {\n				try {\n					let ref_info := registry.resolve_info( ref, current_base_uri );\n					let child := self._child(\n						self._dynamic_target(ref_info),\n						instance,\n						jschema_pointer_join( keyword_location, "$dynamicRef" ),\n						instance_location,\n						ref_info{resource_uri},\n					);\n					result.merge(child);\n					if ( not child.valid() ) {\n						result.add_error( self._subschema_error(\n							jschema_pointer_join( keyword_location, "$dynamicRef" ),\n							instance_location,\n							child.errors(),\n							"$dynamicRef",\n						) );\n						if ( not collect ) { return self._finish( result, pushed_scope ); }\n					}\n				}\n				catch ( Exception e ) {\n					self._invalid(\n						result,\n						ReferenceResolutionError,\n						jschema_pointer_join( keyword_location, "$dynamicRef" ),\n						instance_location,\n						e{message},\n						"$dynamicRef",\n					);\n					if ( not collect ) { return self._finish( result, pushed_scope ); }\n				}\n			}\n		}\n\n		self._validate_type( result, schema, instance, keyword_location, instance_location );\n		if ( not result.valid() and not collect ) { return self._finish( result, pushed_scope ); }\n		self._validate_enum_const( result, schema, instance, keyword_location, instance_location );\n		if ( not result.valid() and not collect ) { return self._finish( result, pushed_scope ); }\n		self._validate_numeric( result, schema, instance, keyword_location, instance_location );\n		if ( not result.valid() and not collect ) { return self._finish( result, pushed_scope ); }\n		self._validate_string( result, schema, instance, keyword_location, instance_location );\n		if ( not result.valid() and not collect ) { return self._finish( result, pushed_scope ); }\n		self._validate_array( result, schema, instance, keyword_location, instance_location, current_base_uri );\n		if ( not result.valid() and not collect ) { return self._finish( result, pushed_scope ); }\n		self._validate_object( result, schema, instance, keyword_location, instance_location, current_base_uri );\n		if ( not result.valid() and not collect ) { return self._finish( result, pushed_scope ); }\n		self._validate_applicators( result, schema, instance, keyword_location, instance_location, current_base_uri );\n		if ( not result.valid() and not collect ) { return self._finish( result, pushed_scope ); }\n		self._validate_unevaluated( result, schema, instance, keyword_location, instance_location, current_base_uri );\n		return self._finish( result, pushed_scope );\n	}\n\n	method _validate_type ( result, schema, instance, kwloc, instloc ) {\n		if ( not validation_enabled ) {\n			return;\n		}\n		if ( not jschema_object_has( schema, "type" ) ) {\n			return;\n		}\n		let spec := jschema_object_get( schema, "type" );\n		let ok := false;\n		let expected := [];\n		if ( spec instanceof String ) {\n			expected := [ spec ];\n		}\n		else if ( spec instanceof Array ) {\n			expected := spec;\n		}\n		for ( let t in expected ) {\n			if ( t instanceof String and jschema_type_matches( instance, t ) ) {\n				ok := true;\n			}\n		}\n		if ( ok ) {\n			return;\n		}\n		self._invalid(\n			result,\n			TypeMismatchError,\n			jschema_pointer_join( kwloc, "type" ),\n			instloc,\n			`Expected ${join( "|", expected )}, got ${jschema_type_name(instance)}.`,\n			"type",\n		);\n	}\n\n	method _validate_enum_const ( result, schema, instance, kwloc, instloc ) {\n		if ( not validation_enabled ) {\n			return;\n		}\n		if ( jschema_object_has( schema, "const" ) ) {\n			if ( jschema_deep_equal(\n				instance,\n				jschema_object_get( schema, "const" ),\n			) ) {\n				return;\n			}\n			self._invalid(\n				result,\n				ConstMismatchError,\n				jschema_pointer_join( kwloc, "const" ),\n				instloc,\n				"Value does not match const.",\n				"const",\n			);\n			if ( not collect ) {\n				return;\n			}\n		}\n\n		if ( jschema_object_has( schema, "enum" ) ) {\n			let allowed := jschema_object_get( schema, "enum" );\n				if ( allowed instanceof Array ) {\n					for ( let option in allowed ) {\n						if ( jschema_deep_equal( instance, option ) ) {\n							return;\n						}\n					}\n				}\n			self._invalid(\n				result,\n				EnumMismatchError,\n				jschema_pointer_join( kwloc, "enum" ),\n				instloc,\n				"Value is not one of the allowed enum values.",\n				"enum",\n			);\n		}\n	}\n\n	method _validate_numeric ( result, schema, instance, kwloc, instloc ) {\n		if ( not validation_enabled ) {\n			return;\n		}\n		if ( not( instance instanceof Number ) ) {\n			return;\n		}\n		if ( jschema_object_has( schema, "multipleOf" ) ) {\n			let n := jschema_object_get( schema, "multipleOf" );\n			let quotient := n instanceof Number and n != 0\n				? instance / n\n				: 0;\n			if (\n				n instanceof Number\n				and n != 0\n				and (\n					quotient > 10 ** 300\n					or quotient < -( 10 ** 300 )\n					or quotient != floor(quotient)\n				)\n			) {\n				self._invalid(\n					result,\n					MultipleOfError,\n					jschema_pointer_join( kwloc, "multipleOf" ),\n					instloc,\n					`Number is not a multiple of ${n}.`,\n					"multipleOf",\n				);\n				if ( not collect ) {\n					return;\n				}\n			}\n		}\n		if (\n			jschema_object_has( schema, "minimum" )\n			and instance < jschema_object_get( schema, "minimum" )\n		) {\n			self._invalid( result, MinimumError, jschema_pointer_join( kwloc, "minimum" ), instloc, "Number is below minimum.", "minimum" );\n			if ( not collect ) {\n				return;\n			}\n		}\n		if (\n			jschema_object_has( schema, "maximum" )\n			and instance > jschema_object_get( schema, "maximum" )\n		) {\n			self._invalid( result, MaximumError, jschema_pointer_join( kwloc, "maximum" ), instloc, "Number is above maximum.", "maximum" );\n			if ( not collect ) {\n				return;\n			}\n		}\n		if (\n			jschema_object_has( schema, "exclusiveMinimum" )\n			and instance <= jschema_object_get( schema, "exclusiveMinimum" )\n		) {\n			self._invalid( result, ExclusiveMinimumError, jschema_pointer_join( kwloc, "exclusiveMinimum" ), instloc, "Number is not above exclusiveMinimum.", "exclusiveMinimum" );\n			if ( not collect ) {\n				return;\n			}\n		}\n		if (\n			jschema_object_has( schema, "exclusiveMaximum" )\n			and instance >= jschema_object_get( schema, "exclusiveMaximum" )\n		) {\n			self._invalid( result, ExclusiveMaximumError, jschema_pointer_join( kwloc, "exclusiveMaximum" ), instloc, "Number is not below exclusiveMaximum.", "exclusiveMaximum" );\n		}\n	}\n\n	method _validate_string ( result, schema, instance, kwloc, instloc ) {\n		if ( not( instance instanceof String or instance instanceof BinaryString ) ) {\n			return;\n		}\n		let text := "" _ instance;\n		if ( validation_enabled ) {\n			if (\n				jschema_object_has( schema, "minLength" )\n				and length text < jschema_object_get( schema, "minLength" )\n			) {\n				self._invalid( result, MinLengthError, jschema_pointer_join( kwloc, "minLength" ), instloc, "String is shorter than minLength.", "minLength" );\n				if ( not collect ) {\n					return;\n				}\n			}\n			if (\n				jschema_object_has( schema, "maxLength" )\n				and length text > jschema_object_get( schema, "maxLength" )\n			) {\n				self._invalid( result, MaxLengthError, jschema_pointer_join( kwloc, "maxLength" ), instloc, "String is longer than maxLength.", "maxLength" );\n				if ( not collect ) {\n					return;\n				}\n			}\n			if ( jschema_object_has( schema, "pattern" ) ) {\n				let pattern := jschema_object_get( schema, "pattern" );\n				if ( pattern instanceof String and not( text ~ _jschema_regexp(pattern) ) ) {\n					self._invalid( result, PatternError, jschema_pointer_join( kwloc, "pattern" ), instloc, "String does not match pattern.", "pattern" );\n					if ( not collect ) {\n						return;\n					}\n				}\n			}\n		}\n		if ( format_assert and jschema_object_has( schema, "format" ) ) {\n			let fmt := jschema_object_get( schema, "format" );\n			if ( fmt instanceof String ) {\n				if ( not formats.has(fmt) ) {\n					if ( unknown_format eq "ignore" ) {\n						return;\n					}\n					self._invalid(\n						result,\n						UnknownFormatError,\n						jschema_pointer_join( kwloc, "format" ),\n						instloc,\n						`Unknown format \'${fmt}\'.`,\n						"format",\n					);\n					if ( not collect ) {\n						return;\n					}\n				}\n				else if ( not formats.check( fmt, text ) ) {\n					self._invalid(\n						result,\n						FormatError,\n						jschema_pointer_join( kwloc, "format" ),\n						instloc,\n						`String does not match format \'${fmt}\'.`,\n						"format",\n					);\n				}\n			}\n		}\n		if ( validation_enabled ) {\n			if ( jschema_object_has( schema, "contentEncoding" ) ) {\n				/* Validation of decoded content is intentionally conservative. */\n			}\n			if ( jschema_object_has( schema, "contentMediaType" ) ) {\n				/* The media type keyword is annotation unless content is decoded. */\n			}\n		}\n	}\n\n	method _validate_array ( result, schema, instance, kwloc, instloc, base_uri ) {\n		if ( not jschema_is_arrayish(instance) ) {\n			return;\n		}\n		let items := jschema_array_items(instance);\n		let len := jschema_array_length(instance);\n		if ( validation_enabled ) {\n			if (\n				jschema_object_has( schema, "minItems" )\n				and len < jschema_object_get( schema, "minItems" )\n			) {\n				self._invalid( result, MinItemsError, jschema_pointer_join( kwloc, "minItems" ), instloc, "Array has too few items.", "minItems" );\n				if ( not collect ) {\n					return;\n				}\n			}\n			if (\n				jschema_object_has( schema, "maxItems" )\n				and len > jschema_object_get( schema, "maxItems" )\n			) {\n				self._invalid( result, MaxItemsError, jschema_pointer_join( kwloc, "maxItems" ), instloc, "Array has too many items.", "maxItems" );\n				if ( not collect ) {\n					return;\n				}\n			}\n			if ( jschema_object_get( schema, "uniqueItems", false ) ) {\n				let i := 0;\n				while ( i < items.length() ) {\n					let j := i + 1;\n					while ( j < items.length() ) {\n						if ( jschema_deep_equal( items[i], items[j] ) ) {\n							self._invalid( result, UniqueItemsError, jschema_pointer_join( kwloc, "uniqueItems" ), instloc, "Array items are not unique.", "uniqueItems" );\n							if ( not collect ) {\n								return;\n							}\n						}\n						j++;\n					}\n					i++;\n				}\n			}\n		}\n\n		if ( jschema_is_unordered_array(instance) and jschema_object_has( schema, "prefixItems" ) ) {\n			self._invalid(\n				result,\n				AdditionalItemsError,\n				jschema_pointer_join( kwloc, "prefixItems" ),\n				instloc,\n				"prefixItems cannot be applied to an unordered collection.",\n				"prefixItems",\n			);\n			if ( not collect ) {\n				return;\n			}\n		}\n\n		let evaluated := [];\n		if ( jschema_object_has( schema, "prefixItems" ) and jschema_is_ordered_array(instance) ) {\n			let prefix := jschema_object_get( schema, "prefixItems" );\n			if ( prefix instanceof Array ) {\n				let i := 0;\n				while ( i < prefix.length() and i < items.length() ) {\n					let child := self._child(\n						prefix[i],\n						items[i],\n						jschema_pointer_join( jschema_pointer_join( kwloc, "prefixItems" ), i ),\n						jschema_pointer_join( instloc, i ),\n						base_uri,\n					);\n					evaluated.push(i);\n					result.mark_item( jschema_pointer_join( instloc, i ) );\n					result.merge(child);\n					if ( not child.valid() ) {\n						result.add_error( self._subschema_error(\n							jschema_pointer_join( jschema_pointer_join( kwloc, "prefixItems" ), i ),\n							jschema_pointer_join( instloc, i ),\n							child.errors(),\n							"prefixItems",\n						) );\n						if ( not collect ) {\n							return result;\n						}\n					}\n					i++;\n				}\n			}\n		}\n\n		if ( jschema_object_has( schema, "items" ) ) {\n			let subschema := jschema_object_get( schema, "items" );\n			let start := 0;\n			if (\n				jschema_object_has( schema, "prefixItems" )\n				and jschema_object_get( schema, "prefixItems" ) instanceof Array\n			) {\n				start := jschema_object_get( schema, "prefixItems" ).length();\n			}\n			let i := 0;\n			while ( i < items.length() ) {\n				if ( not jschema_is_ordered_array(instance) or i >= start ) {\n					let child := self._child(\n						subschema,\n						items[i],\n						jschema_pointer_join( kwloc, "items" ),\n						jschema_pointer_join( instloc, i ),\n						base_uri,\n					);\n					result.mark_item( jschema_pointer_join( instloc, i ) );\n					result.merge(child);\n					if ( not child.valid() ) {\n						result.add_error( self._subschema_error(\n							jschema_pointer_join( kwloc, "items" ),\n							jschema_pointer_join( instloc, i ),\n							child.errors(),\n							"items",\n						) );\n						if ( not collect ) {\n							return result;\n						}\n					}\n				}\n				i++;\n			}\n		}\n\n		if ( jschema_object_has( schema, "contains" ) ) {\n			let matches := 0;\n			let i := 0;\n			while ( i < items.length() ) {\n				let child := self._child(\n					jschema_object_get( schema, "contains" ),\n					items[i],\n					jschema_pointer_join( kwloc, "contains" ),\n					jschema_pointer_join( instloc, i ),\n					base_uri,\n				);\n				if ( child.valid() ) {\n					matches++;\n					result.mark_item( jschema_pointer_join( instloc, i ) );\n					result.merge(child);\n				}\n				i++;\n			}\n			let min := jschema_object_get( schema, "minContains", 1 );\n			let max := jschema_object_get( schema, "maxContains", null );\n			if ( validation_enabled and matches < min ) {\n				self._invalid( result, MinContainsError, jschema_pointer_join( kwloc, "minContains" ), instloc, "Array contains too few matching items.", "minContains" );\n				if ( not collect ) {\n					return;\n				}\n			}\n			if ( validation_enabled and max \u2262 null and matches > max ) {\n				self._invalid( result, MaxContainsError, jschema_pointer_join( kwloc, "maxContains" ), instloc, "Array contains too many matching items.", "maxContains" );\n				if ( not collect ) {\n					return;\n				}\n			}\n		}\n\n	}\n\n	method _validate_object ( result, schema, instance, kwloc, instloc, base_uri ) {\n		if ( not jschema_is_object(instance) ) {\n			return;\n		}\n		let keys := jschema_object_keys(instance);\n		let unique_keys := jschema_object_unique_keys(instance);\n		if ( validation_enabled ) {\n			if (\n				jschema_object_has( schema, "minProperties" )\n				and keys.length() < jschema_object_get( schema, "minProperties" )\n			) {\n				self._invalid( result, MinPropertiesError, jschema_pointer_join( kwloc, "minProperties" ), instloc, "Object has too few properties.", "minProperties" );\n				if ( not collect ) {\n					return;\n				}\n			}\n			if (\n				jschema_object_has( schema, "maxProperties" )\n				and keys.length() > jschema_object_get( schema, "maxProperties" )\n			) {\n				self._invalid( result, MaxPropertiesError, jschema_pointer_join( kwloc, "maxProperties" ), instloc, "Object has too many properties.", "maxProperties" );\n				if ( not collect ) {\n					return;\n				}\n			}\n			if ( jschema_object_has( schema, "required" ) ) {\n				for ( let key in jschema_object_get( schema, "required" ) ) {\n					if ( not jschema_object_has( instance, key ) ) {\n						self._invalid(\n							result,\n							RequiredPropertyError,\n							jschema_pointer_join( kwloc, "required" ),\n							instloc,\n							`Required property \'${key}\' is missing.`,\n							"required",\n						);\n						if ( not collect ) {\n							return;\n						}\n					}\n				}\n			}\n			if ( jschema_object_has( schema, "dependentRequired" ) ) {\n				let deps := jschema_object_get( schema, "dependentRequired" );\n				if ( jschema_is_object(deps) ) {\n					for ( let entry in jschema_object_entries(deps) ) {\n						if ( jschema_object_has( instance, entry[0] ) ) {\n							for ( let dep in entry[1] ) {\n								if ( not jschema_object_has( instance, dep ) ) {\n									self._invalid(\n										result,\n										DependentRequiredPropertyError,\n										jschema_pointer_join( kwloc, "dependentRequired" ),\n										instloc,\n										`Dependent property \'${dep}\' is missing.`,\n										"dependentRequired",\n									);\n									if ( not collect ) {\n										return;\n									}\n								}\n							}\n						}\n					}\n				}\n			}\n			if ( jschema_object_has( schema, "dependencies" ) ) {\n				let deps := jschema_object_get( schema, "dependencies" );\n				if ( jschema_is_object(deps) ) {\n					for ( let entry in jschema_object_entries(deps) ) {\n						if ( jschema_object_has( instance, entry[0] ) ) {\n							if ( entry[1] instanceof Array ) {\n								for ( let dep in entry[1] ) {\n									if ( not jschema_object_has( instance, dep ) ) {\n										self._invalid(\n											result,\n											DependentRequiredPropertyError,\n											jschema_pointer_join( kwloc, "dependencies" ),\n											instloc,\n											`Dependent property \'${dep}\' is missing.`,\n											"dependencies",\n										);\n										if ( not collect ) {\n											return;\n										}\n									}\n								}\n							}\n							else {\n								let child := self._child(\n									entry[1],\n									instance,\n									jschema_pointer_join(\n										jschema_pointer_join( kwloc, "dependencies" ),\n										entry[0],\n									),\n									instloc,\n									base_uri,\n								);\n								result.merge(child);\n								if ( not child.valid() ) {\n									result.add_error( self._subschema_error(\n										jschema_pointer_join(\n											jschema_pointer_join( kwloc, "dependencies" ),\n											entry[0],\n										),\n										instloc,\n										child.errors(),\n										"dependencies",\n									) );\n									if ( not collect ) { return result; }\n								}\n							}\n						}\n					}\n				}\n			}\n		}\n\n		let matched_properties := [];\n		if ( jschema_object_has( schema, "properties" ) ) {\n			let props := jschema_object_get( schema, "properties" );\n			if ( jschema_is_object(props) ) {\n				for ( let entry in jschema_object_entries(props) ) {\n					let key := entry[0];\n					if ( jschema_object_has( instance, key ) ) {\n						let ix := 0;\n						for ( let value in jschema_object_get_all( instance, key ) ) {\n							let child := self._child(\n								entry[1],\n								value,\n								jschema_pointer_join( jschema_pointer_join( kwloc, "properties" ), key ),\n								jschema_pointer_join( instloc, key ),\n								base_uri,\n							);\n							_jschema_add_unique( matched_properties, key );\n							result.mark_property( jschema_pointer_join( instloc, key ) );\n							result.merge(child);\n							if ( not child.valid() ) {\n								result.add_error( self._subschema_error(\n									jschema_pointer_join( jschema_pointer_join( kwloc, "properties" ), key ),\n									jschema_pointer_join( instloc, key ),\n									child.errors(),\n									"properties",\n								) );\n								if ( not collect ) { return result; }\n							}\n							ix++;\n						}\n					}\n				}\n			}\n		}\n\n		if ( jschema_object_has( schema, "patternProperties" ) ) {\n			let patterns := jschema_object_get( schema, "patternProperties" );\n			if ( jschema_is_object(patterns) ) {\n				for ( let pentry in jschema_object_entries(patterns) ) {\n					let pattern := pentry[0];\n					for ( let entry in jschema_object_entries(instance) ) {\n						let key := entry[0];\n						if ( key ~ _jschema_regexp(pattern) ) {\n							let child := self._child(\n								pentry[1],\n								entry[1],\n								jschema_pointer_join( jschema_pointer_join( kwloc, "patternProperties" ), pattern ),\n								jschema_pointer_join( instloc, key ),\n								base_uri,\n							);\n							_jschema_add_unique( matched_properties, key );\n							result.mark_property( jschema_pointer_join( instloc, key ) );\n							result.merge(child);\n							if ( not child.valid() ) {\n								result.add_error( self._subschema_error(\n									jschema_pointer_join( jschema_pointer_join( kwloc, "patternProperties" ), pattern ),\n									jschema_pointer_join( instloc, key ),\n									child.errors(),\n									"patternProperties",\n								) );\n								if ( not collect ) { return result; }\n							}\n						}\n					}\n				}\n			}\n		}\n\n		if ( jschema_object_has( schema, "additionalProperties" ) ) {\n			for ( let entry in jschema_object_entries(instance) ) {\n				let key := entry[0];\n				if ( not( key in matched_properties ) ) {\n					let child := self._child(\n						jschema_object_get( schema, "additionalProperties" ),\n						entry[1],\n						jschema_pointer_join( kwloc, "additionalProperties" ),\n						jschema_pointer_join( instloc, key ),\n						base_uri,\n					);\n					result.merge(child);\n					if ( not child.valid() ) {\n						result.add_error( self.error(\n							AdditionalPropertiesError,\n							jschema_pointer_join( kwloc, "additionalProperties" ),\n							jschema_pointer_join( instloc, key ),\n							"Additional property is not allowed.",\n							"additionalProperties",\n						) );\n						if ( not collect ) { return result; }\n					}\n					result.mark_property( jschema_pointer_join( instloc, key ) );\n				}\n			}\n		}\n\n		if ( jschema_object_has( schema, "propertyNames" ) ) {\n			for ( let key in unique_keys ) {\n				let child := self._child(\n					jschema_object_get( schema, "propertyNames" ),\n					key,\n					jschema_pointer_join( kwloc, "propertyNames" ),\n					jschema_pointer_join( instloc, key ),\n					base_uri,\n				);\n				result.merge(child);\n				if ( not child.valid() ) {\n					result.add_error( self.error(\n						PropertyNamesError,\n						jschema_pointer_join( kwloc, "propertyNames" ),\n						jschema_pointer_join( instloc, key ),\n						"Property name does not match schema.",\n						"propertyNames",\n					) );\n					if ( not collect ) { return result; }\n				}\n			}\n		}\n\n		if ( jschema_object_has( schema, "dependentSchemas" ) ) {\n			let deps := jschema_object_get( schema, "dependentSchemas" );\n			if ( jschema_is_object(deps) ) {\n				for ( let entry in jschema_object_entries(deps) ) {\n					if ( jschema_object_has( instance, entry[0] ) ) {\n						let child := self._child(\n							entry[1],\n							instance,\n							jschema_pointer_join( jschema_pointer_join( kwloc, "dependentSchemas" ), entry[0] ),\n							instloc,\n							base_uri,\n						);\n						result.merge(child);\n						if ( not child.valid() ) {\n							result.add_error( self._subschema_error(\n								jschema_pointer_join( jschema_pointer_join( kwloc, "dependentSchemas" ), entry[0] ),\n								instloc,\n								child.errors(),\n								"dependentSchemas",\n							) );\n							if ( not collect ) { return result; }\n						}\n					}\n				}\n			}\n		}\n\n	}\n\n	method _validate_unevaluated ( result, schema, instance, kwloc, instloc, base_uri ) {\n		if (\n			jschema_is_arrayish(instance)\n			and jschema_object_has( schema, "unevaluatedItems" )\n		) {\n			let items := jschema_array_items(instance);\n			let i := 0;\n			while ( i < items.length() ) {\n				if (\n					not( jschema_pointer_join( instloc, i )\n						in result.evaluatedItems() )\n				) {\n					let child := self._child(\n						jschema_object_get( schema, "unevaluatedItems" ),\n						items[i],\n						jschema_pointer_join( kwloc, "unevaluatedItems" ),\n						jschema_pointer_join( instloc, i ),\n						base_uri,\n					);\n					result.merge(child);\n					if ( not child.valid() ) {\n						result.add_error( self.error(\n							UnevaluatedItemsError,\n							jschema_pointer_join( kwloc, "unevaluatedItems" ),\n							jschema_pointer_join( instloc, i ),\n							"Unevaluated array item is not allowed.",\n							"unevaluatedItems",\n						) );\n						if ( not collect ) { return result; }\n					}\n					result.mark_item( jschema_pointer_join( instloc, i ) );\n				}\n				i++;\n			}\n		}\n\n		if (\n			jschema_is_object(instance)\n			and jschema_object_has( schema, "unevaluatedProperties" )\n		) {\n			for ( let entry in jschema_object_entries(instance) ) {\n				let key := entry[0];\n				if (\n					not( jschema_pointer_join( instloc, key )\n						in result.evaluatedProperties() )\n				) {\n					let child := self._child(\n						jschema_object_get( schema, "unevaluatedProperties" ),\n						entry[1],\n						jschema_pointer_join( kwloc, "unevaluatedProperties" ),\n						jschema_pointer_join( instloc, key ),\n						base_uri,\n					);\n					result.merge(child);\n					if ( not child.valid() ) {\n						result.add_error( self.error(\n							UnevaluatedPropertiesError,\n							jschema_pointer_join( kwloc, "unevaluatedProperties" ),\n							jschema_pointer_join( instloc, key ),\n							"Unevaluated property is not allowed.",\n							"unevaluatedProperties",\n						) );\n						if ( not collect ) { return result; }\n					}\n					result.mark_property( jschema_pointer_join( instloc, key ) );\n				}\n			}\n		}\n	}\n\n	method _validate_applicators ( result, schema, instance, kwloc, instloc, base_uri ) {\n		if ( jschema_object_has( schema, "allOf" ) ) {\n			let arr := jschema_object_get( schema, "allOf" );\n			if ( arr instanceof Array ) {\n				let i := 0;\n				while ( i < arr.length() ) {\n					let child := self._child( arr[i], instance, jschema_pointer_join( jschema_pointer_join( kwloc, "allOf" ), i ), instloc, base_uri );\n					if ( child.valid() ) {\n						result.merge(child);\n					}\n					else {\n						result.merge(child);\n						result.add_error( self.error( AllOfError, jschema_pointer_join( jschema_pointer_join( kwloc, "allOf" ), i ), instloc, "allOf subschema failed.", "allOf" ) );\n						if ( not collect ) { return result; }\n					}\n					i++;\n				}\n			}\n		}\n\n		if ( jschema_object_has( schema, "anyOf" ) ) {\n			let arr := jschema_object_get( schema, "anyOf" );\n			if ( arr instanceof Array ) {\n				let ok := false;\n				let child_errors := [];\n				let i := 0;\n				while ( i < arr.length() ) {\n					let child := self._child( arr[i], instance, jschema_pointer_join( jschema_pointer_join( kwloc, "anyOf" ), i ), instloc, base_uri );\n					if ( child.valid() ) {\n						ok := true;\n						result.merge(child);\n					}\n					else {\n						for ( let e in child.errors() ) { child_errors.push(e); }\n					}\n					i++;\n				}\n				if ( not ok ) {\n					result.add_error( self.error( AnyOfError, jschema_pointer_join( kwloc, "anyOf" ), instloc, "No anyOf subschema matched.", "anyOf" ) );\n					result.add_error( self._subschema_error( jschema_pointer_join( kwloc, "anyOf" ), instloc, child_errors, "anyOf" ) );\n					if ( not collect ) { return result; }\n				}\n			}\n		}\n\n		if ( jschema_object_has( schema, "oneOf" ) ) {\n			let arr := jschema_object_get( schema, "oneOf" );\n			if ( arr instanceof Array ) {\n				let matches := 0;\n				let child_errors := [];\n				let i := 0;\n				while ( i < arr.length() ) {\n					let child := self._child( arr[i], instance, jschema_pointer_join( jschema_pointer_join( kwloc, "oneOf" ), i ), instloc, base_uri );\n					if ( child.valid() ) {\n						matches++;\n						result.merge(child);\n					}\n					else {\n						for ( let e in child.errors() ) { child_errors.push(e); }\n					}\n					i++;\n				}\n				if ( matches != 1 ) {\n					result.add_error( self.error( OneOfError, jschema_pointer_join( kwloc, "oneOf" ), instloc, "Expected exactly one oneOf subschema to match.", "oneOf" ) );\n					if ( matches == 0 ) {\n						result.add_error( self._subschema_error( jschema_pointer_join( kwloc, "oneOf" ), instloc, child_errors, "oneOf" ) );\n					}\n					if ( not collect ) { return result; }\n				}\n			}\n		}\n\n		if ( jschema_object_has( schema, "not" ) ) {\n			let child := self._child( jschema_object_get( schema, "not" ), instance, jschema_pointer_join( kwloc, "not" ), instloc, base_uri );\n			if ( child.valid() ) {\n				self._invalid( result, NotMatchedError, jschema_pointer_join( kwloc, "not" ), instloc, "Value matched a forbidden subschema.", "not" );\n				if ( not collect ) { return result; }\n			}\n		}\n\n		if ( jschema_object_has( schema, "if" ) ) {\n			let cond := self._child( jschema_object_get( schema, "if" ), instance, jschema_pointer_join( kwloc, "if" ), instloc, base_uri );\n			if ( cond.valid() ) {\n				result.merge(cond);\n			}\n			if ( cond.valid() and jschema_object_has( schema, "then" ) ) {\n				let child := self._child( jschema_object_get( schema, "then" ), instance, jschema_pointer_join( kwloc, "then" ), instloc, base_uri );\n				result.merge(child);\n				if ( not child.valid() ) {\n					result.add_error( self.error( IfThenElseError, jschema_pointer_join( kwloc, "then" ), instloc, "then subschema failed.", "then" ) );\n					if ( not collect ) { return result; }\n				}\n			}\n			else if ( not cond.valid() and jschema_object_has( schema, "else" ) ) {\n				let child := self._child( jschema_object_get( schema, "else" ), instance, jschema_pointer_join( kwloc, "else" ), instloc, base_uri );\n				result.merge(child);\n				if ( not child.valid() ) {\n					result.add_error( self.error( IfThenElseError, jschema_pointer_join( kwloc, "else" ), instloc, "else subschema failed.", "else" ) );\n					if ( not collect ) { return result; }\n				}\n			}\n		}\n	}\n}\n\nclass JSONSchema {\n	let schema;\n	let options := {};\n	let registry;\n	let formats;\n	let String base_uri := "";\n	let Boolean format_assert := false;\n	let String unknown_format := "ignore";\n	let Boolean validation_enabled := true;\n\n	method __build__ () {\n		base_uri := _jschema_opt( options, "base_uri", base_uri );\n		registry := _jschema_opt( options, "registry", null );\n		if ( registry \u2261 null ) {\n			registry := new SchemaRegistry();\n		}\n		formats := _jschema_opt( options, "formats", null );\n		if ( formats \u2261 null ) {\n			formats := _jschema_opt( options, "format_registry", null );\n		}\n		if ( formats \u2261 null ) {\n			formats := new FormatRegistry();\n		}\n		let loader := _jschema_opt( options, "loader", null );\n		if ( loader \u2261 null and _jschema_opt( options, "allow_network", false ) ) {\n			loader := new HTTPResourceLoader();\n		}\n		if ( loader \u2262 null ) {\n			registry.set_loader(loader);\n		}\n		unknown_format := _jschema_opt( options, "unknown_format", "ignore" );\n		validation_enabled := _jschema_opt(\n			options,\n			"validation_enabled",\n			_jschema_validation_vocab_enabled( schema, registry, base_uri ),\n		);\n		format_assert := _jschema_format_assertion_vocab_enabled(\n			schema,\n			registry,\n			base_uri,\n			_jschema_opt( options, "format_assert", false ),\n		);\n		registry.register( schema, base_uri );\n	}\n\n	method _evaluator ( Boolean collect ) {\n		return new _SchemaEvaluator(\n			registry: registry,\n			formats: formats,\n			collect: collect,\n			format_assert: format_assert,\n			unknown_format: unknown_format,\n			validation_enabled: validation_enabled,\n		);\n	}\n\n	method is_valid ( instance ) {\n		return self._evaluator(false).evaluate(\n			schema,\n			instance,\n			"",\n			"",\n			base_uri,\n		).valid();\n	}\n\n	method validate ( instance ) {\n		let ev := self._evaluator(true).evaluate(\n			schema,\n			instance,\n			"",\n			"",\n			base_uri,\n		);\n		return new ValidationResult(\n			valid: ev.valid(),\n			errors: ev.errors(),\n		);\n	}\n}\n\nfunction valid ( schema, instance, options := {} ) {\n	return new JSONSchema( schema: schema, options: options ).is_valid(instance);\n}\n\nfunction validate ( schema, instance, options := {} ) {\n	return new JSONSchema( schema: schema, options: options ).validate(instance);\n}\n';
        virtualFiles["/modules/std/mail.zzm"] = `=encoding utf8

=head1 NAME

std/mail - Pure ZuzuScript mail message object model.

=head1 SYNOPSIS

  from std/mail import Address, Head, Body, Message;
  let message := new Message(
    head: new Head(),
    body: Body.bytes( to_binary("Hello\\r\\n") )
  );

=head1 IMPLEMENTATION SUPPORT

This module is supported by all implementations of ZuzuScript.

=head1 DESCRIPTION

This module provides the object model for RFC 5322-style message
headers, address objects, MIME-ish bodies, date helpers, a conservative
parser, and integration with compatible low-level mailers.

The parser ignores multipart preamble and epilogue bytes in Phase 9.
When either is present, C<Parser.warnings()> records the limitation.

The serializer can generate missing multipart boundaries on request.
C<Serializer.serialize()> writes matching C<Content-Type> output for the
generated boundary. C<Serializer.serialize_body()> returns only body bytes,
so callers using it with a generated boundary must provide the matching
C<Content-Type> header separately.

=head1 EXPORTS

=head2 Functions

=over

=item C<< parse_datetime(String text) >>

Parameters: C<text> is a mail date string. Returns: C<Time>. Parses a
mail header date into a C<std/time> object.

=item C<< format_datetime(Time time) >>

Parameters: C<time> is a C<std/time> object. Returns: C<String>. Formats
a time for use in mail headers.

=back

=head2 Classes

=over

=item C<Address>

Mail address object.

=over

=item C<< Address.parse(String text) >>, C<< Address.parse_list(String text) >>

Parameters: C<text> is address header text. Returns: C<Address> or
C<Array>. Parses one address or a comma-separated address list.

=item C<< address.local() >>, C<< address.domain() >>, C<< address.display_name() >>, C<< address.address() >>

Parameters: none. Returns: C<String> or C<null>. Returns address
components.

=item C<< address.to_header() >>, C<< address.to_String() >>

Parameters: none. Returns: C<String>. Formats the address.

=item C<< address.to_Dict() >>

Parameters: none. Returns: C<Dict>. Converts the address to a
dictionary.

=back

=item C<Head>

Ordered mail header collection.

=over

=item C<< head.fields() >>, C<< head.to_PairList() >>, C<< head.to_Iterator() >>

Parameters: none. Returns: C<PairList> or C<Function>. Returns header
fields or an iterator.

=item C<< head.raw(String name, fallback := null) >>, C<< head.raw_all(String name) >>, C<< head.decoded(String name, fallback := null) >>, C<< head.decoded_all(String name) >>, C<< head.get(String name, fallback := null) >>, C<< head.get_all(String name) >>

Parameters: C<name> is a header name and C<fallback> is optional.
Returns: C<String>, C<Array>, or fallback. Reads header values.

=item C<< head.set(String name, String value) >>, C<< head.add(String name, String value) >>, C<< head.remove(String name) >>

Parameters: C<name> is a header name and C<value> is header text.
Returns: C<Head>. Mutates header fields.

=item C<< head.has(String name) >>

Parameters: C<name> is a header name. Returns: C<Boolean>. Tests whether
a header exists.

=item C<< head.content_type() >>, C<< head.content_transfer_encoding() >>, C<< head.charset() >>, C<< head.boundary() >>, C<< head.message_id() >>, C<< head.date() >>, C<< head.from() >>, C<< head.to() >>, C<< head.cc() >>, C<< head.bcc() >>, C<< head.subject() >>

Parameters: none. Returns: header-specific value. Reads common headers.

=back

=item C<Body>

Mail body value.

=over

=item C<< Body.bytes(BinaryString raw, ... PairList options) >>

Parameters: C<raw> is body bytes and C<options> describe content type,
encoding, and parts. Returns: C<Body>. Creates a leaf or multipart body.

=item C<< Body.nested(message, ... PairList options) >>

Parameters: C<message> is a C<Message>. Returns: C<Body>. Creates a
nested message body.

=item C<< body.is_multipart() >>, C<< body.is_nested() >>

Parameters: none. Returns: C<Boolean>. Reports body shape.

=item C<< body.bytes() >>, C<< body.decoded() >>, C<< body.encoded() >>

Parameters: none. Returns: C<BinaryString>. Returns raw, decoded, or
encoded body bytes.

=item C<< body.parts() >>, C<< body.part(Number index) >>, C<< body.count() >>

Parameters: C<index> selects a body part. Returns: C<Array>, C<Body>, or
C<Number>. Reads multipart body parts.

=item C<< body.nested() >>, C<< body.content_type() >>, C<< body.transfer_encoding() >>, C<< body.to_Dict() >>

Parameters: none. Returns: value. Reads body metadata or converts the
body to a dictionary.

=back

=item C<Message>

Mail message object with C<head> and C<body>.

=over

=item C<< message.head() >>, C<< message.body() >>

Parameters: none. Returns: C<Head> or C<Body>. Returns message parts.

=item C<< message.header(String name, fallback := null) >>, C<< message.headers(String name) >>

Parameters: C<name> is a header name and C<fallback> is optional.
Returns: C<String>, C<Array>, or fallback. Reads message headers.

=item C<< message.set_header(String name, String value) >>, C<< message.add_header(String name, String value) >>, C<< message.remove_header(String name) >>

Parameters: C<name> is a header name and C<value> is header text.
Returns: C<Message>. Mutates message headers.

=item C<< message.subject() >>, C<< message.from() >>, C<< message.to() >>, C<< message.cc() >>, C<< message.bcc() >>, C<< message.date() >>, C<< message.message_id() >>

Parameters: none. Returns: header-specific value. Reads common message
headers.

=item C<< message.is_part() >>, C<< message.container() >>, C<< message.toplevel() >>

Parameters: none. Returns: C<Boolean> or C<Message>. Reads containment
state.

=item C<< message.send(mailer, ... PairList options) >>

Parameters: C<mailer> is a compatible low-level mailer. Returns: value.
Sends the message.

=item C<< message.to_Dict() >>

Parameters: none. Returns: C<Dict>. Converts the message to a
dictionary.

=back

=item C<Parser>

Conservative mail parser.

=over

=item C<< parser.warnings() >>

Parameters: none. Returns: C<Array>. Returns non-fatal parse warnings.

=item C<< parser.parse(BinaryString bytes) >>

Parameters: C<bytes> is raw message bytes. Returns: C<Message>. Parses a
mail message.

=back

=item C<Serializer>

Mail serializer.

=over

=item C<< serializer.serialize_body(Message message, ... PairList options) >>

Parameters: C<message> is a mail message and C<options> control output.
Returns: C<BinaryString>. Serializes only the message body.

=item C<< serializer.serialize(Message message, ... PairList options) >>

Parameters: C<message> is a mail message and C<options> control output.
Returns: C<BinaryString>. Serializes a complete message.

=back

=back

=head1 COPYRIGHT AND LICENCE

B<< std/mail >> is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under
the terms of either the Artistic License 1.0 or the GNU General Public
License version 2.

=cut

from std/string import chr, index, join, ord, substr, trim;

from std/string/base64 import
	encode as _base64_encode,
	decode as _base64_decode;
from std/string/quoted_printable import decode as _qp_decode;
from std/time import Time, TimeZone;

function _parse_one_address;
function _parse_address_list;
function _parse_address_header;
function _mail_send_serialize_body;

function _has_crlf ( String text ) {
	return index( text, "\\r" ) >= 0 or index( text, "\\n" ) >= 0;
}

function _assert_no_crlf ( String text, String context ) {
	if ( _has_crlf(text) ) {
		die \`mail.\${context}: value must not contain CR or LF\`;
	}
}

function _is_ws ( String ch ) {
	return ch eq " " or ch eq "\\t";
}

function _skip_ws ( String text, Number i ) {
	let pos := i;
	let n := length text;
	while ( pos < n and _is_ws( substr( text, pos, 1 ) ) ) {
		pos++;
	}
	return pos;
}

function _div_floor ( Number n, Number d ) {
	return floor( n / d );
}

function _hex_value ( String ch ) {
	let v := index( "0123456789ABCDEF", uc(ch) );
	return v;
}

function _bytes_to_binary ( Array bytes ) {
	let alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
		_ "abcdefghijklmnopqrstuvwxyz0123456789+/";
	let out := "";
	let i := 0;
	let n := bytes.length();

	while ( i < n ) {
		let b0 := bytes[i];
		let b1 := null;
		let b2 := null;
		if ( i + 1 < n ) {
			b1 := bytes[i + 1];
		}
		if ( i + 2 < n ) {
			b2 := bytes[i + 2];
		}

		let c0 := _div_floor( b0, 4 );
		let c1 := ( b0 mod 4 ) * 16;
		let c2 := 64;
		let c3 := 64;

		if ( not( b1 == null ) ) {
			c1 += _div_floor( b1, 16 );
			c2 := ( b1 mod 16 ) * 4;
			if ( not( b2 == null ) ) {
				c2 += _div_floor( b2, 64 );
				c3 := b2 mod 64;
			}
		}

		out _= substr( alphabet, c0, 1 );
		out _= substr( alphabet, c1, 1 );
		out _= c2 == 64 ? "=" : substr( alphabet, c2, 1 );
		out _= c3 == 64 ? "=" : substr( alphabet, c3, 1 );
		i += 3;
	}

	return _base64_decode(out);
}

function _binary_to_bytes ( BinaryString raw ) {
	let alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
		_ "abcdefghijklmnopqrstuvwxyz0123456789+/";
	let b64 := _base64_encode(raw);
	let out := [];
	let i := 0;
	let n := length b64;

	while ( i < n ) {
		let c0 := index( alphabet, substr( b64, i, 1 ) );
		let c1 := index( alphabet, substr( b64, i + 1, 1 ) );
		let ch2 := substr( b64, i + 2, 1 );
		let ch3 := substr( b64, i + 3, 1 );
		let c2 := -1;
		let c3 := -1;
		if ( ch2 ne "=" ) {
			c2 := index( alphabet, ch2 );
		}
		if ( ch3 ne "=" ) {
			c3 := index( alphabet, ch3 );
		}

		out.push( c0 * 4 + _div_floor( c1, 16 ) );
		if ( c2 >= 0 ) {
			out.push( ( c1 mod 16 ) * 16 + _div_floor( c2, 4 ) );
		}
		if ( c3 >= 0 ) {
			out.push( ( c2 mod 4 ) * 64 + c3 );
		}

		i += 4;
	}

	return out;
}

function _latin1_to_string ( BinaryString raw ) {
	let out := "";
	for ( let b in _binary_to_bytes(raw) ) {
		out _= chr(b);
	}
	return out;
}

function _read_quoted_string ( String text, Number start ) {
	let n := length text;
	if ( substr( text, start, 1 ) ne "\\"" ) {
		die "mail.invalid_address: expected quoted string";
	}

	let out := "";
	let i := start + 1;
	while ( i < n ) {
		let ch := substr( text, i, 1 );
		if ( ch eq "\\"" ) {
			return { value: out, end: i + 1 };
		}
		if ( ch eq "\\\\" ) {
			if ( i + 1 >= n ) {
				die "mail.invalid_address: unterminated quoted string";
			}
			out _= substr( text, i + 1, 1 );
			i += 2;
			next;
		}
		if ( ch eq "\\r" or ch eq "\\n" ) {
			die "mail.invalid_address: quoted string must not contain CR or LF";
		}
		out _= ch;
		i++;
	}

	die "mail.invalid_address: unterminated quoted string";
}

function _quote_string ( String text ) {
	let out := "\\"";
	let i := 0;
	let n := length text;

	while ( i < n ) {
		let ch := substr( text, i, 1 );
		if ( ch eq "\\\\" or ch eq "\\"" ) {
			out _= "\\\\";
		}
		out _= ch;
		i++;
	}

	return out _ "\\"";
}

function _is_alpha ( String ch ) {
	let cp := ord(ch);
	return ( cp >= 65 and cp <= 90 ) or ( cp >= 97 and cp <= 122 );
}

function _is_digit ( String ch ) {
	let cp := ord(ch);
	return cp >= 48 and cp <= 57;
}

function _is_atext ( String ch ) {
	if ( _is_alpha(ch) or _is_digit(ch) ) {
		return true;
	}
	return index( "!#$%&'*+-/=?^_\`{|}~", ch ) >= 0;
}

function _is_dot_atom ( String text ) {
	let n := length text;
	return false if n == 0;
	return false if substr( text, 0, 1 ) eq ".";
	return false if substr( text, n - 1, 1 ) eq ".";

	let prev_dot := false;
	let i := 0;
	while ( i < n ) {
		let ch := substr( text, i, 1 );
		if ( ch eq "." ) {
			return false if prev_dot;
			prev_dot := true;
		}
		else {
			return false if not _is_atext(ch);
			prev_dot := false;
		}
		i++;
	}

	return true;
}

function _is_domain_text ( String text ) {
	let n := length text;
	return false if n == 0;
	return false if substr( text, 0, 1 ) eq ".";
	return false if substr( text, n - 1, 1 ) eq ".";

	let i := 0;
	while ( i < n ) {
		let ch := substr( text, i, 1 );
		return false if not(
			_is_alpha(ch)
			or _is_digit(ch)
			or ch eq "-"
			or ch eq "."
		);
		i++;
	}

	return true;
}

function _is_phrase_text ( String text ) {
	let n := length text;
	return false if n == 0;
	return false if text ne trim(text);

	let i := 0;
	while ( i < n ) {
		let ch := substr( text, i, 1 );
		if ( _is_ws(ch) ) {
			i++;
			next;
		}
		return false if not _is_atext(ch) and ch ne ".";
		i++;
	}

	return true;
}

function _find_unquoted (
	String text,
	String target,
	Number start := 0,
	Boolean ignore_angle := false,
) {
	let i := start;
	let n := length text;
	let in_quote := false;
	let escape := false;
	let in_literal := false;
	let angle_depth := 0;

	while ( i < n ) {
		let ch := substr( text, i, 1 );

		if ( escape ) {
			escape := false;
			i++;
			next;
		}
		if ( in_quote ) {
			if ( ch eq "\\\\" ) {
				escape := true;
			}
			else if ( ch eq "\\"" ) {
				in_quote := false;
			}
			i++;
			next;
		}
		if ( in_literal ) {
			if ( ch eq "]" ) {
				in_literal := false;
			}
			i++;
			next;
		}

		if ( ch eq target and ( not ignore_angle or angle_depth == 0 ) ) {
			return i;
		}
		if ( ch eq "\\"" ) {
			in_quote := true;
		}
		else if ( ch eq "[" ) {
			in_literal := true;
		}
		else if ( ch eq "<" ) {
			angle_depth++;
		}
		else if ( ch eq ">" and angle_depth > 0 ) {
			angle_depth--;
		}

		i++;
	}

	return -1;
}

function _find_top_level ( String text, String target, Number start := 0 ) {
	return _find_unquoted( text, target, start, true );
}

function _parse_phrase ( String raw ) {
	let text := trim(raw);
	return null if text eq "";

	if ( substr( text, 0, 1 ) eq "\\"" ) {
		let quoted := _read_quoted_string( text, 0 );
		if ( trim( substr( text, quoted{end} ) ) ne "" ) {
			die "mail.invalid_address: text follows quoted display name";
		}
		return quoted{value};
	}

	return text;
}

function _parse_addr_spec ( String raw ) {
	let text := trim(raw);
	_assert_no_crlf( text, "invalid_address" );

	if ( substr( text, 0, 1 ) eq "@" ) {
		die "mail.invalid_address: obsolete route syntax is not supported";
	}

	let at := _find_unquoted( text, "@", 0, false );
	if ( at < 0 ) {
		die "mail.invalid_address: mailbox address is missing @";
	}

	let route := _find_unquoted( text, ":", 0, false );
	if ( route >= 0 and route < at ) {
		die "mail.invalid_address: obsolete route syntax is not supported";
	}

	let local := trim( substr( text, 0, at ) );
	let domain := trim( substr( text, at + 1 ) );
	if ( local eq "" or domain eq "" ) {
		die "mail.invalid_address: mailbox address is incomplete";
	}

	if ( substr( local, 0, 1 ) eq "\\"" ) {
		let quoted := _read_quoted_string( local, 0 );
		if ( quoted{end} != length local ) {
			die "mail.invalid_address: text follows quoted local part";
		}
		local := quoted{value};
	}
	else if ( not _is_dot_atom(local) ) {
		die "mail.invalid_address: invalid local part";
	}

	if ( substr( domain, 0, 1 ) eq "[" ) {
		if ( substr( domain, ( length domain ) - 1, 1 ) ne "]" ) {
			die "mail.invalid_address: unterminated domain literal";
		}
		if ( _has_crlf(domain) ) {
			die "mail.invalid_address: invalid domain literal";
		}
	}
	else if ( not _is_domain_text(domain) ) {
		die "mail.invalid_address: invalid domain";
	}

	return { local: local, domain: domain };
}

function _decode_q_encoded_word ( String text ) {
	let bytes := [];
	let i := 0;
	let n := length text;

	while ( i < n ) {
		let ch := substr( text, i, 1 );
		if ( ch eq "_" ) {
			bytes.push(32);
			i++;
			next;
		}
		if ( ch eq "=" ) {
			if ( i + 2 >= n ) {
				return null;
			}
			let hi := _hex_value( substr( text, i + 1, 1 ) );
			let lo := _hex_value( substr( text, i + 2, 1 ) );
			if ( hi < 0 or lo < 0 ) {
				return null;
			}
			bytes.push( hi * 16 + lo );
			i += 3;
			next;
		}

		let cp := ord(ch);
		return null if cp > 127;
		bytes.push(cp);
		i++;
	}

	return _bytes_to_binary(bytes);
}

function _normal_charset ( String charset ) {
	let cs := lc(charset);
	if ( cs in [ "utf-8", "utf8" ] ) {
		return "utf-8";
	}
	if ( cs in [ "us-ascii", "ascii" ] ) {
		return "us-ascii";
	}
	if ( cs in [ "latin1", "latin-1", "iso-8859-1", "iso8859-1" ] ) {
		return "latin1";
	}
	return null;
}

function _decode_charset_bytes ( BinaryString bytes, String charset ) {
	let cs := _normal_charset(charset);
	return null if cs == null;

	if ( cs eq "latin1" ) {
		return _latin1_to_string(bytes);
	}

	return try {
		to_string(bytes);
	}
	catch {
		null;
	};
}

function _parse_encoded_word_at ( String text, Number start ) {
	if ( substr( text, start, 2 ) ne "=?" ) {
		return null;
	}

	let q1 := index( text, "?", start + 2 );
	return null if q1 < 0;
	let q2 := index( text, "?", q1 + 1 );
	return null if q2 < 0;
	let end := index( text, "?=", q2 + 1 );
	return null if end < 0;

	let charset := substr( text, start + 2, q1 - start - 2 );
	let encoding := lc( substr( text, q1 + 1, q2 - q1 - 1 ) );
	let payload := substr( text, q2 + 1, end - q2 - 1 );
	let bytes := null;

	if ( charset eq "" or payload eq "" ) {
		return null;
	}
	if ( encoding eq "b" ) {
		bytes := try {
			_base64_decode(payload);
		}
		catch {
			null;
		};
	}
	else if ( encoding eq "q" ) {
		bytes := _decode_q_encoded_word(payload);
	}
	else {
		return null;
	}

	return null if bytes == null;
	let decoded := _decode_charset_bytes( bytes, charset );
	return null if decoded == null;

	return { text: decoded, end: end + 2 };
}

function _decode_rfc2047 ( String raw ) {
	let out := "";
	let pending_ws := "";
	let last_encoded := false;
	let i := 0;
	let n := length raw;

	while ( i < n ) {
		let ch := substr( raw, i, 1 );
		if ( _is_ws(ch) ) {
			let start := i;
			while ( i < n and _is_ws( substr( raw, i, 1 ) ) ) {
				i++;
			}
			pending_ws _= substr( raw, start, i - start );
			next;
		}

		if ( substr( raw, i, 2 ) eq "=?" ) {
			let parsed := _parse_encoded_word_at( raw, i );
			if ( not( parsed == null ) ) {
				out _= pending_ws unless last_encoded;
				pending_ws := "";
				out _= parsed{text};
				last_encoded := true;
				i := parsed{end};
				next;
			}
		}

		out _= pending_ws;
		pending_ws := "";
		out _= ch;
		last_encoded := false;
		i++;
	}

	return out _ pending_ws;
}

function _copy_pairlist ( fields ) {
	let copy := new PairList();
	if ( fields == null ) {
		return copy;
	}
	if ( not( fields instanceof PairList ) ) {
		die "mail.invalid_headers: Head fields expects PairList";
	}
	for ( let pair in fields.to_Array() ) {
		copy.add( pair.key, pair.value );
	}
	return copy;
}

function _mail_send_recipients_option ( value ) {
	if ( value instanceof String ) {
		return [ value ];
	}
	if ( not( value instanceof Array ) ) {
		die "mail.send: envelope_to expects String or Array";
	}

	let out := [];
	for ( let item in value ) {
		if ( not( item instanceof String ) ) {
			die "mail.send: envelope_to expects String or Array of String";
		}
		out.push(item);
	}
	if ( out.length() == 0 ) {
		die "mail.invalid_address: Message.send requires at least one "
			_ "envelope recipient";
	}
	return out;
}

function _mail_send_options ( PairList options ) {
	let out := {
		envelope_from: null,
		envelope_to: null,
		send_options: new PairList(),
	};

	for ( let pair in options.to_Array() ) {
		if ( pair.key eq "envelope_from" ) {
			if ( not( pair.value instanceof String ) ) {
				die "mail.send: envelope_from expects String";
			}
			out{envelope_from} := pair.value;
		}
		else if ( pair.key eq "envelope_to" ) {
			out{envelope_to} := _mail_send_recipients_option(pair.value);
		}
		else if ( pair.key eq "send_options" ) {
			if ( not( pair.value instanceof Dict )
				and not( pair.value instanceof PairList ) ) {
				die "mail.send: send_options expects Dict or PairList";
			}
			out{send_options} := pair.value;
		}
		else {
			die "mail.send: unsupported option '" _ pair.key _ "'";
		}
	}

	return out;
}

function _valid_header_name ( String name ) {
	let n := length name;
	return false if n == 0;
	let i := 0;
	while ( i < n ) {
		let cp := ord( substr( name, i, 1 ) );
		return false if cp < 33 or cp > 126 or cp == 58;
		i++;
	}
	return true;
}

function _check_header_name ( String name ) {
	if ( not _valid_header_name(name) ) {
		die "mail.invalid_headers: invalid header name";
	}
}

function _check_header_value ( value ) {
	if ( not( value instanceof String ) ) {
		die "mail.invalid_headers: header value expects String, got "
			_ typeof value;
	}
	_assert_no_crlf( value, "invalid_headers" );
}

function _split_header_segments ( String text, String delimiter ) {
	let out := [];
	let start := 0;
	let i := 0;
	let n := length text;
	let in_quote := false;
	let escape := false;

	while ( i < n ) {
		let ch := substr( text, i, 1 );
		if ( escape ) {
			escape := false;
		}
		else if ( in_quote ) {
			if ( ch eq "\\\\" ) {
				escape := true;
			}
			else if ( ch eq "\\"" ) {
				in_quote := false;
			}
		}
		else if ( ch eq "\\"" ) {
			in_quote := true;
		}
		else if ( ch eq delimiter ) {
			out.push( substr( text, start, i - start ) );
			start := i + 1;
		}
		i++;
	}
	out.push( substr( text, start ) );

	return out;
}

function _unquote_header_param ( String text ) {
	let value := trim(text);
	if ( length value >= 2 and substr( value, 0, 1 ) eq "\\"" ) {
		let quoted := _read_quoted_string( value, 0 );
		if ( trim( substr( value, quoted{end} ) ) eq "" ) {
			return quoted{value};
		}
	}
	return value;
}

function _header_main_value ( String value ) {
	let parts := _split_header_segments( value, ";" );
	return lc( trim( parts[0] ) );
}

function _header_parameter ( String value, String wanted ) {
	let parts := _split_header_segments( value, ";" );
	let i := 1;
	while ( i < parts.length() ) {
		let part := parts[i];
		let equals_at := _find_unquoted( part, "=", 0, false );
		if ( equals_at > 0 ) {
			let name := lc( trim( substr( part, 0, equals_at ) ) );
			if ( name eq lc(wanted) ) {
				return _unquote_header_param( substr( part, equals_at + 1 ) );
			}
		}
		i++;
	}
	return null;
}

function _body_options ( PairList options ) {
	let opts := {
		content_type: null,
		transfer_encoding: null,
		charset: null,
		boundary: null,
	};

	for ( let option in options.to_Array() ) {
		let key := option.key;
		let value := option.value;
		if ( key eq "content_type" ) {
			opts{content_type} := value;
		}
		else if ( key eq "transfer_encoding"
			or key eq "content_transfer_encoding" ) {
			opts{transfer_encoding} := value;
		}
		else if ( key eq "charset" ) {
			opts{charset} := value;
		}
		else if ( key eq "boundary" ) {
			opts{boundary} := value;
		}
		else {
			die \`mail.body: unsupported Body option '\${key}'\`;
		}
	}

	return opts;
}

function _copy_array ( Array items ) {
	let out := [];
	for ( let item in items ) {
		out.push(item);
	}
	return out;
}

function _bytes_slice ( Array bytes, Number start, count := null ) {
	let out := [];
	let end := count == null ? bytes.length() : start + count;
	end := bytes.length() if end > bytes.length();
	let i := start;

	while ( i < end ) {
		out.push(bytes[i]);
		i++;
	}

	return out;
}

function _bytes_to_latin1_string ( Array bytes ) {
	return _latin1_to_string( _bytes_to_binary(bytes) );
}

function _split_message_bytes ( Array bytes ) {
	let n := bytes.length();
	let i := 0;
	let line_start := 0;

	while ( i < n ) {
		if ( bytes[i] == 10 ) {
			let content_end := i;
			if ( content_end > line_start and bytes[content_end - 1] == 13 ) {
				content_end--;
			}
			if ( content_end == line_start ) {
				return {
					header_bytes: _bytes_slice( bytes, 0, line_start ),
					body_bytes: _bytes_slice( bytes, i + 1 ),
					header_size: line_start,
					found_separator: true,
				};
			}
			i++;
			line_start := i;
			next;
		}
		i++;
	}

	return {
		header_bytes: _bytes_slice( bytes, 0 ),
		body_bytes: [],
		header_size: n,
		found_separator: false,
	};
}

function _mail_header_lines ( Array bytes ) {
	let lines := [];
	let n := bytes.length();
	let i := 0;
	let line_start := 0;

	while ( i < n ) {
		if ( bytes[i] == 10 ) {
			let content_end := i;
			if ( content_end > line_start and bytes[content_end - 1] == 13 ) {
				content_end--;
			}
			lines.push(
				_bytes_to_latin1_string(
					_bytes_slice( bytes, line_start, content_end - line_start ),
				),
			);
			i++;
			line_start := i;
			next;
		}
		i++;
	}

	if ( line_start < n ) {
		lines.push( _bytes_to_latin1_string( _bytes_slice( bytes, line_start ) ) );
	}

	return lines;
}

function _parse_mail_header_fields ( Array header_bytes ) {
	let fields := new PairList();
	let current_name := null;
	let current_value := "";

	for ( let line in _mail_header_lines(header_bytes) ) {
		next if line eq "";

		if ( _is_ws( substr( line, 0, 1 ) ) ) {
			if ( current_name == null ) {
				die "mail.parse: folded header without previous field";
			}
			current_value _= " " _ trim(line);
			next;
		}

		if ( not( current_name == null ) ) {
			fields.add( current_name, current_value );
		}

		let colon := index( line, ":" );
		if ( colon <= 0 ) {
			die "mail.parse: malformed header line";
		}

		current_name := substr( line, 0, colon );
		if ( not _valid_header_name(current_name) ) {
			die "mail.parse: invalid header name";
		}
		current_value := trim( substr( line, colon + 1 ) );
	}

	if ( not( current_name == null ) ) {
		fields.add( current_name, current_value );
	}

	return fields;
}

function _only_sp_tab ( String text ) {
	let i := 0;
	let n := length text;

	while ( i < n ) {
		return false if not _is_ws( substr( text, i, 1 ) );
		i++;
	}

	return true;
}

function _mail_boundary_line_kind ( Array line_bytes, String boundary ) {
	let line := _bytes_to_latin1_string(line_bytes);
	let delimiter := "--" _ boundary;
	let dlen := length delimiter;

	return null if length line < dlen;
	return null if substr( line, 0, dlen ) ne delimiter;

	let tail := substr( line, dlen );
	return "open" if _only_sp_tab(tail);

	if ( length tail >= 2 and substr( tail, 0, 2 ) eq "--" ) {
		return "close" if _only_sp_tab( substr( tail, 2 ) );
	}

	return null;
}

function _mail_part_end_before_boundary (
	Array bytes,
	Number part_start,
	Number line_start
) {
	let end := line_start;
	if ( end > part_start and bytes[end - 1] == 10 ) {
		end--;
		if ( end > part_start and bytes[end - 1] == 13 ) {
			end--;
		}
	}
	return end;
}

function _scan_multipart_parts ( Array bytes, String boundary ) {
	let parts := [];
	let n := bytes.length();
	let line_start := 0;
	let opened := false;
	let closed := false;
	let part_start := 0;
	let preamble_size := 0;
	let epilogue_size := 0;

	while ( line_start < n ) {
		let line_end := line_start;
		while ( line_end < n and bytes[line_end] != 10 ) {
			line_end++;
		}

		let content_end := line_end;
		if ( content_end > line_start and bytes[content_end - 1] == 13 ) {
			content_end--;
		}

		let after_line := line_end < n ? line_end + 1 : n;
		let kind := _mail_boundary_line_kind(
			_bytes_slice( bytes, line_start, content_end - line_start ),
			boundary,
		);

		if ( not( kind == null ) ) {
			if ( not opened ) {
				opened := true;
				preamble_size := line_start;
				part_start := after_line;
				if ( kind eq "close" ) {
					closed := true;
					epilogue_size := n - after_line;
					return {
						opened: opened,
						closed: closed,
						parts: parts,
						preamble_size: preamble_size,
						epilogue_size: epilogue_size,
					};
				}
			}
			else {
				let part_end := _mail_part_end_before_boundary(
					bytes,
					part_start,
					line_start,
				);
				parts.push(
					_bytes_slice( bytes, part_start, part_end - part_start ),
				);
				part_start := after_line;

				if ( kind eq "close" ) {
					closed := true;
					epilogue_size := n - after_line;
					return {
						opened: opened,
						closed: closed,
						parts: parts,
						preamble_size: preamble_size,
						epilogue_size: epilogue_size,
					};
				}
			}
		}

		line_start := after_line;
	}

	if ( opened and not closed ) {
		parts.push( _bytes_slice( bytes, part_start ) );
	}

	return {
		opened: opened,
		closed: closed,
		parts: parts,
		preamble_size: preamble_size,
		epilogue_size: epilogue_size,
	};
}

function _is_identity_transfer_encoding ( encoding ) {
	if ( encoding == null or encoding eq "" ) {
		return true;
	}
	return encoding in [ "identity", "7bit", "8bit", "binary" ];
}

function _invalid_datetime ( String message ) {
	die "mail.invalid_datetime: " _ message;
}

function _numeric_zone_seconds ( String zone ) {
	return null if not( zone ~ /^[+-][0-9]{4}$/ );

	let sign := substr( zone, 0, 1 ) eq "-" ? -1 : 1;
	let hours := int( substr( zone, 1, 2 ) );
	let minutes := int( substr( zone, 3, 2 ) );
	return null if hours > 23 or minutes > 59;
	return sign * ( hours * 3600 + minutes * 60 );
}

function _datetime_apply_option ( Dict opts, Dict seen, key, value ) {
	if ( not( key instanceof String ) ) {
		_invalid_datetime("format option names must be strings");
	}
	if ( seen.exists(key) ) {
		_invalid_datetime( "conflicting format option '" _ key _ "'" );
	}
	seen.set( key, true );

	if ( key eq "utc" ) {
		if ( not( value instanceof Boolean ) ) {
			_invalid_datetime("format option 'utc' expects Boolean");
		}
		opts{utc} := value;
		opts{utc_seen} := true;
		return;
	}
	if ( key eq "offset" ) {
		if ( not( value instanceof String ) ) {
			_invalid_datetime("format option 'offset' expects String");
		}
		let seconds := _numeric_zone_seconds(value);
		if ( seconds == null ) {
			_invalid_datetime("format option 'offset' expects +HHMM or -HHMM");
		}
		opts{offset} := value;
		opts{offset_seconds} := seconds;
		opts{offset_seen} := true;
		return;
	}
	if ( key eq "include_weekday" ) {
		if ( not( value instanceof Boolean ) ) {
			_invalid_datetime("format option 'include_weekday' expects Boolean");
		}
		opts{include_weekday} := value;
		return;
	}

	_invalid_datetime( "unknown format option '" _ key _ "'" );
}

function _datetime_options ( options, PairList named_options ) {
	let opts := {
		utc: true,
		utc_seen: false,
		offset: "+0000",
		offset_seconds: 0,
		offset_seen: false,
		include_weekday: true,
	};
	let seen := {};

	if ( options instanceof Dict ) {
		for ( let key in options.keys() ) {
			_datetime_apply_option( opts, seen, key, options.get(key) );
		}
	}
	else if ( options instanceof PairList ) {
		for ( let pair in options.to_Array() ) {
			_datetime_apply_option( opts, seen, pair.key, pair.value );
		}
	}
	else {
		_invalid_datetime("format options expects Dict");
	}

	for ( let pair in named_options.to_Array() ) {
		_datetime_apply_option( opts, seen, pair.key, pair.value );
	}

	if ( opts{offset_seen} and not opts{utc_seen} ) {
		opts{utc} := false;
	}
	if ( opts{utc} and opts{offset_seconds} != 0 ) {
		_invalid_datetime("format options 'utc' and 'offset' conflict");
	}
	return opts;
}

function _datetime_parse_error_message ( e ) {
	let message := lc( "" _ e );
	return "invalid time zone" if index( message, "invalid time zone" ) >= 0;
	return "invalid time zone" if index( message, "timezone offset" ) >= 0;
	return "invalid date" if index( message, "invalid date" ) >= 0;
	return "invalid time" if index( message, "invalid time" ) >= 0;
	return "invalid month" if index( message, "invalid month" ) >= 0;
	return "invalid weekday" if index( message, "invalid weekday" ) >= 0;
	return "invalid year" if index( message, "invalid year" ) >= 0;
	return "expected RFC 5322 date-time";
}

function parse_datetime ( String text ) {
	_assert_no_crlf( text, "invalid_datetime" );

	try {
		return Time.parse( trim(text) );
	}
	catch ( Exception e ) {
		_invalid_datetime( _datetime_parse_error_message(e) );
	}
}

function format_datetime (
	time,
	options := {},
	... PairList named_options
) {
	if ( not( time instanceof Time ) ) {
		_invalid_datetime("format_datetime expects Time");
	}

	let opts := _datetime_options( options, named_options );
	let zoned := opts{utc}
		? time.with_timezone( TimeZone.utc() )
		: time.with_timezone( TimeZone.offset(opts{offset_seconds}) );
	return zoned.to_rfc5322( include_weekday: opts{include_weekday} );
}

class Address {
	let local := null;
	let domain := null;
	let display_name := null;

	method __build__ () {
		if ( not( local instanceof String ) or local eq "" ) {
			die "mail.invalid_address: local part expects non-empty String";
		}
		if ( not( domain instanceof String ) or domain eq "" ) {
			die "mail.invalid_address: domain expects non-empty String";
		}
		if ( not( display_name == null ) and not( display_name instanceof String ) ) {
			die "mail.invalid_address: display_name expects String or null";
		}

		_assert_no_crlf( local, "invalid_address" );
		_assert_no_crlf( domain, "invalid_address" );
		if ( not( display_name == null ) ) {
			_assert_no_crlf( display_name, "invalid_address" );
		}
	}

	method local () {
		return local;
	}

	method domain () {
		return domain;
	}

	method display_name () {
		return display_name;
	}

	method address () {
		let lhs := _is_dot_atom(local) ? local : _quote_string(local);
		return lhs _ "@" _ domain;
	}

	method to_header () {
		if ( display_name == null or display_name eq "" ) {
			return self.address();
		}

		let name := _is_phrase_text(display_name)
			? display_name
			: _quote_string(display_name);
		return name _ " <" _ self.address() _ ">";
	}

	method to_String () {
		return self.to_header();
	}

	method to_Dict () {
		return {
			local: local,
			domain: domain,
			display_name: display_name,
			address: self.address(),
			header: self.to_header(),
		};
	}

	static method parse ( String text ) {
		return _parse_one_address(text);
	}

	static method parse_list ( String text ) {
		return _parse_address_list(text);
	}
}

function _parse_one_address ( String raw ) {
	let text := trim(raw);
	_assert_no_crlf( text, "invalid_address" );

	if ( text eq "" ) {
		die "mail.invalid_address: empty address";
	}
	if ( _find_unquoted( text, "(", 0, false ) >= 0
		or _find_unquoted( text, ")", 0, false ) >= 0 ) {
		die "mail.invalid_address: obsolete comment syntax is not supported";
	}

	let angle_start := _find_unquoted( text, "<", 0, false );
	if ( angle_start >= 0 ) {
		let angle_end := _find_unquoted( text, ">", angle_start + 1, false );
		if ( angle_end < 0 ) {
			die "mail.invalid_address: unterminated angle address";
		}
		if ( trim( substr( text, angle_end + 1 ) ) ne "" ) {
			die "mail.invalid_address: text follows angle address";
		}

		let spec := _parse_addr_spec(
			substr( text, angle_start + 1, angle_end - angle_start - 1 ),
		);
		return new Address(
			local: spec{local},
			domain: spec{domain},
			display_name: _parse_phrase( substr( text, 0, angle_start ) ),
		);
	}

	let spec := _parse_addr_spec(text);
	return new Address( local: spec{local}, domain: spec{domain} );
}

function _parse_address_list ( String text ) {
	_assert_no_crlf( text, "invalid_address" );

	let out := [];
	let i := 0;
	let n := length text;

	while ( i < n ) {
		i := _skip_ws( text, i );
		if ( i < n and substr( text, i, 1 ) eq "," ) {
			i++;
			next;
		}

		let comma := _find_top_level( text, ",", i );
		let semi := _find_top_level( text, ";", i );
		let colon := _find_top_level( text, ":", i );
		let group_end := semi;

		if ( colon >= 0
			and ( comma < 0 or colon < comma )
			and ( semi < 0 or colon < semi ) ) {
			if ( group_end < 0 ) {
				die "mail.invalid_address: unterminated address group";
			}
			for ( let addr in _parse_address_list(
				substr( text, colon + 1, group_end - colon - 1 ),
			) ) {
				out.push(addr);
			}
			i := group_end + 1;
			next;
		}

		let end := comma < 0 ? n : comma;
		if ( semi >= 0 and semi < end ) {
			end := semi;
		}
		let token := trim( substr( text, i, end - i ) );
		if ( token ne "" ) {
			out.push( Address.parse(token) );
		}
		i := end + 1;
	}

	return out;
}

function _parse_address_header ( value ) {
	if ( value == null ) {
		return [];
	}
	return Address.parse_list(value);
}

function _mail_send_addresses_from_headers ( head, Array names ) {
	let out := [];
	for ( let name in names ) {
		for ( let value in head.decoded_all(name) ) {
			for ( let address in Address.parse_list(value) ) {
				out.push(address);
			}
		}
	}
	return out;
}

function _mail_send_envelope_from ( head ) {
	let senders := _mail_send_addresses_from_headers( head, [ "Sender" ] );
	if ( senders.length() == 1 ) {
		return senders[0].address();
	}
	if ( senders.length() > 1 ) {
		die "mail.invalid_address: Message.send requires exactly one "
			_ "Sender address";
	}

	let from_addrs := _mail_send_addresses_from_headers( head, [ "From" ] );
	if ( from_addrs.length() == 1 ) {
		return from_addrs[0].address();
	}
	if ( from_addrs.length() > 1 ) {
		die "mail.invalid_address: Message.send requires exactly one "
			_ "From address when Sender is absent";
	}
	die "mail.invalid_address: Message.send requires a Sender or From "
		_ "address";
}

function _mail_send_envelope_to ( head ) {
	let addresses := _mail_send_addresses_from_headers(
		head,
		[ "To", "Cc", "Bcc" ],
	);
	let seen := {};
	let out := [];

	for ( let address in addresses ) {
		let value := address.address();
		if ( not( value in seen ) ) {
			seen{(value)} := true;
			out.push(value);
		}
	}
	if ( out.length() == 0 ) {
		die "mail.invalid_address: Message.send requires at least one "
			_ "envelope recipient";
	}
	return out;
}

function _mail_send_headers ( head ) {
	let out := new PairList();
	for ( let pair in head.to_PairList().to_Array() ) {
		if ( lc(pair.key) ne "bcc" ) {
			out.add( pair.key, pair.value );
		}
	}
	return out;
}

class Head {
	let fields := null;

	method __build__ () {
		fields := _copy_pairlist(fields);
		for ( let pair in fields.to_Array() ) {
			_check_header_name(pair.key);
			_check_header_value(pair.value);
		}
	}

	method fields () {
		return fields.keys();
	}

	method raw ( String name, fallback := null ) {
		_check_header_name(name);
		let key := lc(name);
		for ( let pair in fields.to_Array() ) {
			if ( lc(pair.key) eq key ) {
				return pair.value;
			}
		}
		return fallback;
	}

	method raw_all ( String name ) {
		_check_header_name(name);
		let key := lc(name);
		let out := [];
		for ( let pair in fields.to_Array() ) {
			if ( lc(pair.key) eq key ) {
				out.push(pair.value);
			}
		}
		return out;
	}

	method decoded ( String name, fallback := null ) {
		let raw := self.raw( name, null );
		return fallback if raw == null;
		return _decode_rfc2047(raw);
	}

	method decoded_all ( String name ) {
		let out := [];
		for ( let value in self.raw_all(name) ) {
			out.push( _decode_rfc2047(value) );
		}
		return out;
	}

	method get ( String name, fallback := null ) {
		return self.decoded( name, fallback );
	}

	method get_all ( String name ) {
		return self.decoded_all(name);
	}

	method set ( String name, String value ) {
		self.remove(name);
		return self.add( name, value );
	}

	method add ( String name, String value ) {
		_check_header_name(name);
		_check_header_value(value);
		fields.add( name, value );
		return self;
	}

	method remove ( String name ) {
		_check_header_name(name);
		let key := lc(name);
		let kept := new PairList();
		for ( let pair in fields.to_Array() ) {
			if ( lc(pair.key) ne key ) {
				kept.add( pair.key, pair.value );
			}
		}
		fields := kept;
		return self;
	}

	method has ( String name ) {
		return not( self.raw( name, null ) == null );
	}

	method to_PairList () {
		return _copy_pairlist(fields);
	}

	method to_Iterator () {
		let items := fields.to_Array();
		return items.to_Iterator();
	}

	method content_type () {
		let value := self.decoded( "Content-Type", null );
		return value == null ? null : _header_main_value(value);
	}

	method content_transfer_encoding () {
		let value := self.decoded( "Content-Transfer-Encoding", null );
		return value == null ? null : lc( trim(value) );
	}

	method charset () {
		let value := self.decoded( "Content-Type", null );
		let got := value == null ? null : _header_parameter( value, "charset" );
		return got == null ? null : lc(got);
	}

	method boundary () {
		let value := self.decoded( "Content-Type", null );
		return value == null ? null : _header_parameter( value, "boundary" );
	}

	method message_id () {
		return self.decoded( "Message-ID", null );
	}

	method date () {
		return self.decoded( "Date", null );
	}

	method from () {
		return _parse_address_header( self.decoded( "From", null ) );
	}

	method to () {
		return _parse_address_header( self.decoded( "To", null ) );
	}

	method cc () {
		return _parse_address_header( self.decoded( "Cc", null ) );
	}

	method bcc () {
		return _parse_address_header( self.decoded( "Bcc", null ) );
	}

	method subject () {
		return self.decoded( "Subject", null );
	}
}

class _BodyBase {
	let kind := "bytes";
	let _bytes := null;
	let _parts := null;
	let _nested := null;
	let content_type := null;
	let transfer_encoding := null;
	let charset := null;
	let boundary := null;
	let _owner_message but weak;

	method __build__ () {
		_bytes := to_binary("") if _bytes == null;
		_parts := [] if _parts == null;
		self._refresh_links();
	}

	method _refresh_links () {
		if ( kind eq "multipart" ) {
			for ( let part in _parts ) {
				part._set_container(self);
			}
		}
		else if ( kind eq "nested" and not( _nested == null ) ) {
			_nested._set_container(self);
		}
		return self;
	}

	method _set_owner_message ( owner ) {
		_owner_message := owner but weak;
		return self;
	}

	method owner_message () {
		return _owner_message;
	}

	method is_multipart () {
		return kind eq "multipart";
	}

	method is_nested () {
		return kind eq "nested";
	}

	method bytes () {
		if ( kind ne "bytes" ) {
			die "mail.body: only leaf bodies expose bytes";
		}
		return _bytes;
	}

	method parts () {
		return _copy_array(_parts);
	}

	method part ( Number index ) {
		if ( kind ne "multipart" ) {
			die "mail.body: only multipart bodies expose parts";
		}
		return _parts[index];
	}

	method count () {
		if ( kind eq "multipart" ) {
			return _parts.length();
		}
		return kind eq "nested" ? 1 : 0;
	}

	method nested () {
		return kind eq "nested" ? _nested : null;
	}

	method content_type () {
		return content_type;
	}

	method transfer_encoding () {
		return transfer_encoding == null ? "identity" : lc(transfer_encoding);
	}

	method decoded () {
		if ( kind ne "bytes" ) {
			die "mail.body: multipart/nested decoding is planned for Phase 10";
		}

		let enc := self.transfer_encoding();
		if ( enc eq "base64" ) {
			return _base64_decode( to_string(_bytes) );
		}
		if ( enc eq "quoted-printable" ) {
			return _qp_decode( to_string(_bytes) );
		}
		if ( enc in [ "identity", "7bit", "8bit", "binary" ] ) {
			return _bytes;
		}

		die \`mail.body: unsupported transfer encoding '\${enc}'\`;
	}

	method encoded () {
		if ( kind ne "bytes" ) {
			die "mail.body: multipart/nested encoding is planned for Phase 10";
		}
		return _bytes;
	}

	method to_Dict () {
		if ( kind eq "multipart" ) {
			return {
				kind: kind,
				content_type: content_type,
				transfer_encoding: transfer_encoding,
				charset: charset,
				boundary: boundary,
				parts: _parts.map( fn part -> part.to_Dict() ),
			};
		}
		if ( kind eq "nested" ) {
			return {
				kind: kind,
				content_type: content_type,
				transfer_encoding: transfer_encoding,
				charset: charset,
				message: _nested == null ? null : _nested.to_Dict(),
			};
		}
		return {
			kind: kind,
			content_type: content_type,
			transfer_encoding: transfer_encoding,
			charset: charset,
			bytes: _bytes,
		};
	}

}

class Body extends _BodyBase {
	static method bytes ( BinaryString raw, ... PairList options ) {
		let opts := _body_options(options);
		return new Body(
			kind: "bytes",
			_bytes: raw,
			content_type: opts{content_type},
			transfer_encoding: opts{transfer_encoding},
			charset: opts{charset},
		);
	}

	static method multipart (
		Array parts,
		String boundary,
		... PairList options
	) {
		_assert_no_crlf( boundary, "body" );
		let opts := _body_options(options);
		let ctype := opts{content_type} == null
			? "multipart/mixed"
			: opts{content_type};
		let body := new Body(
			kind: "multipart",
			_parts: _copy_array(parts),
			content_type: ctype,
			transfer_encoding: opts{transfer_encoding},
			charset: opts{charset},
			boundary: boundary,
		);
		return body._refresh_links();
	}

	static method nested ( message, ... PairList options ) {
		let opts := _body_options(options);
		let ctype := opts{content_type} == null
			? "message/rfc822"
			: opts{content_type};
		let body := new Body(
			kind: "nested",
			_nested: message,
			content_type: ctype,
			transfer_encoding: opts{transfer_encoding},
			charset: opts{charset},
		);
		return body._refresh_links();
	}
}

class Message {
	let head := null;
	let body := null;
	let _container but weak;

	method __build__ () {
		head := new Head() if head == null;
		body := Body.bytes( to_binary("") ) if body == null;
		body._set_owner_message(self);
	}

	method _set_container ( container ) {
		_container := container but weak;
		return self;
	}

	method head () {
		return head;
	}

	method body () {
		return body;
	}

	method header ( String name, fallback := null ) {
		return head.get( name, fallback );
	}

	method headers ( String name ) {
		return head.get_all(name);
	}

	method set_header ( String name, String value ) {
		head.set( name, value );
		return self;
	}

	method add_header ( String name, String value ) {
		head.add( name, value );
		return self;
	}

	method remove_header ( String name ) {
		head.remove(name);
		return self;
	}

	method subject () {
		return head.subject();
	}

	method from () {
		return head.from();
	}

	method to () {
		return head.to();
	}

	method cc () {
		return head.cc();
	}

	method bcc () {
		return head.bcc();
	}

	method date () {
		return head.date();
	}

	method message_id () {
		return head.message_id();
	}

	method is_part () {
		return not( _container == null );
	}

	method container () {
		return _container;
	}

	method toplevel () {
		let current := self;
		while ( not( current.container() == null ) ) {
			let owner := current.container().owner_message();
			return current if owner == null;
			current := owner;
		}
		return current;
	}

	method send ( mailer, ... PairList options ) {
		if ( mailer == null or not( mailer can "send" ) ) {
			die "mail.unsupported: Message.send requires a compatible mailer";
		}

		let opts := _mail_send_options(options);
		let envelope_from := opts{envelope_from} == null
			? _mail_send_envelope_from(head)
			: opts{envelope_from};
		let envelope_to := opts{envelope_to} == null
			? _mail_send_envelope_to(head)
			: opts{envelope_to};
		let headers := _mail_send_headers(head);
		let send_body := _mail_send_serialize_body(self);

		return mailer.send(
			envelope_from,
			envelope_to,
			headers,
			send_body,
			opts{send_options},
		);
	}

	method to_Dict () {
		return {
			head: head.to_PairList(),
			body: body.to_Dict(),
			is_part: self.is_part(),
		};
	}
}

class Parser {
	let strict := false;
	let max_header_bytes := 65536;
	let max_depth := 32;
	let decode_transfer := false;
	let _warnings := [];

	method __build__ () {
		if ( not( strict instanceof Boolean ) ) {
			die "mail.parse: strict expects Boolean";
		}
		if ( not( max_header_bytes instanceof Number ) or max_header_bytes < 0 ) {
			die "mail.parse: max_header_bytes expects non-negative Number";
		}
		if ( not( max_depth instanceof Number ) or max_depth < 0 ) {
			die "mail.parse: max_depth expects non-negative Number";
		}
		if ( not( decode_transfer instanceof Boolean ) ) {
			die "mail.parse: decode_transfer expects Boolean";
		}

		_warnings := [];
	}

	method warnings () {
		return _copy_array(_warnings);
	}

	method _warn ( String message ) {
		_warnings.push( "mail.parse: " _ message );
		return self;
	}

	method _fail ( String message ) {
		die "mail.parse: " _ message;
	}

	method _enforce_depth ( Number depth ) {
		if ( depth > max_depth ) {
			self._fail("max_depth exceeded");
		}
	}

	method _parse_head ( Array header_bytes ) {
		let fields := _parse_mail_header_fields(header_bytes);
		return new Head( fields: fields );
	}

	method _header_malformed_message ( BinaryString raw ) {
		self._warn("malformed header section; preserving original bytes");
		return new Message(
			head: new Head(),
			body: Body.bytes(raw),
		);
	}

	method _safe_content_type ( Head head ) {
		try {
			return head.content_type();
		}
		catch {
			if ( strict ) {
				self._fail("malformed Content-Type header");
			}
			self._warn("malformed Content-Type header");
			return null;
		}
	}

	method _safe_charset ( Head head ) {
		try {
			return head.charset();
		}
		catch {
			if ( strict ) {
				self._fail("malformed Content-Type charset");
			}
			self._warn("malformed Content-Type charset");
			return null;
		}
	}

	method _safe_boundary ( Head head ) {
		try {
			return head.boundary();
		}
		catch {
			if ( strict ) {
				self._fail("malformed multipart boundary");
			}
			self._warn("malformed multipart boundary");
			return null;
		}
	}

	method _safe_transfer_encoding ( Head head ) {
		try {
			return head.content_transfer_encoding();
		}
		catch {
			if ( strict ) {
				self._fail("malformed Content-Transfer-Encoding header");
			}
			self._warn("malformed Content-Transfer-Encoding header");
			return null;
		}
	}

	method _leaf_body (
		BinaryString raw,
		content_type,
		transfer_encoding,
		charset
	) {
		return Body.bytes(
			raw,
			content_type: content_type,
			transfer_encoding: transfer_encoding,
			charset: charset,
		);
	}

	method _multipart_body (
		BinaryString raw,
		Array body_bytes,
		String content_type,
		transfer_encoding,
		charset,
		boundary,
		Number depth
	) {
		if ( boundary == null or boundary eq "" or _has_crlf(boundary) ) {
			if ( strict ) {
				self._fail("multipart body missing boundary");
			}
			self._warn("multipart body missing boundary; using leaf body");
			return self._leaf_body( raw, content_type, transfer_encoding, charset );
		}

		let scanned := _scan_multipart_parts( body_bytes, boundary );
		if ( not scanned{opened} ) {
			if ( strict ) {
				self._fail("multipart boundary open delimiter not found");
			}
			self._warn("multipart boundary open delimiter not found; using leaf body");
			return self._leaf_body( raw, content_type, transfer_encoding, charset );
		}

		if ( scanned{preamble_size} > 0 ) {
			self._warn("multipart preamble ignored");
		}
		if ( scanned{epilogue_size} > 0 ) {
			self._warn("multipart epilogue ignored");
		}
		if ( not scanned{closed} ) {
			if ( strict ) {
				self._fail("multipart boundary close delimiter not found");
			}
			self._warn("multipart boundary close delimiter not found");
		}

		let messages := [];
		for ( let part_bytes in scanned{parts} ) {
			messages.push(
				self._parse_message( _bytes_to_binary(part_bytes), depth + 1 ),
			);
		}

		return Body.multipart(
			messages,
			boundary,
			content_type: content_type,
			transfer_encoding: transfer_encoding,
			charset: charset,
		);
	}

	method _nested_body (
		BinaryString raw,
		String content_type,
		transfer_encoding,
		charset,
		Number depth
	) {
		if ( not _is_identity_transfer_encoding(transfer_encoding) ) {
			if ( strict ) {
				self._fail("encoded message/rfc822 bodies are not supported");
			}
			self._warn("encoded message/rfc822 body kept as leaf body");
			return self._leaf_body( raw, content_type, transfer_encoding, charset );
		}

		return Body.nested(
			self._parse_message( raw, depth + 1 ),
			content_type: content_type,
			transfer_encoding: transfer_encoding,
			charset: charset,
		);
	}

	method _parse_message ( BinaryString raw, Number depth ) {
		self._enforce_depth(depth);

		let bytes := _binary_to_bytes(raw);
		let split := _split_message_bytes(bytes);
		if ( split{header_size} > max_header_bytes ) {
			self._fail("max_header_bytes exceeded");
		}

		let head;
		if ( strict ) {
			head := try {
				self._parse_head( split{header_bytes} );
			} catch {
				self._fail("malformed header section");
			};
		}
		else {
			let fallback := null;
			head := try {
				self._parse_head( split{header_bytes} );
			} catch {
				fallback := self._header_malformed_message(raw);
				null;
			};
			return fallback if not( fallback == null );
		}

		let raw_body := _bytes_to_binary( split{body_bytes} );
		let content_type := self._safe_content_type(head);
		let charset := self._safe_charset(head);
		let boundary := self._safe_boundary(head);
		let transfer_encoding := self._safe_transfer_encoding(head);
		let body;

		if ( not( content_type == null ) and index( content_type, "multipart/" ) == 0 ) {
			body := self._multipart_body(
				raw_body,
				split{body_bytes},
				content_type,
				transfer_encoding,
				charset,
				boundary,
				depth,
			);
		}
		else if ( content_type eq "message/rfc822" ) {
			body := self._nested_body(
				raw_body,
				content_type,
				transfer_encoding,
				charset,
				depth,
			);
		}
		else {
			body := self._leaf_body(
				raw_body,
				content_type,
				transfer_encoding,
				charset,
			);
		}

		return new Message( head: head, body: body );
	}

	method parse ( BinaryString bytes ) {
		return self._parse_message( bytes, 0 );
	}
}

function _mail_serialize_fail ( String message ) {
	die "mail.serialize: " _ message;
}

function _mail_serialize_append_text (
	Array out,
	String text,
	String context
) {
	let i := 0;
	let n := length text;

	while ( i < n ) {
		let cp := ord( substr( text, i, 1 ) );
		if ( cp > 255 ) {
			_mail_serialize_fail(
				context _ " contains a character outside byte range",
			);
		}
		out.push(cp);
		i++;
	}

	return out;
}

function _mail_serialize_append_binary ( Array out, BinaryString bytes ) {
	for ( let b in _binary_to_bytes(bytes) ) {
		out.push(b);
	}
	return out;
}

function _mail_serialize_header_words ( String value ) {
	let words := [];
	let i := 0;
	let n := length value;

	while ( i < n ) {
		i := _skip_ws( value, i );
		last if i >= n;

		let start := i;
		while ( i < n and not _is_ws( substr( value, i, 1 ) ) ) {
			i++;
		}
		words.push( substr( value, start, i - start ) );
	}

	return words;
}

function _mail_serialize_folded_header_lines (
	String name,
	String value,
	Number line_length
) {
	let unfolded := name _ ": " _ value;
	return [ unfolded ] if length unfolded <= line_length;

	let words := _mail_serialize_header_words(value);
	return [ unfolded ] if words.length() <= 1;

	let lines := [];
	let first_prefix := name _ ": ";
	let line := first_prefix;

	for ( let word in words ) {
		let separator := ( line eq first_prefix or line eq "\\t" )
			? ""
			: " ";
		let candidate := line _ separator _ word;

		if ( length candidate <= line_length
			or line eq first_prefix
			or line eq "\\t" ) {
			line := candidate;
			next;
		}

		lines.push(line);
		line := "\\t" _ word;
	}

	lines.push(line);
	return lines;
}

function _mail_serialize_quote_boundary ( String boundary ) {
	return _quote_string(boundary);
}

class Serializer {
	let newline := "\\r\\n";
	let fold_headers := true;
	let line_length := 78;
	let generate_boundary := false;
	let _boundary_counter := 0;

	method __build__ () {
		if ( not( newline instanceof String ) ) {
			self._fail("newline expects String");
		}
		if ( newline ne "\\r\\n" and newline ne "\\n" ) {
			self._fail("newline must be CRLF or LF");
		}
		if ( not( fold_headers instanceof Boolean ) ) {
			self._fail("fold_headers expects Boolean");
		}
		if ( not( line_length instanceof Number ) ) {
			self._fail("line_length expects Number");
		}
		if ( line_length < 1 ) {
			self._fail("line_length must be positive");
		}
		if ( not( generate_boundary instanceof Boolean ) ) {
			self._fail("generate_boundary expects Boolean");
		}
		if ( not( _boundary_counter instanceof Number ) or _boundary_counter < 0 ) {
			self._fail("_boundary_counter expects non-negative Number");
		}

		line_length := int(line_length);
		_boundary_counter := int(_boundary_counter);
	}

	method _fail ( String message ) {
		_mail_serialize_fail(message);
	}

	method _reject_method_options ( PairList options ) {
		let items := options.to_Array();
		if ( items.length() > 0 ) {
			self._fail(
				"unsupported method option '" _ items[0].key
					_ "'; use constructor named arguments",
			);
		}
	}

	method _validate_header_pair ( pair ) {
		if ( not( pair.key instanceof String ) or not _valid_header_name(pair.key) ) {
			self._fail("invalid header name");
		}
		if ( not( pair.value instanceof String ) ) {
			self._fail("header value expects String, got " _ typeof pair.value);
		}
		if ( _has_crlf(pair.value) ) {
			self._fail("header value must not contain CR or LF");
		}
	}

	method _append_line ( Array out, String line ) {
		_mail_serialize_append_text( out, line, "header line" );
		_mail_serialize_append_text( out, newline, "newline" );
	}

	method _append_header ( Array out, String name, String value ) {
		let lines := fold_headers
			? _mail_serialize_folded_header_lines(
				name,
				value,
				line_length,
			)
			: [ name _ ": " _ value ];

		for ( let line in lines ) {
			self._append_line( out, line );
		}
	}

	method _generated_boundary () {
		_boundary_counter++;
		return \`zuzu-boundary-\${_boundary_counter}\`;
	}

	method _validate_boundary ( String boundary ) {
		if ( boundary eq "" ) {
			self._fail("multipart body missing boundary");
		}
		if ( _has_crlf(boundary) ) {
			self._fail("multipart boundary must not contain CR or LF");
		}
		return boundary;
	}

	method _header_boundary ( Head head ) {
		let value := head.raw( "Content-Type", null );
		return null if value == null;

		let boundary := null;
		try {
			boundary := _header_parameter( value, "boundary" );
		}
		catch {
			boundary := null;
		}

		return boundary;
	}

	method _body_content_type ( body ) {
		let data := body.to_Dict();
		let content_type := data{content_type};
		return "multipart/mixed" if content_type == null;
		if ( not( content_type instanceof String ) ) {
			self._fail("multipart content_type expects String");
		}
		return content_type;
	}

	method _content_type_with_boundary (
		body,
		String value,
		String boundary
	) {
		let existing := null;
		let main := null;
		try {
			existing := _header_parameter( value, "boundary" );
			main := _header_main_value(value);
		}
		catch {
			existing := null;
			main := null;
		}

		let quoted := _mail_serialize_quote_boundary(boundary);
		if ( not( existing == null ) and existing eq "" ) {
			return self._body_content_type(body) _ "; boundary=" _ quoted;
		}
		if ( existing == null ) {
			if ( main == null or index( main, "multipart/" ) != 0 ) {
				return self._body_content_type(body) _ "; boundary=" _ quoted;
			}
			return value _ "; boundary=" _ quoted;
		}

		return value;
	}

	method _generated_content_type ( body, String boundary ) {
		return self._body_content_type(body)
			_ "; boundary="
			_ _mail_serialize_quote_boundary(boundary);
	}

	method _full_context ( Message message ) {
		let body := message.body();
		let data := body.to_Dict();
		if ( data{kind} ne "multipart" ) {
			return { multipart: false, boundary: null };
		}

		let boundary := data{boundary};
		if ( not( boundary == null ) and not( boundary instanceof String ) ) {
			self._fail("multipart boundary expects String");
		}
		if ( boundary == null or boundary eq "" ) {
			boundary := self._header_boundary( message.head() );
		}
		if ( not( boundary == null ) and not( boundary instanceof String ) ) {
			self._fail("multipart boundary expects String");
		}
		if ( boundary == null or boundary eq "" ) {
			if ( generate_boundary ) {
				boundary := self._generated_boundary();
			}
			else {
				return { multipart: true, boundary: null };
			}
		}

		return {
			multipart: true,
			boundary: self._validate_boundary(boundary),
		};
	}

	method _multipart_boundary ( body, boundary_override := null ) {
		if ( not( boundary_override == null ) ) {
			return self._validate_boundary(boundary_override);
		}

		let data := body.to_Dict();
		let boundary := data{boundary};

		if ( boundary == null or boundary eq "" ) {
			if ( generate_boundary ) {
				return self._generated_boundary();
			}
			self._fail("multipart body missing boundary");
		}
		if ( not( boundary instanceof String ) ) {
			self._fail("multipart boundary expects String");
		}
		return self._validate_boundary(boundary);
	}

	method _serialize_body ( body, boundary_override := null ) {
		let data := body.to_Dict();
		let kind := data{kind};

		if ( kind eq "bytes" ) {
			return body.encoded();
		}
		if ( kind eq "nested" ) {
			let nested := body.nested();
			if ( nested == null ) {
				self._fail("message/rfc822 body missing nested message");
			}
			return self.serialize(nested);
		}
		if ( kind ne "multipart" ) {
			self._fail("unsupported body kind '" _ kind _ "'");
		}

		let boundary := self._multipart_boundary( body, boundary_override );
		let out := [];

		for ( let part in body.parts() ) {
			_mail_serialize_append_text( out, "--" _ boundary, "boundary" );
			_mail_serialize_append_text( out, newline, "newline" );
			_mail_serialize_append_binary( out, self.serialize(part) );
			_mail_serialize_append_text( out, newline, "newline" );
		}

		_mail_serialize_append_text( out, "--" _ boundary _ "--", "boundary" );
		_mail_serialize_append_text( out, newline, "newline" );

		return _bytes_to_binary(out);
	}

	method serialize_body ( Message message, ... PairList options ) {
		self._reject_method_options(options);
		return self._serialize_body( message.body() );
	}

	method serialize ( Message message, ... PairList options ) {
		self._reject_method_options(options);
		let out := [];
		let context := self._full_context(message);
		let saw_content_type := false;

		for ( let pair in message.head().to_PairList().to_Array() ) {
			self._validate_header_pair(pair);
			let value := pair.value;
			if ( context{multipart}
				and lc(pair.key) eq "content-type"
				and not saw_content_type
				and not( context{boundary} == null ) ) {
				value := self._content_type_with_boundary(
					message.body(),
					value,
					context{boundary},
				);
				saw_content_type := true;
			}
			else if ( lc(pair.key) eq "content-type" ) {
				saw_content_type := true;
			}
			self._append_header( out, pair.key, value );
		}

		if ( context{multipart}
			and not saw_content_type
			and not( context{boundary} == null ) ) {
			self._append_header(
				out,
				"Content-Type",
				self._generated_content_type(
					message.body(),
					context{boundary},
				),
			);
		}

		_mail_serialize_append_text( out, newline, "newline" );
		_mail_serialize_append_binary(
			out,
			self._serialize_body( message.body(), context{boundary} ),
		);

		return _bytes_to_binary(out);
	}
}

function _mail_send_serialize_body ( message ) {
	return ( new Serializer() ).serialize_body(message);
}
`;
        virtualFiles["/modules/std/data/xml/escape.zzm"] = `=encoding utf8

=head1 NAME

std/data/xml/escape - XML entity escaping helpers.

=head1 SYNOPSIS

  from std/data/xml/escape import
    escape_xml, unescape_xml;

  let escaped := escape_xml(
    "<tea attr=\\"hot\\">& 'biscuits'</tea>"
  );
  let text := unescape_xml(
    "&lt;tea&gt;&#x41;&#65;&lt;/tea&gt;"
  );

=head1 IMPLEMENTATION SUPPORT

This module is supported by all implementations of ZuzuScript.

=head1 DESCRIPTION

This module provides lightweight XML entity
escaping and unescaping helpers.

=head1 EXPORTS

=head2 Functions

=over

=item C<< escape_xml(value) >>

Parameters: C<value> is any value. Returns: C<String>. Escapes XML
special characters C<&>, C<< < >>, C<< > >>, C<">, and C<'>.

=item C<< unescape_xml(value) >>

Parameters: C<value> is any value. Returns: C<String>. Unescapes XML
named entities C<&lt;>, C<&gt;>, C<&quot;>, C<&apos;>, and C<&amp;>.

Also decodes numeric entities in decimal and hexadecimal
forms, such as C<&#65;> and C<&#x41;>.

=back

=head1 COPYRIGHT AND LICENCE

B<< std/data/xml/escape >> is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under
the terms of either the Artistic License 1.0 or the GNU General Public
License version 2.

=cut

from std/string import substr, replace, sprint, index;

function escape_xml ( value ) {
	let out := value \u2261 null ? "" : "" _ value;
	out := replace( out, "&", "&amp;", "g" );
	out := replace( out, "<", "&lt;", "g" );
	out := replace( out, ">", "&gt;", "g" );
	out := replace( out, "\\"", "&quot;", "g" );
	out := replace( out, "'", "&apos;", "g" );
	return out;
}

function _hex_to_number ( String digits ) {
	let out := 0;
	let i := 0;
	let n := length digits;

	while ( i < n ) {
		let ch := substr( digits, i, 1 );
		let val := 0;

		if ( ch ~ /[0-9]/ ) {
			val := 0 + ch;
		}
		else {
			let lower := lc(ch);
			val := 10 + index( "abcdef", lower );
		}

		out := out * 16 + val;
		i++;
	}

	return out;
}

function _decode_numeric_xml_entities ( text ) {
	let out := "";
	let i := 0;
	let n := length text;

	while ( i < n ) {
		let ch := substr( text, i, 1 );
		if ( ch \u2261 "&" and i + 2 < n and substr( text, i, 2 ) \u2261 "&#" ) {
			let j := i + 2;
			let hex := false;

			if ( j < n ) {
				let mark := substr( text, j, 1 );
				if ( mark \u2261 "x" or mark \u2261 "X" ) {
					hex := true;
					j++;
				}
			}

			let digits := "";
			while ( j < n ) {
				let d := substr( text, j, 1 );
				last if d \u2261 ";";

				if ( hex ) {
					last unless d ~ /[0-9A-Fa-f]/;
				}
				else {
					last unless d ~ /[0-9]/;
				}

				digits _= d;
				j++;
			}

			if ( digits \u2262 "" and j < n and substr( text, j, 1 ) \u2261 ";" ) {
				let code := hex
					? _hex_to_number( digits )
					: 0 + digits;
				out _= sprint( "%c", code );
				i := j + 1;
				next;
			}
		}

		out _= ch;
		i++;
	}

	return out;
}

function unescape_xml ( value ) {
	let out := value \u2261 null ? "" : "" _ value;
	out := _decode_numeric_xml_entities( out );
	out := replace( out, "&lt;", "<", "g" );
	out := replace( out, "&gt;", ">", "g" );
	out := replace( out, "&quot;", "\\"", "g" );
	out := replace( out, "&apos;", "'", "g" );
	out := replace( out, "&amp;", "&", "g" );
	return out;
}
`;
        virtualFiles["/modules/std/path/simple.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/path/simple - Tiny JSONPath/XPath-like traversal helper.\n\n=head1 SYNOPSIS\n\n  from std/path/simple import SimplePath;\n\n  let data := {\n    store: {\n      books: [\n        { author: "Nigel Rees" },\n        { author: "J. R. R. Tolkien" },\n      ],\n    },\n  };\n\n  let p := new SimplePath( path: "store.books[*].author" );\n  for ( let name in p.query(data) ) {\n    say name;\n  }\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nC<SimplePath> implements only a tiny subset of path traversal:\n\n=over\n\n=item * C<.something>\n\nDict/PairList lookup by key.\n\n=item * C<.*>\n\nDict/PairList wildcard that yields all values.\n\n=item * C<[1]>\n\nArray lookup by numeric index.\n\n=item * C<[-1]>\n\nNegative indexes count from the end of arrays.\n\n=item * C<[*]>\n\nArray/Bag/Set wildcard that yields all items.\n\n=back\n\nNo other syntax is supported.\n\nThe public API intentionally mirrors key C<std/path/z> methods:\nC<get>, C<select>, C<query>, C<first>, C<exists>,\nC<expression>, C<assign_first>, C<assign_all>, C<assign_maybe>,\nC<ref_first>, C<ref_all>, and C<ref_maybe>.\n\nThe path operators C<@>, C<@@>, and C<@?> can be set to use this module\nin a lexical scope:\n\n  from std/path/simple import SimplePath;\n  SimplePath.use();\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<< SimplePath({ path: String }) >>\n\nConstructs a simple path selector. Returns: C<SimplePath>.\n\n=over\n\n=item C<< SimplePath.use() >>\n\nParameters: none. Returns: C<null>. Makes this path class the lexical\nimplementation for C<@>, C<@@>, and C<@?>.\n\n=item C<< path.expression() >>\n\nParameters: none. Returns: C<String>. Returns the original path\nexpression.\n\n=item C<< path.get(value) >>, C<< path.select(value) >>, C<< path.query(value) >>\n\nParameters: C<value> is the query root. Returns: C<Array>. Evaluates the\npath and returns selected values.\n\n=item C<< path.first(value, fallback) >>\n\nParameters: C<value> is the query root and C<fallback> is returned when\nthere is no match. Returns: value. Returns the first selected value.\n\n=item C<< path.exists(value) >>\n\nParameters: C<value> is the query root. Returns: C<Boolean>. Returns\ntrue when the path selects at least one value.\n\n=item C<< path.assign_first(target, value, op := ":=", weak := false) >>\n\nParameters: C<target> is the query root, C<value> is the assignment\nvalue, C<op> is an assignment operator, and C<weak> is accepted for path\nAPI compatibility. Returns: value. Updates the first selected location.\n\n=item C<< path.assign_all(target, value, op := ":=", weak := false) >>\n\nParameters: same as C<assign_first>. Returns: value. Updates every\nselected location.\n\n=item C<< path.assign_maybe(target, value, op := ":=", weak := false) >>\n\nParameters: same as C<assign_first>. Returns: C<Boolean>. Updates the\nfirst selected location when one exists.\n\n=item C<< path.ref_first(target) >>\n\nParameters: C<target> is the query root. Returns: C<Function>. Returns a\nreference-like getter/setter for the first selected location.\n\n=item C<< path.ref_all(target) >>\n\nParameters: C<target> is the query root. Returns: C<Array>. Returns\nreference-like getter/setters for all selected locations.\n\n=item C<< path.ref_maybe(target) >>\n\nParameters: C<target> is the query root. Returns: C<Function> or\nC<null>. Returns a reference-like getter/setter for the first selected\nlocation when one exists.\n\n=back\n\n=back\n\n=cut\n\nfrom std/string import substr;\n\n\nclass SimplePath {\n	let String path;\n	let Array _steps := [];\n\n	static method use () {\n		from std/internals import setupperprop;\n		setupperprop( 1, "paths", self );\n	}\n\n	method __build__ () {\n		_steps := self._parse(path);\n	}\n\n	method expression () {\n		return path;\n	}\n\n	method _parse ( String raw ) {\n		let text := raw;\n		let steps := [];\n		let i := 0;\n\n		while ( i < length text ) {\n			let ch := substr( text, i, 1 );\n			if ( ch \u2261 "." ) {\n				i++;\n				die "SimplePath parse error: expected name or * after \'.\'"\n					if i >= length text;\n				let after_dot := substr( text, i, 1 );\n				if ( after_dot \u2261 "*" ) {\n					steps.push( { kind: "dict_wildcard" } );\n					i++;\n					next;\n				}\n				let start := i;\n				while ( i < length text ) {\n					let c := substr( text, i, 1 );\n					last if c \u2261 "." or c \u2261 "[" or c \u2261 "]";\n					i++;\n				}\n				let key := substr( text, start, i - start );\n				die "SimplePath parse error: empty key"\n					if key \u2261 "";\n				steps.push( { kind: "key", value: key } );\n				next;\n			}\n\n			if ( ch \u2261 "[" ) {\n				let close := i + 1;\n				while ( close < length text and substr( text, close, 1 ) \u2262 "]" ) {\n					close++;\n				}\n				die "SimplePath parse error: missing closing \']\'"\n					if close >= length text;\n				let inner := substr( text, i + 1, close - i - 1 );\n				if ( inner \u2261 "*" ) {\n					steps.push( { kind: "list_wildcard" } );\n				}\n				else if ( inner ~ /^-?[0-9]+$/ ) {\n					steps.push( { kind: "index", value: int(inner) } );\n				}\n				else {\n					die `SimplePath parse error: unsupported bracket token \'[${inner}]\'`;\n				}\n				i := close + 1;\n				next;\n			}\n\n			let start := i;\n			while ( i < length text ) {\n				let c := substr( text, i, 1 );\n				last if c \u2261 "." or c \u2261 "[" or c \u2261 "]";\n				i++;\n			}\n			let key := substr( text, start, i - start );\n			die `SimplePath parse error: unexpected token \'${ch}\'`\n				if key \u2261 "";\n			steps.push( { kind: "key", value: key } );\n		}\n\n		return steps;\n	}\n\n	method _node ( value, parent, key ) {\n		return {\n			value: value,\n			parent: parent,\n			key: key,\n		};\n	}\n\n	method _evaluate_nodes ( value ) {\n		let current := [ self._node( value, null, null ) ];\n\n		for ( let step in _steps ) {\n			let next_nodes := [];\n\n			for ( let node in current ) {\n				let v := node{value};\n\n				if ( step{kind} \u2261 "key" ) {\n					if ( v instanceof Dict and v.exists( step{value} ) ) {\n						next_nodes.push( self._node( v.get( step{value} ), node, step{value} ) );\n					}\n					else if ( v instanceof PairList ) {\n						for ( let item in v.get_all( step{value} ) ) {\n							next_nodes.push( self._node( item, node, step{value} ) );\n						}\n					}\n					next;\n				}\n\n				if ( step{kind} \u2261 "dict_wildcard" ) {\n					if ( v instanceof Dict ) {\n						for ( let k in v.keys() ) {\n							next_nodes.push( self._node( v.get(k), node, k ) );\n						}\n					}\n					else if ( v instanceof PairList ) {\n						for ( let pair in v.to_Array() ) {\n							next_nodes.push( self._node( pair.value, node, pair.key ) );\n						}\n					}\n					next;\n				}\n\n				if ( step{kind} \u2261 "index" ) {\n					if ( v instanceof Array ) {\n						let idx := step{value};\n						if ( idx < 0 ) {\n							idx := v.length() + idx;\n						}\n						if ( idx >= 0 and idx < v.length() ) {\n							next_nodes.push( self._node( v[idx], node, idx ) );\n						}\n					}\n					next;\n				}\n\n				if ( step{kind} \u2261 "list_wildcard" ) {\n					if ( v instanceof Array ) {\n						let i := 0;\n						while ( i < v.length() ) {\n							next_nodes.push( self._node( v[i], node, i ) );\n							i++;\n						}\n					}\n					else if ( v instanceof Bag or v instanceof Set ) {\n						for ( let item in v.to_Array() ) {\n							next_nodes.push( self._node( item, node, "*" ) );\n						}\n					}\n					next;\n				}\n			}\n\n			current := next_nodes;\n		}\n\n		return current;\n	}\n\n	method _evaluate ( value ) {\n		return self._evaluate_nodes(value).map( fn n -> n{value} );\n	}\n\n	method get ( value ) {\n		return self._evaluate(value);\n	}\n\n	method select ( value ) {\n		return self._evaluate(value);\n	}\n\n	method query ( value ) {\n		return self._evaluate(value);\n	}\n\n	method first ( value, fallback ) {\n		let out := self._evaluate(value);\n		return out.length() = 0 ? fallback : out[0];\n	}\n\n	method exists ( value ) {\n		return self._evaluate(value).length() > 0;\n	}\n\n	method _assign_node ( Dict node, value ) {\n		let parent := node{parent};\n		die "SimplePath assignment target has no parent node"\n			if parent \u2261 null;\n\n		let container := parent{value};\n		let key := node{key};\n\n		if ( container instanceof Array ) {\n			die "SimplePath assignment expects numeric array index"\n				if not( key instanceof Number );\n			container[key] := value;\n			return value;\n		}\n\n		if ( container instanceof Dict ) {\n			die "SimplePath assignment expects string dict key"\n				if not( key instanceof String );\n			container{(key)} := value;\n			return value;\n		}\n\n		if ( container instanceof PairList ) {\n			die "SimplePath assignment expects string pairlist key"\n				if not( key instanceof String );\n			container.set( key, value );\n			return value;\n		}\n\n		die `SimplePath assignment target container \'${typeof container}\' is not assignable`;\n	}\n\n	method _ref_for_node ( Dict node ) {\n		let parent := node{parent};\n		die "SimplePath assignment target has no parent node"\n			if parent \u2261 null;\n\n		let container := parent{value};\n		let key := node{key};\n\n		if ( container instanceof Array ) {\n			die "SimplePath assignment expects numeric array index"\n				if not( key instanceof Number );\n			return \\ container[key];\n		}\n\n		if ( container instanceof Dict ) {\n			die "SimplePath assignment expects string dict key"\n				if not( key instanceof String );\n			return \\ container{(key)};\n		}\n\n		if ( container instanceof PairList ) {\n			die "SimplePath assignment expects string pairlist key"\n				if not( key instanceof String );\n			return \\ container{(key)};\n		}\n\n		die `SimplePath assignment target container \'${typeof container}\' is not assignable`;\n	}\n\n	method _apply_assignment_ref ( ref, value, op := ":=", weak := false ) {\n		die "SimplePath weak assignment is not supported"\n			if weak;\n\n		if ( op \u2261 ":=" ) {\n			return ref(value);\n		}\n\n		let current := ref();\n\n		if ( op \u2261 "+=" ) {\n			current += value;\n		}\n		else if ( op \u2261 "-=" ) {\n			current -= value;\n		}\n		else if ( op \u2261 "*=" or op \u2261 "\xD7=" ) {\n			current *= value;\n		}\n		else if ( op \u2261 "/=" or op \u2261 "\xF7=" ) {\n			current /= value;\n		}\n		else if ( op \u2261 "**=" ) {\n			current **= value;\n		}\n		else if ( op \u2261 "_=" ) {\n			current _= value;\n		}\n		else if ( op \u2261 "?:=" ) {\n			current ?:= value;\n		}\n		else if ( op \u2261 "~=" ) {\n			current ~= value[0] -> value[1](m);\n		}\n		else {\n			die `Unsupported path assignment operator \'${op}\'`;\n		}\n\n		ref(current);\n		return current;\n	}\n\n	method _assign_all_result ( value, op, last_result ) {\n		return op \u2261 "~=" ? last_result : value;\n	}\n\n	method assign_first ( target, value, op := ":=", weak := false ) {\n		let nodes := self._evaluate_nodes(target);\n		die "SimplePath assignment found no matches"\n			if nodes.length() \u2261 0;\n		return self._apply_assignment_ref(\n			self._ref_for_node( nodes[0] ),\n			value,\n			op,\n			weak,\n		);\n	}\n\n	method assign_all ( target, value, op := ":=", weak := false ) {\n		let nodes := self._evaluate_nodes(target);\n		if ( nodes.length() \u2261 0 ) {\n			return self._assign_all_result( value, op, value );\n		}\n\n		let i := 0;\n		let last_result := value;\n		while ( i < nodes.length() ) {\n			last_result := self._apply_assignment_ref(\n				self._ref_for_node( nodes[i] ),\n				value,\n				op,\n				weak,\n			);\n			i++;\n		}\n\n		return self._assign_all_result( value, op, last_result );\n	}\n\n	method assign_maybe ( target, value, op := ":=", weak := false ) {\n		let nodes := self._evaluate_nodes(target);\n		if ( nodes.length() \u2261 0 ) {\n			return false;\n		}\n\n		self._apply_assignment_ref(\n			self._ref_for_node( nodes[0] ),\n			value,\n			op,\n			weak,\n		);\n		return true;\n	}\n\n	method ref_first ( target ) {\n		let nodes := self._evaluate_nodes(target);\n		die "SimplePath assignment found no matches"\n			if nodes.length() \u2261 0;\n		return self._ref_for_node( nodes[0] );\n	}\n\n	method ref_all ( target ) {\n		let nodes := self._evaluate_nodes(target);\n		let out := [];\n		for ( let node in nodes ) {\n			out.push( self._ref_for_node(node) );\n		}\n		return out;\n	}\n\n	method ref_maybe ( target ) {\n		let nodes := self._evaluate_nodes(target);\n		return nodes.length() \u2261 0 ? null : self._ref_for_node( nodes[0] );\n	}\n}\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/path/simple >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n';
        virtualFiles["/modules/std/path/z.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/path/z - Pure Zuzu implementation of ZPath selectors.\n\n=head1 SYNOPSIS\n\n  from std/path/z import ZPath;\n  from std/time import Time;\n\n  let data := {\n    users: [\n      { name: "Ada", age: 32, updated: new Time() },\n      { name: "Bob", age: 27 },\n    ],\n  };\n\n  let names := query( data, "/users/*/name" );\n  let zp := new ZPath( path: "/users/#0/name" );\n  say( zp.first( data, "n/a" ) );\n  say( exists( data, "/users/#9/name" ) );\n  say( first( data, "/users/#0/updated/@year" ) );\n  say( zp.assign_first( data, "Adele" ) );\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nNative (pure-Zuzu) path traversal for structured values.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<< ZPath({ path: String, ast? }) >>\n\nConstructs a compiled ZPath selector. Returns: C<ZPath>.\n\n=over\n\n=item C<< ZPath.use() >>\n\nParameters: none. Returns: C<null>. Makes this path class the lexical\nimplementation for C<@>, C<@@>, and C<@?>.\n\n=item C<< path.get_evaluator() >>\n\nParameters: none. Returns: C<Evaluator>. Returns the evaluator used for\nthis path.\n\n=item C<< path.evaluate(raw, meta := {}) >>\n\nParameters: C<raw> is the query root and C<meta> is optional evaluation\nmetadata. Returns: C<Array>. Evaluates the path and returns selected\nnodes.\n\n=item C<< path.get(raw) >>, C<< path.select(raw) >>, C<< path.query(raw) >>\n\nParameters: C<raw> is the query root. Returns: C<Array>. Evaluates the\npath and returns selected primitive values.\n\n=item C<< path.first(raw, fallback?) >>\n\nParameters: C<raw> is the query root and C<fallback> is optional.\nReturns: value. Returns the first selected value or C<fallback>/C<null>.\n\n=item C<< path.exists(raw) >>\n\nParameters: C<raw> is the query root. Returns: C<Boolean>. Returns true\nwhen the path selects at least one value.\n\n=item C<< path.assign_first(raw, value, op := ":=", weak := false) >>\n\nParameters: C<raw> is the query root, C<value> is the assignment value,\nC<op> is an assignment operator, and C<weak> requests weak assignment.\nReturns: value. Updates the first selected node or throws if none match.\n\n=item C<< path.assign_all(raw, value, op := ":=", weak := false) >>\n\nParameters: same as C<assign_first>. Returns: value. Updates every\nselected node.\n\n=item C<< path.assign_maybe(raw, value, op := ":=", weak := false) >>\n\nParameters: same as C<assign_first>. Returns: C<Boolean>. Updates the\nfirst selected node when one exists.\n\n=item C<< path.ref_first(raw) >>\n\nParameters: C<raw> is the query root. Returns: C<Function>. Returns a\nreference-like getter/setter for the first selected node.\n\n=item C<< path.ref_all(raw) >>\n\nParameters: C<raw> is the query root. Returns: C<Array>. Returns\nreference-like getter/setters for all selected nodes.\n\n=item C<< path.ref_maybe(raw) >>\n\nParameters: C<raw> is the query root. Returns: C<Function> or C<null>.\nReturns a reference-like getter/setter for the first selected node when\none exists.\n\n=back\n\n=back\n\n=head1 USE WITH PATH OPERATORS\n\nThe path operators C<@>, C<@@>, and C<@?> can be set to use this module\nin a lexical scope.\n\n  from std/path/z import ZPath;\n\n  function find_usernames (data) {\n    ZPath.use();\n    return data @@ "/users/*/name";\n  }\n\nHowever, for repeatedly used paths it may be more efficient to compile the\npath once and use many times:\n\n  let _usernames_zpath;\n  function find_usernames (data) {\n    from std/path/z import ZPath;\n    _usernames_zpath ?:= new ZPath( path: "/users/*/name" );\n    return data @@ _usernames_zpath;\n  }\n\n=head1 SUPPORTED TYPES\n\n=over\n\n=item B<Null>, B<Boolean>, B<Number>, B<String>, B<BinaryString>, B<Regexp>\n\nTreated as terminal nodes. These objects cannot have child objects.\n\n=item B<Array>\n\nArray items can be indexed by number.\n\n=item B<Bag>, B<Set>\n\nItems cannot be indexed by number, but can be returned by "*".\n\n=item B<Dict>\n\nValues are named by their key.\n\n=item B<PairList>\n\nPairs can be indexed by number, named by their key, or use a combination of\nboth.\n\n  {{ foo: 11, bar: -1, foo: 22, foo: 33 }}\n\nC<< /#2 >> (0-based index) will retrieve C<< foo: 22 >>.\nC<< /foo >> will retrieve C<< foo: 11 >>, C<< foo: 22 >>, and C<< foo: 33 >>.\nC<< /foo#2 >> (0-based index on just values with key "foo") will retrieve C<< foo: 33 >>.\n\nNote that rather than just retrieving the value, a Pair object is retrieved.\nThe selected Pair exposes C<< @key >> and C<< @value >> attributes. Path\nassignment to a selected Pair, or to its C<< @value >> attribute, replaces\nthat pair entry\'s value while preserving pair order and duplicate keys.\n\n=item B<< Pair >>\n\nPair objects do not have child objects but do have C<< @key >> and\nC<< @value >> attributes.\n\n  let pairlist := {{ foo: 11, bar: -1, foo: 22, foo: 33 }};\n  say( first( pairlist, "/#2/@key" ) );     // "foo"\n  say( first( pairlist, "/#2/@value" ) );   // 22\n\n=item B<< Time >>\n\nTime is treated as a terminal node with attributes C<< @year >>,\nC<< @month >>, C<< @day >>, C<< @hour >>, C<< @min >>, and C<< @sec >>.\n\nSee C<< std/time >>.\n\n=item B<< Path >>\n\nPaths representing files are treated as terminal nodes with attributes\ncorresponding to the values from the C<stat> system call: C<< @dev >>,\nC<< @ino >>, C<< @mode >>, C<< @nlink >>, C<< @uid >>, C<< @gid >>,\nC<< @rdev >>, C<< @size >>, C<< @atime >>, C<< @mtime >>, C<< @ctime >>,\nC<< @blksize >>, and C<< @blocks >>.\n\nSee C<< std/io >>.\n\n=item B<< XMLDocument >>, B<< XMLNode >>, etc.\n\nAre treated roughly how the ZPath specification suggests.\n\n  /html/body/table/tbody/tr     // all rows in the tbody\n  /html/body/table/tbody/tr#0   // the first row in the tbody\n  /html/body/table/tbody/#0     // the child element in the tbody\n  /html/body/table[@id]         // all tables that have an id attribute\n\nSee C<< std/data/xml >>.\n\n=back\n\n=head1 SEE ALSO\n\nSpecification: L<https://zpath.me>.\n\nZPath specification: L<https://zpath.me>.\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/path/z >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/path/z/parser import Parser;\nfrom std/path/z/evaluate import Evaluator;\nfrom std/path/z/context import Ctx;\n\nlet _cache;\ndo {\n	from std/cache/lru try import Cache;\n	if ( Cache ) {\n		_cache := new Cache( capacity: 16 );\n	}\n};\n\nclass ZPath {\n	let String path;\n	let ast;\n	let ev;\n\n	static method use () {\n		from std/internals import setupperprop;\n		setupperprop( 1, "paths", self );\n	}\n\n	method __build__ () {\n		ev := self.get_evaluator;\n		const p := new Parser( allowed_operators: ev.operator_definitions() );\n		ast ?:= _cache\n			? _cache.get( path, fn x \u2192 p.parse_top_level_terms(x) )\n			: p.parse_top_level_terms(path);\n	}\n\n	method get_evaluator () {\n		return new Evaluator();\n	}\n\n	method evaluate ( raw, meta := {} ) {\n\n		meta.set( "level", 0 ) unless meta.defined( "level" );\n		const ctx := new Ctx(\n			root: raw,\n			nodeset: meta.get( "nodeset", null ),\n			parentset: meta.get( "parentset", null ),\n			meta: meta,\n		);\n\n		const short_circuit := ( meta.get( "want", "all" ) in [ "first", "exists" ] );\n\n		let results := [];\n		for ( let term in ast ) {\n			for ( let node in ev.eval_expr( term, ctx ) ) {\n				let next_node := ev.maybe_apply_action( node, ctx );\n				results.push(next_node);\n				return results if short_circuit;\n			}\n		}\n\n		return results;\n	}\n\n	method get ( raw ) {\n		return self.evaluate(raw).map( fn r \u2192 r.primitive_value );\n	}\n\n	method select ( raw ) {\n		return self.evaluate(raw).map( fn r \u2192 r.primitive_value );\n	}\n\n	method query ( raw ) {\n		return self.evaluate(raw).map( fn r \u2192 r.primitive_value );\n	}\n\n	method first ( raw, fallback? ) {\n		let got := self.evaluate( raw, { want: "first" } );\n		return got.empty ? fallback : got[0].primitive_value;\n	}\n\n	method exists ( raw ) {\n		let got := self.evaluate( raw, { want: "exists" } );\n		return not got.empty;\n	}\n\n	method _apply_assignment_ref ( ref, value, op := ":=", weak := false ) {\n		if ( op \u2261 ":=" ) {\n			return weak ? ref( value, true ) : ref(value);\n		}\n\n		let current := ref();\n\n		if ( op \u2261 "+=" ) {\n			current += value;\n		}\n		else if ( op \u2261 "-=" ) {\n			current -= value;\n		}\n		else if ( op \u2261 "*=" or op \u2261 "\xD7=" ) {\n			current *= value;\n		}\n		else if ( op \u2261 "/=" or op \u2261 "\xF7=" ) {\n			current /= value;\n		}\n		else if ( op \u2261 "**=" ) {\n			current **= value;\n		}\n		else if ( op \u2261 "_=" ) {\n			current _= value;\n		}\n		else if ( op \u2261 "?:=" ) {\n			current ?:= value;\n		}\n		else if ( op \u2261 "~=" ) {\n			current ~= value[0] -> value[1](m);\n		}\n		else {\n			die `Unsupported path assignment operator \'${op}\'`;\n		}\n\n		ref(current);\n		return current;\n	}\n\n	method _assign_all_result ( value, op, last_result ) {\n		return op \u2261 "~=" ? last_result : value;\n	}\n\n	method assign_first ( raw, value, op := ":=", weak := false ) {\n		let got := self.evaluate( raw, { want: "first" } );\n		die "Path assignment (@) found no matches" if got.empty;\n		return self._apply_assignment_ref(\n			got[0].ref(),\n			value,\n			op,\n			weak,\n		);\n	}\n\n	method assign_all ( raw, value, op := ":=", weak := false ) {\n		let got := self.evaluate(raw);\n		if ( got.empty ) {\n			return self._assign_all_result( value, op, value );\n		}\n\n		let last_result := value;\n		for ( let node in got ) {\n			last_result := self._apply_assignment_ref(\n				node.ref(),\n				value,\n				op,\n				weak,\n			);\n		}\n\n		return self._assign_all_result( value, op, last_result );\n	}\n\n	method assign_maybe ( raw, value, op := ":=", weak := false ) {\n		let got := self.evaluate( raw, { want: "first" } );\n		if ( got.empty ) {\n			return false;\n		}\n\n		self._apply_assignment_ref( got[0].ref(), value, op, weak );\n		return true;\n	}\n\n	method ref_first ( raw ) {\n		let got := self.evaluate( raw, { want: "first" } );\n		die "Path assignment (@) found no matches" if got.empty;\n		return got[0].ref();\n	}\n\n	method ref_all ( raw ) {\n		return self.evaluate(raw).map( fn n \u2192 n.ref );\n	}\n\n	method ref_maybe ( raw ) {\n		let got := self.evaluate( raw, { want: "first" } );\n		return got.empty ? null : got[0].ref();\n	}\n}\n';
        virtualFiles["/modules/std/path/z/context.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/path/z/context - Evaluation context used by std/path/z.\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module provides the pure-Zuzu evaluation context used by ZPath.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<< Ctx({ root, nodeset?, parentset?, meta? }) >>\n\nConstructs a ZPath evaluation context. Returns: C<Ctx>. Wraps C<root>\nas a C<std/path/z/node> C<Node> and stores the active node sets.\n\n=over\n\n=item C<< ctx.with_nodeset(ns, ps) >>\n\nParameters: C<ns> is the next node set and C<ps> is the parent set.\nReturns: C<Ctx>. Returns a copy of the context with different node\nsets.\n\n=item C<< ctx.nested(extras?) >>\n\nParameters: C<extras> is optional metadata. Returns: C<Ctx>. Returns a\nnested context with incremented metadata level.\n\n=item C<< ctx.root() >>\n\nParameters: none. Returns: C<Node>. Returns the root node.\n\n=item C<< ctx.nodeset() >>\n\nParameters: none. Returns: C<Array>. Returns the current node set.\n\n=item C<< ctx.parentset() >>\n\nParameters: none. Returns: C<Array> or C<null>. Returns the parent node\nset.\n\n=item C<< ctx.meta() >>\n\nParameters: none. Returns: C<Dict>. Returns context metadata.\n\n=back\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/path/z/context >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/path/z/node import Node;\n\nclass Ctx {\n	let root := null;\n	let nodeset := null;\n	let parentset := null;\n	let meta := null;\n\n	method __build__ () {\n		if ( not ( root instanceof Node ) ) {\n			let root_obj := root;\n			let node_type := null;\n\n			try {\n				node_type := int( "" _ root_obj.nodeType() );\n			}\n			catch {\n			}\n\n			let xml_document := node_type = 9;\n			if ( not xml_document and root_obj can documentElement ) {\n				try {\n					root_obj.documentElement();\n					xml_document := true;\n				}\n				catch {\n				}\n			}\n\n			if ( xml_document ) {\n				try {\n					let de := root_obj.documentElement();\n					root_obj := de if de \u2262 null;\n				}\n				catch {\n				}\n			}\n\n			root := Node.wrap( root_obj );\n		}\n\n		nodeset ?:= [ root ];\n		meta ?:= { level: 0 };\n	}\n\n	method with_nodeset ( ns, ps ) {\n		return new Ctx(\n			root: root,\n			nodeset: ns,\n			parentset: ps,\n			meta: meta,\n		);\n	}\n\n	method nested ( extras? ) {\n		// Extras is optional metadata; an empty map is still a value.\n		let extra_meta := extras ?: {};\n\n		let next_meta := {\n			level: meta.get( "level", 0 ) + 1,\n		};\n\n		for ( let pair in extra_meta.enumerate ) {\n			next_meta.add( pair );\n		}\n\n		return new Ctx(\n			root: root,\n			nodeset: nodeset,\n			parentset: parentset,\n			meta: next_meta,\n		);\n	}\n\n	method root () { return root; }\n	method nodeset () { return nodeset; }\n	method parentset () { return parentset; }\n	method meta () { return meta; }\n}\n';
        virtualFiles["/modules/std/path/z/evaluate.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/path/z/evaluate - Pure Zuzu evaluator for ZPath expressions.\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module provides the pure-Zuzu evaluator used by ZPath.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<Evaluator>\n\nPure-Zuzu evaluator for parsed ZPath AST values.\n\n=over\n\n=item C<< evaluator.operator_definitions() >>\n\nParameters: none. Returns: C<Array>. Returns the active operator\ndefinition table.\n\n=item C<< evaluator.function_definitions() >>\n\nParameters: none. Returns: C<Array>. Returns the active function\ndefinition table.\n\n=item C<< evaluator.eval_expr_wrap(ast, ctx) >>\n\nParameters: C<ast> is an AST node and C<ctx> is a C<Ctx>. Returns:\nC<Array>. Evaluates with optional debug dumping.\n\n=item C<< evaluator.eval_expr(ast, ctx) >>\n\nParameters: C<ast> is an AST node and C<ctx> is a C<Ctx>. Returns:\nC<Array>. Evaluates an expression to a node set.\n\n=item C<< evaluator.nested_ctx(ctx, ... PairList extras) >>\n\nParameters: C<ctx> is a C<Ctx> or C<null> and C<extras> are metadata.\nReturns: C<Ctx> or C<null>. Creates a nested evaluation context.\n\n=item C<< evaluator.eval_binop(ast, ctx) >>, C<< evaluator.eval_unop(ast, ctx) >>\n\nParameters: C<ast> is an operator AST node and C<ctx> is a C<Ctx>.\nReturns: C<Array>. Evaluates a binary or unary operator.\n\n=item C<< evaluator.eval_path(path_ast, ctx) >>\n\nParameters: C<path_ast> is a path AST node and C<ctx> is a C<Ctx>.\nReturns: C<Array>. Evaluates a path expression to selected nodes.\n\n=item C<< evaluator.maybe_apply_action(node, ctx) >>\n\nParameters: C<node> is a C<Node> and C<ctx> is a C<Ctx>. Returns:\nC<Node>. Applies any pending path action.\n\n=item C<< evaluator.eval_fn(fn_ast, ctx) >>\n\nParameters: C<fn_ast> is a function-call AST node and C<ctx> is a\nC<Ctx>. Returns: C<Array>. Evaluates a ZPath function call.\n\n=item C<< evaluator.string_replace(string, pattern, replacement) >>\n\nParameters: all arguments are strings or regex-like values. Returns:\nC<String>. Applies ZPath string replacement.\n\n=item C<< evaluator.dedup_nodes(nodes) >>\n\nParameters: C<nodes> is an array of nodes. Returns: C<Array>. Removes\nduplicate nodes while preserving order.\n\n=item C<< evaluator.truthy(n) >>\n\nParameters: C<n> is a node or value. Returns: C<Boolean>. Applies ZPath\ntruthiness.\n\n=item C<< evaluator.to_number(n) >>, C<< evaluator.to_string(n) >>\n\nParameters: C<n> is a node or value. Returns: C<Number> or C<String>.\nCoerces a ZPath value.\n\n=item C<< evaluator.equals(a, b) >>\n\nParameters: C<a> and C<b> are nodes or values. Returns: C<Boolean>.\nCompares two ZPath values.\n\n=back\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/path/z/evaluate >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/string import replace, index, substr;\nfrom std/path/z/node import Node;\nfrom std/path/z/functions import STANDARD_FUNCTIONS;\nfrom std/path/z/operators import STANDARD_OPERATORS;\n\nlet _do_dump := false;\n\nclass Evaluator {\n	let _operator_definitions;\n	let _function_definitions;\n\n	let \u03B5 := 0.000000001;\n\n	method operator_definitions () {\n		_operator_definitions ?:= STANDARD_OPERATORS;\n		return _operator_definitions;\n	}\n\n	method function_definitions () {\n		_function_definitions ?:= STANDARD_FUNCTIONS;\n		return _function_definitions;\n	}\n\n	method eval_expr_wrap ( ast, ctx ) {\n		from std/dump import Dumper;\n		let got := self._real_eval_expr ( ast, ctx );\n		say `AST ${Dumper.dump(ast)} CTX ${Dumper.dump(ctx)} \u21D2 GOT ${Dumper.dump(got)}` if _do_dump;\n		return got;\n	}\n\n	method eval_expr ( ast, ctx ) {\n\n		switch ( ast{t} : eq ) {\n			case "num":\n				return [ Node.wrap( ast{v} ) ];\n			case "str":\n				return [ Node.wrap( ast{v} ) ];\n			case "path":\n				return self.eval_path( ast, ctx );\n			case "fn":\n				return self.eval_fn( ast, ctx );\n			case "un":\n				return self.eval_unop( ast, ctx );\n			case "bin":\n				return self.eval_binop( ast, ctx );\n			case "ternary":\n				let c  := self.eval_expr( ast{c}, ctx );\n				let ab := self.truthy( c.get(0) ) ? "a" : "b";\n				return self.eval_expr( ast{(ab)}, ctx );\n			case "elvis":\n				let left := self.eval_expr( ast{c}, ctx );\n				let first := left.get( 0, null );\n				return left if first \u2262 null and first.primitive_value() \u2262 null;\n				return self.eval_expr( ast{b}, ctx );\n			default:\n				die "Panic! Unknown AST node type!";\n		}\n	}\n\n	method nested_ctx ( ctx, ... PairList extras ) {\n		return null if ctx \u2261 null;\n		return ctx.nested( extras );\n	}\n\n	method _hold_parent ( node, parent ) {\n		if ( node \u2262 null and parent \u2262 null ) {\n			node.hold_parent(parent);\n		}\n		return node;\n	}\n\n	method _children ( node ) {\n		let out := [];\n		for ( let child in node.children() ) {\n			out.push( self._hold_parent( child, node ) );\n		}\n		return out;\n	}\n\n	method _attributes ( node ) {\n		let out := [];\n		for ( let attr in node.attributes() ) {\n			out.push( self._hold_parent( attr, node ) );\n		}\n		return out;\n	}\n\n	method _indexed_child ( node, i ) {\n		return self._hold_parent( node.indexed_child(i), node );\n	}\n\n	method _named_child ( node, name ) {\n		return self._hold_parent( node.named_child(name), node );\n	}\n\n	method _named_indexed_child ( node, name, i ) {\n		return self._hold_parent( node.named_indexed_child( name, i ), node );\n	}\n\n	method eval_binop ( ast, ctx ) {\n		const op := ast{op};\n		const op_def := self.operator_definitions().first(\n			fn x \u2192 x.get_spelling eq op and x.is_binary()\n		);\n		if ( op_def and op_def{f} ) {\n			const implementation := op_def{f};\n			return implementation( op_def, self, ast, ctx, ast{l}, ast{r} );\n		}\n		return [];\n	}\n\n	method eval_unop ( ast, ctx ) {\n		const op := ast{op};\n		const op_def := self.operator_definitions().first(\n			fn x \u2192 x.get_spelling eq op and x.is_unary()\n		);\n		if ( op_def and op_def{f} ) {\n			const implementation := op_def{f};\n			return implementation( op_def, self, ast, ctx, ast{e} );\n		}\n		return [];\n	}\n\n	method eval_path ( path_ast, ctx ) {\n		let current := [];\n		for ( let n in ctx.nodeset() ) {\n			current.push(n);\n		}\n\n		let parentset := ctx.parentset();\n\n		for ( let seg in path_ast{s} ) {\n			let next_nodes := [];\n\n			if ( seg{k} \u2261 "root" ) {\n				next_nodes := [ ctx.root() ];\n			}\n			else if ( seg{k} \u2261 "dot" ) {\n				next_nodes := current;\n			}\n			else if ( seg{k} \u2261 "parent" ) {\n				for ( let n in current ) {\n					let p := n.parent();\n					if ( p \u2262 null ) {\n						next_nodes.push(p);\n					}\n				}\n				next_nodes := self.dedup_nodes(next_nodes);\n			}\n			else if ( seg{k} \u2261 "ancestors" ) {\n				let anc := [];\n				for ( let n in current ) {\n					let p := n.parent();\n					while ( p \u2262 null ) {\n						anc.push(p);\n						p := p.parent();\n					}\n				}\n				next_nodes := self.dedup_nodes(anc);\n			}\n			else if ( seg{k} \u2261 "star" ) {\n				let kids := [];\n				for ( let n in current ) {\n					for ( let child in self._children(n) ) {\n						if ( child.type() \u2262 "attr" ) {\n							kids.push(child);\n						}\n					}\n				}\n				next_nodes := self.dedup_nodes(kids);\n			}\n			else if ( seg{k} \u2261 "desc" ) {\n				let acc := [];\n				let stack := [];\n				for ( let n in current ) {\n					stack.push(n);\n				}\n\n				while ( stack.length() > 0 ) {\n					let n := stack.shift();\n					acc.push(n);\n					for ( let child in self._children(n) ) {\n						if ( child.type() \u2262 "attr" ) {\n							stack.push(child);\n						}\n					}\n				}\n				next_nodes := self.dedup_nodes(acc);\n			}\n			else if ( seg{k} \u2261 "index" ) {\n				let idx := seg{i};\n				let kids := [];\n				for ( let n in current ) {\n					let c := self._indexed_child( n, idx );\n					kids.push(c) if c \u2262 null;\n				}\n				next_nodes := self.dedup_nodes(kids);\n			}\n			else if ( seg{k} \u2261 "fnseg" ) {\n				let out := [];\n				for ( let n in current ) {\n					let seg_ctx := ctx.with_nodeset( [ n ], current );\n					let fn_ast := { t: "fn", n: seg{n}, a: seg{a} };\n					let res := self.eval_fn( fn_ast, seg_ctx );\n					for ( let x in res ) {\n						out.push(x);\n					}\n				}\n				next_nodes := out;\n			}\n			else if ( seg{k} \u2261 "name" ) {\n				let name := seg{n};\n\n				if ( name ~ /^\\@/ ) {\n					if ( name \u2261 "@*" ) {\n						let attrs := [];\n						for ( let n in current ) {\n							for ( let a in self._attributes(n) ) {\n								attrs.push(a);\n							}\n						}\n						next_nodes := self.dedup_nodes(attrs);\n					}\n					else {\n						let attrs := [];\n						for ( let n in current ) {\n							for ( let a in self._attributes(n) ) {\n								if ( a.name() \u2261 name ) {\n									attrs.push(a);\n								}\n							}\n						}\n						next_nodes := self.dedup_nodes(attrs);\n					}\n				}\n				else {\n					let kids := [];\n					for ( let n in current ) {\n						if ( n.can_have_named_indexed_children() ) {\n							let idx := 0;\n							while ( true ) {\n								let c := self._named_indexed_child( n, name, idx );\n								last if c \u2261 null;\n								kids.push(c);\n								idx++;\n							}\n						}\n						else {\n							let c := self._named_child( n, name );\n							kids.push(c) if c \u2262 null;\n						}\n					}\n					next_nodes := self.dedup_nodes(kids);\n				}\n\n				if ( seg.exists("i") and seg{i} \u2262 null ) {\n					let idx := seg{i};\n					let picked := [];\n					for ( let n in current ) {\n						let c := self._named_indexed_child( n, name, idx );\n						picked.push(c) if c \u2262 null;\n					}\n					next_nodes := self.dedup_nodes(picked);\n				}\n			}\n			else {\n				die "Unknown path segment kind: " _ seg{k};\n			}\n\n			if ( seg.exists("q") and seg{q}.length() > 0 ) {\n				for ( let q in seg{q} ) {\n					if ( q.exists("t") and q{t} \u2261 "num" and q{v} ~ /^\\d+$/ ) {\n						let idx := 0 + q{v};\n\n						if ( next_nodes.length() > 0 and self._node_is_xml(next_nodes[0]) ) {\n							next_nodes := ( idx \u2265 0 and idx < next_nodes.length() ) ? [ next_nodes[idx] ] : [];\n						}\n						else {\n							let picked := [];\n							for ( let node in next_nodes ) {\n								let ch := self._children(node)\n									.grep( fn c \u2192 c.type() \u2262 "attr" );\n								if ( idx \u2265 0 and idx < ch.length() ) {\n									picked.push( ch[idx] );\n								}\n							}\n							next_nodes := picked;\n						}\n\n						next;\n					}\n\n					let filtered := [];\n					let i := 0;\n					while ( i < next_nodes.length() ) {\n						let node := next_nodes[i];\n						let ns_ctx := ctx.with_nodeset( next_nodes, current );\n						let filter_ctx := ns_ctx.with_nodeset( [ node ], next_nodes );\n						let r := self.eval_expr( q, self.nested_ctx( filter_ctx, want: "exists" ) );\n\n						let ok := false;\n						if ( q.exists("t") and q{t} \u2261 "path" ) {\n							ok := r.length() > 0;\n						}\n						else {\n							ok := self.truthy( r.length() > 0 ? r[0] : null );\n						}\n\n						if ( ok ) {\n							filtered.push(node);\n						}\n						i++;\n					}\n					next_nodes := filtered;\n				}\n			}\n\n			parentset := current;\n			current := next_nodes;\n		}\n\n		return current;\n	}\n\n	method maybe_apply_action ( node, ctx ) {\n		const meta := ctx.meta();\n		return node if not meta.exists( "action" );\n		const action := meta{action};\n		return node if action \u2261 null;\n		return node if not action.exists( "op" );\n		node.do_action(action);\n		return node;\n	}\n\n	method eval_fn ( fn_ast, ctx ) {\n		const name := fn_ast{n};\n		const fn_def := self.function_definitions().first( fn f \u2192 f.has_name(name) );\n		// Function-argument ASTs are null or arrays; empty arrays are values.\n		return fn_def{f}( fn_def, self, fn_ast, ctx, fn_ast{a} ?: [] ) if fn_def;\n		return [];\n	}\n\n	method string_replace ( string, pattern, replacement ) {\n		let text := string \u2261 null ? "" : "" _ string;\n		let rep := replacement \u2261 null ? "" : "" _ replacement;\n\n		try {\n			return replace( text, pattern, rep, "g" );\n		}\n		catch {\n			return replace( text, "" _ pattern, rep, "g" );\n		}\n	}\n\n	method dedup_nodes ( nodes ) {\n		let seen := {};\n		let out := [];\n		for ( let n in nodes ) {\n			// Node ids are null or stable identifiers; only null needs anon keys.\n			let key := n.id ?: ( "anon:" _ out.length() _ ":" _ ( "" _ n.raw() ) );\n			if ( not seen.exists(key) ) {\n				seen.set( key, true );\n				out.push(n);\n			}\n		}\n		return out;\n	}\n\n	method truthy ( n ) {\n		return false if n \u2261 null;\n		let pv := n.primitive_value();\n		return pv ? true : false;\n	}\n\n	method to_number ( n ) {\n		return null if n \u2261 null;\n		return n.number_value();\n	}\n\n	method to_string ( n ) {\n		return null if n \u2261 null;\n		return n.string_value();\n	}\n\n	method equals ( a, b ) {\n		return false if a \u2261 null or b \u2261 null;\n\n		let a_type := a.type();\n		let b_type := b.type();\n\n		if ( b_type eq "null" ) {\n			return a_type eq "null";\n		}\n		if ( a_type eq "null" ) {\n			return b_type eq "null";\n		}\n\n		if ( a_type eq "boolean" and b_type eq "boolean" ) {\n			let av := a.primitive_value() ? true : false;\n			let bv := b.primitive_value() ? true : false;\n			return av \u2261 bv;\n		}\n\n		if ( a_type \u2261 "number" and b_type \u2261 "number" ) {\n			let av := a.number_value();\n			let bv := b.number_value();\n			return false if av \u2261 null or bv \u2261 null;\n\n			if ( ( "" _ av ) ~ /\\./ or ( "" _ bv ) ~ /\\./ ) {\n				return abs( av - bv ) < \u03B5;\n			}\n\n			return av = bv;\n		}\n\n		let string_like := [ "string", "text", "attr", "comment", "element" ];\n		if ( a_type in string_like and b_type in string_like ) {\n			let av := a.string_value();\n			let bv := b.string_value();\n			return av eq bv;\n		}\n\n		let aid := a.id();\n		let bid := b.id();\n		return false if aid \u2261 null or bid \u2261 null;\n		return aid eq bid;\n	}\n\n	method _node_is_xml ( n ) {\n		if ( n \u2261 null ) {\n			return false;\n		}\n		let raw := n.raw();\n		try {\n			let node_type := raw.nodeType();\n			return node_type \u2262 null;\n		}\n		catch {\n			return false;\n		}\n	}\n}\n';
        virtualFiles["/modules/std/path/z/functions.zzm"] = `=encoding utf8

=head1 NAME

std/path/z/functions - Function definitions for ZPath.

=head1 IMPLEMENTATION SUPPORT

This module is supported by all implementations of ZuzuScript.

=head1 DESCRIPTION

This module defines the function objects and standard function table used
by C<std/path/z>.

=head1 EXPORTS

=head2 Classes

=over

=item C<< Func({ spelling: String, f: Function }) >>

Constructs a ZPath function definition. Returns: C<Func>.

=over

=item C<< func.has_name(n) >>

Parameters: C<n> is a function name. Returns: C<Boolean>. Returns true
when C<n> matches the function spelling.

=back

=back

=head2 Functions

=over

=item C<< replace(haystack, needle, replacement) >>

Parameters: C<haystack> is source text, C<needle> is a pattern, and
C<replacement> is replacement text. Returns: C<String>. Performs ZPath
replacement with capture substitutions.

=item C<< mk_single_number_function(String name, Function impl) >>

Parameters: C<name> is a ZPath function name and C<impl> maps one
number. Returns: C<Function>. Builds a function wrapper for per-node
numeric functions.

=item C<< mk_aggregate_number_function(String name, Function impl) >>

Parameters: C<name> is a ZPath function name and C<impl> maps an array
of numbers. Returns: C<Function>. Builds a function wrapper for
aggregate numeric functions.

=item C<< mk_single_string_function(String name, Function impl) >>

Parameters: C<name> is a ZPath function name and C<impl> maps one
string. Returns: C<Function>. Builds a function wrapper for per-node
string functions.

=item C<< mk_match_function() >>

Parameters: none. Returns: C<Function>. Builds the standard ZPath
C<match> function implementation.

=back

=head2 Constants

=over

=item C<STANDARD_FUNCTIONS>

Type: C<Array>. Standard ZPath function definitions.

=back

=head1 COPYRIGHT AND LICENCE

B<< std/path/z/functions >> is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under
the terms of either the Artistic License 1.0 or the GNU General Public
License version 2.

=cut

from std/path/z/node import KDLNodeNode, KDLValueNode, Node, XmlNodeNode;
from std/path/z/operators import EvalHelpers;
from std/data/xml/escape import escape_xml, unescape_xml;
from std/string import index, rindex, search, sprint, substr, join;
from std/math import Math;


class Func with EvalHelpers {
	let String spelling with get;
	let Function f;

	method has_name ( n ) {
		return true if self.get_spelling eq n;
		return false;
	}
}

function replace ( haystack, needle, replacement ) {
	let copy := haystack;

	if ( replacement ~ /\\$[0-9]/ ) {
		let r := replacement;
		copy ~= needle \u2192 do {
			let matches := m;
			r ~= /\\$([0-9]+)/g \u2192 matches[ m[1] ];
			r;
		};
	}
	else {
		copy ~= needle \u2192 replacement;
	}

	return copy;
}

function mk_single_number_function ( String name, Function impl ) {
	return function ( funk, ev, ast, ctx, args ) {
		let nodes := [];
		for ( let a in args ) {
			const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );
			for ( let n in got ) {
				nodes.push( n );
			}
		}
		else {
			nodes := ctx.nodeset;
		}
		return nodes
			.map( fn x \u2192 x.number_value )
			.grep( fn x \u2192 x instanceof Number )
			.map( fn x \u2192 funk.wrap_for_array( impl(x) ) );
	};
}

function mk_aggregate_number_function ( String name, Function impl ) {
	return function ( funk, ev, ast, ctx, args ) {
		let nodes := [];
		for ( let a in args ) {
			const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );
			for ( let n in got ) {
				nodes.push( n );
			}
		}
		else {
			nodes := ctx.nodeset;
		}
		const nums := nodes
			.map( fn x \u2192 x.number_value )
			.grep( fn x \u2192 x instanceof Number );
		return funk.wrap( impl( nums ) );
	};
}

function mk_single_string_function ( String name, Function impl ) {
	return function ( funk, ev, ast, ctx, args ) {
		let nodes := [];
		for ( let a in args ) {
			const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );
			for ( let n in got ) {
				nodes.push( n );
			}
		}
		else {
			nodes := ctx.nodeset;
		}
		return nodes
			.map( fn x \u2192 x.string_value )
			.grep( fn x \u2192 x instanceof String )
			.map( fn x \u2192 funk.wrap_for_array( impl(x) ) );
	};
}

function mk_match_function () {
	return function ( funk, ev, ast, ctx, args ) {
		let nodes := [];
		let re;

		if ( args.empty ) {
			die "Not enough arguments for match()";
		}
		else {
			re := try {
				ev.eval_expr( args[0], ev.nested_ctx( ctx ) )[0].string_value;
			} catch {
				"";
			};
		}

		for ( let a in args[1:] ) {
			const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );
			for ( let n in got ) {
				nodes.push( n );
			}
		}
		else {
			nodes := ctx.nodeset;
		}

		return nodes
			.map( fn x \u2192 x.string_value )
			.grep( fn x \u2192 x instanceof String )
			.map( fn x \u2192 funk.wrap_for_array( ( x ~ re ) ? true : false ) );
	}
}

const STANDARD_FUNCTIONS := [
	new Func(
		spelling: "true",
		f: function ( funk, ev, ast, ctx, args ) {
			die "Too many arguments for true()" unless args.empty;
			return funk.wrap( true );
		},
	),

	new Func(
		spelling: "false",
		f: function ( funk, ev, ast, ctx, args ) {
			die "Too many arguments for false()" unless args.empty;
			return funk.wrap( false );
		},
	),

	new Func(
		spelling: "null",
		f: function ( funk, ev, ast, ctx, args ) {
			die "Too many arguments for null()" unless args.empty;
			return funk.wrap( null );
		},
	),

	new Func(
		spelling: "die",
		f: function ( funk, ev, ast, ctx, args ) {
			die "Called 'die' function in zpath";
		},
	),

	new Func(
		spelling: "count",
		f: function ( funk, ev, ast, ctx, args ) {
			let n := 0;
			for ( let a in args ) {
				const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );
				n += got.length;
			}
			else {
				// Parentset can be an empty array; only null falls back.
				const cur := ctx.parentset ?: ctx.nodeset;
				n := cur.length;
			}
			return funk.wrap( n );
		},
	),

	new Func(
		spelling: "index",
		f: function ( funk, ev, ast, ctx, args ) {
			if ( args.length = 0 ) {
				const cur := ctx.nodeset.get( 0, null );
				return funk.wrap( cur ? cur.ix : null );
			}
			else if ( args.length = 1 ) {
				const got := ev.eval_expr( args[0], ev.nested_ctx( ctx ) );
				return got.map( fn x \u2192 funk.wrap_for_array(x.ix) );
			}
			die "Too many arguments for index()";
		},
	),

	new Func(
		spelling: "key",
		f: function ( funk, ev, ast, ctx, args ) {
			if ( args.length = 0 ) {
				const cur := ctx.nodeset.get( 0, null );
				return funk.wrap( cur ? cur.key : null );
			}
			else if ( args.length = 1 ) {
				const got := ev.eval_expr( args[0], ev.nested_ctx( ctx ) );
				return got.map(
					fn x \u2192 funk.wrap_for_array(
						x \u2261 null ? null : x.key
					)
				);
			}
			die "Too many arguments for key()";
		},
	),

	new Func(
		spelling: "type",
		f: function ( funk, ev, ast, ctx, args ) {
			if ( args.length = 0 ) {
				const cur := ctx.nodeset.get( 0, null );
				return funk.wrap( cur ? cur.type : "undefined" );
			}
			else if ( args.length = 1 ) {
				const got := ev.eval_expr( args[0], ev.nested_ctx( ctx ) ).get( 0, null );
				return funk.wrap( got ? got.type : "undefined" );
			}
			die "Too many arguments for type()";
		},
	),

	new Func(
		spelling: "union",
		f: function ( funk, ev, ast, ctx, args ) {
			let out := [];
			for ( let arg in args ) {
				const got := ev.eval_expr( arg, ev.nested_ctx( ctx ) );
				for ( let n in got ) {
					out.push( n );
				}
			}
			return ev.dedup_nodes( out );
		},
	),

	new Func(
		spelling: "intersection",
		f: function ( funk, ev, ast, ctx, args ) {
			return [] if args.empty;

			let out := ev.eval_expr( args[0], ev.nested_ctx( ctx ) );
			out := ev.dedup_nodes( out );

			let i := 1;
			while ( i < args.length() ) {
				let got := ev.eval_expr( args[i], ev.nested_ctx( ctx ) );
				got := ev.dedup_nodes( got );

				let seen := {};
				for ( let n in got ) {
					let key := n.id();
					if ( key \u2261 null ) {
						key := "anon:" _ ( "" _ n.raw() );
					}
					seen.set( key, true );
				}

				let next_out := [];
				for ( let n in out ) {
					let key := n.id();
					if ( key \u2261 null ) {
						key := "anon:" _ ( "" _ n.raw() );
					}
					if ( seen.exists(key) ) {
						next_out.push(n);
					}
				}

				out := next_out;
				last if out.empty;
				i++;
			}

			return ev.dedup_nodes( out );
		},
	),

	new Func(
		spelling: "is-first",
		f: function ( funk, ev, ast, ctx, args ) {
			if ( args.length = 0 ) {
				const cur := ctx.nodeset.get( 0, null );
				return [] unless cur and cur.parent;
				return funk.wrap( cur.ix = 0 );
			}
			die "Too many arguments for is-first()";
		},
	),

	new Func(
		spelling: "is-last",
		f: function ( funk, ev, ast, ctx, args ) {
			if ( args.length = 0 ) {
				const cur := ctx.nodeset.get( 0, null );
				return [] unless cur and cur.parent and cur.ix \u2262 null;
				const siblings := cur.parent.children
					.grep( fn kid \u2192 kid.key \u2261 cur.key );
				return [] if siblings.empty;
				let pos := 0;
				while ( pos < siblings.length ) {
					const kid := siblings[pos];
					last if kid.id() \u2261 cur.id();
					pos++;
				}
				return [] if pos \u2265 siblings.length;
				return funk.wrap( pos = siblings.length - 1 );
			}
			die "Too many arguments for is-last()";
		},
	),

	new Func(
		spelling: "next",
		f: function ( funk, ev, ast, ctx, args ) {
			if ( args.length = 0 ) {
				const cur := ctx.nodeset.get( 0, null );
				return [ cur.next_sibling ];
			}
			else {
				let out := [];
				for ( let arg in args ) {
					const got := ev.eval_expr( arg, ev.nested_ctx( ctx ) );
					for ( let n in got ) {
						out.push( n.next_sibling );
					}
				}
				return out;
			}
		},
	),

	new Func(
		spelling: "prev",
		f: function ( funk, ev, ast, ctx, args ) {
			if ( args.length = 0 ) {
				const cur := ctx.nodeset.get( 0, null );
				return [ cur.prev_sibling ];
			}
			else {
				let out := [];
				for ( let arg in args ) {
					const got := ev.eval_expr( arg, ev.nested_ctx( ctx ) );
					for ( let n in got ) {
						out.push( n.prev_sibling );
					}
				}
				return out;
			}
		},
	),

	new Func(
		spelling: "string",
		f: function ( funk, ev, ast, ctx, args ) {
			if ( args.length = 0 ) {
				const cur := ctx.nodeset.get( 0, null );
				return [] unless cur;
				return funk.wrap( cur.string_value );
			}
			else {
				let out := [];
				for ( let arg in args ) {
					const got := ev.eval_expr( arg, ev.nested_ctx( ctx ) );
					for ( let n in got ) {
						out.push( n );
					}
				}
				return out.map( fn x \u2192 funk.wrap_for_array( x.string_value ) );
			}
		},
	),

	new Func(
		spelling: "number",
		f: function ( funk, ev, ast, ctx, args ) {
			if ( args.length = 0 ) {
				const cur := ctx.nodeset.get( 0, null );
				return [] unless cur;
				return funk.wrap( cur.number_value );
			}
			else {
				let out := [];
				for ( let arg in args ) {
					const got := ev.eval_expr( arg, ev.nested_ctx( ctx ) );
					for ( let n in got ) {
						out.push( n );
					}
				}
				return out.map( fn x \u2192 funk.wrap_for_array( x.number_value ) );
			}
		},
	),

	new Func(
		spelling: "value",
		f: function ( funk, ev, ast, ctx, args ) {
			if ( args.length = 0 ) {
				const cur := ctx.nodeset.get( 0, null );
				return [] unless cur;
				return funk.wrap( cur.primitive_value );
			}
			else {
				let out := [];
				for ( let arg in args ) {
					const got := ev.eval_expr( arg, ev.nested_ctx( ctx ) );
					for ( let n in got ) {
						out.push( n );
					}
				}
				return out.map( fn x \u2192 funk.wrap_for_array( x.primitive_value ) );
			}
		},
	),

	new Func(
		spelling: "ceil",
		f: mk_single_number_function( "ceil", fn n \u2192 ceil n ),
	),

	new Func(
		spelling: "floor",
		f: mk_single_number_function( "floor", fn n \u2192 floor n ),
	),

	new Func(
		spelling: "round",
		f: mk_single_number_function( "round", fn n \u2192 round n ),
	),

	new Func(
		spelling: "sum",
		f: mk_aggregate_number_function( "sum", fn nums \u2192 Math.sum(nums) ),
	),

	new Func(
		spelling: "min",
		f: mk_aggregate_number_function( "min", fn nums \u2192 Math.min(nums) ),
	),

	new Func(
		spelling: "max",
		f: mk_aggregate_number_function( "max", fn nums \u2192 Math.max(nums) ),
	),

	new Func(
		spelling: "escape",
		f: mk_single_string_function( "escape", fn s \u2192 escape_xml(s) ),
	),

	new Func(
		spelling: "unescape",
		f: mk_single_string_function( "unescape", fn s \u2192 unescape_xml(s) ),
	),

	new Func(
		spelling: "upper-case",
		f: mk_single_string_function( "upper-case", fn s \u2192 uc s ),
	),

	new Func(
		spelling: "lower-case",
		f: mk_single_string_function( "lower-case", fn s \u2192 lc s ),
	),

	new Func(
		spelling: "index-of",
		f: function ( funk, ev, ast, ctx, args ) {
			let nodes := [];
			let search;

			if ( args.empty ) {
				die "Not enough arguments for index-of()";
			}
			else {
				search := try {
					ev.eval_expr( args[0], ev.nested_ctx( ctx ) )[0].string_value;
				} catch {
					"";
				};
			}

			for ( let a in args[1:] ) {
				const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );
				for ( let n in got ) {
					nodes.push( n );
				}
			}
			else {
				nodes := ctx.nodeset;
			}

			return nodes
				.map( fn x \u2192 x.string_value )
				.grep( fn x \u2192 x instanceof String )
				.map( fn x \u2192 funk.wrap_for_array( index(x, search) ) );
		}
	),

	new Func(
		spelling: "last-index-of",
		f: function ( funk, ev, ast, ctx, args ) {
			let nodes := [];
			let search;

			if ( args.empty ) {
				die "Not enough arguments for last-index-of()";
			}
			else {
				search := try {
					ev.eval_expr( args[0], ev.nested_ctx( ctx ) )[0].string_value;
				} catch {
					"";
				};
			}

			for ( let a in args[1:] ) {
				const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );
				for ( let n in got ) {
					nodes.push( n );
				}
			}
			else {
				nodes := ctx.nodeset;
			}

			return nodes
				.map( fn x \u2192 x.string_value )
				.grep( fn x \u2192 x instanceof String )
				.map( fn x \u2192 funk.wrap_for_array( rindex(x, search) ) );
		}
	),

	new Func(
		spelling: "substring",
		f: function ( funk, ev, ast, ctx, args ) {

			let nodes := [];
			let start;
			let len;

			if ( args.length < 2 ) {
				die "Not enough arguments for substring()";
			}
			else {
				start := try {
					ev.eval_expr( args[-2], ev.nested_ctx( ctx ) )[0].number_value;
				} catch {
					0;
				};
				len := try {
					ev.eval_expr( args[-1], ev.nested_ctx( ctx ) )[0].number_value;
				} catch {
					0;
				};
			}

			for ( let a in args[0:-2] ) {
				const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );
				for ( let n in got ) {
					nodes.push( n );
				}
			}
			else {
				nodes := ctx.nodeset;
			}

			return nodes
				.map( fn x \u2192 x.string_value )
				.grep( fn x \u2192 x instanceof String )
				.map( fn x \u2192 funk.wrap_for_array( substr(x, start, len) ) );
		}
	),

	new Func(
		spelling: "format",
		f: function ( funk, ev, ast, ctx, args ) {
			let nodes := [];
			let fmt;

			if ( args.empty ) {
				die "Not enough arguments for format()";
			}
			else {
				fmt := try {
					ev.eval_expr( args[0], ev.nested_ctx( ctx ) )[0].string_value;
				} catch {
					"";
				};
			}

			for ( let a in args[1:] ) {
				const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );
				for ( let n in got ) {
					nodes.push( n );
				}
			}
			else {
				nodes := ctx.nodeset;
			}

			return nodes
				.map( fn x \u2192 x.string_value )
				.grep( fn x \u2192 x instanceof String )
				.map( fn x \u2192 funk.wrap_for_array( sprint(fmt, x) ) );
		}
	),

	new Func(
		spelling: "string-length",
		f: mk_single_string_function( "string-length", fn s \u2192 length s ),
	),

	new Func(
		spelling: "match",
		f: mk_match_function(),
	),

	new Func(
		spelling: "matches",
		f: mk_match_function(),
	),

	new Func(
		spelling: "replace",
		f: function ( funk, ev, ast, ctx, args ) {
			let nodes := [];
			let pattern;
			let replacement;

			if ( args.length < 2 ) {
				die "Not enough arguments for replace()";
			}
			else {
				pattern := try {
					ev.eval_expr( args[0], ev.nested_ctx( ctx ) )[0].string_value;
				} catch {
					"";
				};
				replacement := try {
					ev.eval_expr( args[1], ev.nested_ctx( ctx ) )[0].string_value;
				} catch {
					"";
				};
			}

			for ( let a in args[2:] ) {
				const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );
				for ( let n in got ) {
					nodes.push( n );
				}
			}
			else {
				nodes := ctx.nodeset;
			}

			return nodes
				.map( fn x \u2192 x.string_value )
				.grep( fn x \u2192 x instanceof String )
				.map( fn x \u2192 funk.wrap_for_array( replace( x, pattern, replacement ) ) );
		}
	),

	new Func(
		spelling: "join",
		f: function ( funk, ev, ast, ctx, args ) {
			let nodes := [];
			let joiner;

			if ( args.empty ) {
				die "Not enough arguments for format()";
			}
			else {
				joiner := try {
					ev.eval_expr( args[0], ev.nested_ctx( ctx ) )[0].string_value;
				} catch {
					"";
				};
			}

			for ( let a in args[1:] ) {
				const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );
				for ( let n in got ) {
					nodes.push( n );
				}
			}
			else {
				nodes := ctx.nodeset;
			}

			const strings := nodes
				.map( fn x \u2192 x.string_value )
				.grep( fn x \u2192 x instanceof String );
			return funk.wrap( join( joiner, strings ) );
		}
	),

	new Func(
		spelling: "url",
		f: function ( funk, ev, ast, ctx, args ) {
			if ( args.length = 0 ) {
				const cur := ctx.nodeset.get( 0, null );
				return [] unless cur;
				return funk.wrap( cur instanceof XmlNodeNode ? cur.raw.namespaceURI() : null );
			}
			else if ( args.length = 1 ) {
				const got := ev.eval_expr( args[0], ev.nested_ctx( ctx ) );
				return got.map(
					fn x \u2192 funk.wrap_for_array(
						x instanceof XmlNodeNode ? x.raw.namespaceURI() : null
					)
				);
			}
			die "Too many arguments for url()";
		},
	),

	new Func(
		spelling: "local-name",
		f: function ( funk, ev, ast, ctx, args ) {
			if ( args.length = 0 ) {
				const cur := ctx.nodeset.get( 0, null );
				return [] unless cur;
				return funk.wrap(
					cur instanceof XmlNodeNode ? cur.raw.localName()
						: cur instanceof KDLNodeNode ? cur.name()
						: null
				);
			}
			else if ( args.length = 1 ) {
				const got := ev.eval_expr( args[0], ev.nested_ctx( ctx ) );
				return got.map(
					fn x \u2192 funk.wrap_for_array(
						x instanceof XmlNodeNode ? x.raw.localName()
							: x instanceof KDLNodeNode ? x.name()
							: null
					)
				);
			}
			die "Too many arguments for local-name()";
		},
	),

	new Func(
		spelling: "tag",
		f: function ( funk, ev, ast, ctx, args ) {
			if ( args.length = 0 ) {
				const cur := ctx.nodeset.get( 0, null );
				return [] unless cur;
				if ( cur instanceof KDLNodeNode ) {
					let ann := cur.raw().type_annotation();
					return funk.wrap( ann \u2261 null ? null : "" _ ann );
				}
				if ( cur instanceof KDLValueNode ) {
					let ann := cur.raw().type_annotation();
					return funk.wrap( ann \u2261 null ? null : "" _ ann );
				}
				return funk.wrap( cur.has_tagged ? cur.tagged{tag} : null );
			}
			else if ( args.length = 1 ) {
				const got := ev.eval_expr( args[0], ev.nested_ctx( ctx ) );
				return got.map(
					fn x \u2192 funk.wrap_for_array(
						x instanceof KDLNodeNode
							? (
								x.raw().type_annotation() \u2261 null
									? null
									: "" _ x.raw().type_annotation()
							)
							: x instanceof KDLValueNode
							? (
								x.raw().type_annotation() \u2261 null
									? null
									: "" _ x.raw().type_annotation()
							)
							: x can has_tagged ? x.tagged{tag} : null
					)
				);
			}
			die "Too many arguments for tag()";
		},
	),
];
`;
        virtualFiles["/modules/std/path/z/lexer.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/path/z/lexer - Pure Zuzu lexer for ZPath expressions.\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module provides the pure-Zuzu lexer used by ZPath.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<< Lexer({ src: String, allowed_operators: Array }) >>\n\nConstructs a ZPath lexer. Returns: C<Lexer>. Tokenizes C<src> using the\nallowed operator table.\n\n=over\n\n=item C<< lexer.peek() >>\n\nParameters: none. Returns: C<Dict>. Returns the current token without\nadvancing.\n\n=item C<< lexer.peek_n(n) >>\n\nParameters: C<n> is a zero-based lookahead offset. Returns: C<Dict>.\nReturns a token ahead of the current position.\n\n=item C<< lexer.peek_kind() >>\n\nParameters: none. Returns: C<String>. Returns the current token kind.\n\n=item C<< lexer.peek_kind_n(n) >>\n\nParameters: C<n> is a zero-based lookahead offset. Returns: C<String>.\nReturns a token kind ahead of the current position.\n\n=item C<< lexer.next_tok() >>\n\nParameters: none. Returns: C<Dict>. Consumes and returns the current\ntoken.\n\n=item C<< lexer.expect(k) >>\n\nParameters: C<k> is the expected token kind. Returns: C<Dict>. Consumes\nand returns the current token, throwing when it has a different kind.\n\n=item C<< lexer.known_operators() >>\n\nParameters: none. Returns: C<Array>. Returns the allowed operator\ndefinitions.\n\n=back\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/path/z/lexer >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/string import substr;\n\nclass Lexer {\n	let src := "";\n	let scan_i := 0;\n	let toks := [];\n	let pos := 0;\n	let allowed_operators;\n\n	method __build__ () {\n		die "Expected some operators" unless allowed_operators;\n		toks := self._tokenize(src);\n	}\n\n	method peek () {\n		return toks[pos];\n	}\n\n	method peek_n ( n ) {\n		return toks[pos + n];\n	}\n\n	method peek_kind () {\n		return toks[pos]{k};\n	}\n\n	method peek_kind_n ( n ) {\n		return toks[pos + n]{k};\n	}\n\n	method next_tok () {\n		let tok := toks[pos];\n		pos++;\n		return tok;\n	}\n\n	method expect ( k ) {\n		let t := self.next_tok();\n		die `Expected ${k}, got ${t{k}}` if t{k} \u2262 k;\n		return t;\n	}\n\n	method _is_ws ( c ) {\n		return c \u2262 null and c ~ /\\s/;\n	}\n\n	method _prev_sig ( chars, idx ) {\n		let j := idx - 1;\n		while ( j >= 0 ) {\n			if ( chars[j] ~ /\\s/ ) {\n				j--;\n				next;\n			}\n			return chars[j];\n		}\n		return null;\n	}\n\n	method _next_sig ( chars, idx, n ) {\n		let j := idx + 1;\n		while ( j < n ) {\n			if ( chars[j] ~ /\\s/ ) {\n				j++;\n				next;\n			}\n			return chars[j];\n		}\n		return null;\n	}\n\n	method _is_path_ctx_prev ( c ) {\n		return c \u2261 "[" or c \u2261 "(" or c \u2261 "," or c \u2261 ":" or c \u2261 "?" or c \u2261 "/";\n	}\n\n	method _is_path_ctx_next ( c ) {\n		return c \u2261 "]" or c \u2261 ")" or c \u2261 "," or c \u2261 ":" or c \u2261 "?" or c \u2261 "/";\n	}\n\n	method _ws_on_both ( left, right ) {\n		return self._is_ws(left) and self._is_ws(right);\n	}\n\n	method known_operators () {\n		return allowed_operators;\n	}\n\n	method _sorted_operators () {\n		return self.known_operators()\n			.grep( fn o \u2192 not o.lexer_should_ignore )\n			.sort( fn ( x, y ) \u2192 y.char_length <=> x.char_length );\n	}\n\n	method _operator_at ( chars, i, n, ops ) {\n		let oi := 0;\n		while ( oi < ops.length ) {\n			let op := ops[oi];\n			let spell := op{spelling};\n			let m := length spell;\n			if ( i + m <= n ) {\n				let got := "";\n				let j := 0;\n				while ( j < m ) {\n					got _= chars[i + j];\n					j++;\n				}\n				if ( got \u2261 spell ) {\n					return op;\n				}\n			}\n			oi++;\n		}\n		return null;\n	}\n\n	method _is_name_char ( c ) {\n		return c ~ /[A-Za-z0-9_\\-]/;\n	}\n\n	method _allows_operator_kind ( kind ) {\n		return allowed_operators.first( fn op \u2192 op.get_kind() \u2261 kind )\n			? true\n			: false;\n	}\n\n	method _tokenize ( String source ) {\n		let t := [];\n		let chars := [];\n		let n := length source;\n		let ops := self._sorted_operators();\n		let z := 0;\n		while ( z < n ) {\n			chars.push( substr( source, z, 1 ) );\n			z++;\n		}\n\n		let i := 0;\n		while ( i < n ) {\n			let ch := chars[i];\n\n			if ( ch ~ /\\s/ ) {\n				i++;\n				next;\n			}\n\n			let prev := i > 0 ? chars[i - 1] : null;\n			let nxt := i + 1 < n ? chars[i + 1] : null;\n\n			let prev_nonws := self._prev_sig( chars, i );\n			let next_nonws := self._next_sig( chars, i, n );\n\n			function push_token ( tok ) {\n				tok{ws_before} := self._is_ws(prev) ? true : false;\n				tok{ws_after}  := self._is_ws(nxt)  ? true : false;\n				t.push( tok );\n			}\n\n			function push_sized_token ( tok, after ) {\n				tok{ws_before} := self._is_ws(prev) ? true : false;\n				tok{ws_after}  := self._is_ws(after) ? true : false;\n				t.push( tok );\n			}\n\n			if ( ch \u2261 "/" ) {\n				if (\n					self._ws_on_both( prev, nxt )\n					and prev_nonws \u2262 null and next_nonws \u2262 null\n					and not self._is_path_ctx_prev(prev_nonws)\n					and not self._is_path_ctx_next(next_nonws)\n				) {\n					push_token( { k: "SLASH", v: "/" } );\n					i++;\n					next;\n				}\n				if (\n					( self._is_ws(prev) xor self._is_ws(nxt) )\n					and prev_nonws \u2262 null and next_nonws \u2262 null\n					and not self._is_path_ctx_prev(prev_nonws)\n					and not self._is_path_ctx_next(next_nonws)\n				) {\n					die `Binary operator \'/\' requires whitespace around it`;\n				}\n				t.push( { k: "SLASH_PATH", v: "/" } );\n				i++;\n				next;\n			}\n\n			let op := self._operator_at( chars, i, n, ops );\n			if ( op \u2262 null ) {\n				let spell := op.get_spelling();\n				let need_ws := op.requires_whitespace();\n				let m := length spell;\n				let op_prev := i > 0 ? chars[i - 1] : null;\n				let op_next := i + m < n ? chars[i + m] : null;\n				let path_ambiguous_star :=\n					( spell \u2261 "*" or spell \u2261 "**" )\n					and not self._ws_on_both( op_prev, op_next );\n\n				let left_name := false;\n				let right_name := false;\n				if ( spell ~ /^[A-Za-z_]/ ) {\n					left_name := op_prev \u2262 null and self._is_name_char(op_prev);\n					right_name := op_next \u2262 null and self._is_name_char(op_next);\n				}\n\n				if (\n					not path_ambiguous_star\n					and not left_name\n					and not right_name\n				) {\n					if ( need_ws ) {\n						if ( self._ws_on_both( op_prev, op_next ) ) {\n							push_sized_token( { k: op.get_kind(), v: spell }, op_next );\n							i := i + m;\n							next;\n						}\n						die `Binary operator \'${spell}\' requires whitespace around it`;\n					}\n					push_sized_token( { k: op.get_kind(), v: spell }, op_next );\n					i := i + m;\n					next;\n				}\n			}\n\n			if ( ch \u2261 "(" ) { t.push( { k: "LPAREN", v: "(" } ); i++; next; }\n			if ( ch \u2261 ")" ) { t.push( { k: "RPAREN", v: ")" } ); i++; next; }\n			if ( ch \u2261 "[" ) { t.push( { k: "LBRACK", v: "[" } ); i++; next; }\n			if ( ch \u2261 "]" ) { t.push( { k: "RBRACK", v: "]" } ); i++; next; }\n			if ( ch \u2261 "," ) { t.push( { k: "COMMA", v: "," } ); i++; next; }\n\n			if ( ch \u2261 "." ) {\n				if ( i + 2 < n and chars[i + 1] \u2261 "." and chars[i + 2] \u2261 "*" ) {\n					push_token( { k: "DOTDOTSTAR", v: "..*" } );\n					i := i + 3;\n					next;\n				}\n				if ( i + 1 < n and chars[i + 1] \u2261 "." ) {\n					push_token( { k: "DOTDOT", v: ".." } );\n					i := i + 2;\n					next;\n				}\n				push_token( { k: "DOT", v: "." } );\n				i++;\n				next;\n			}\n\n			if ( ch \u2261 "*" and self._ws_on_both( prev, nxt ) ) {\n				push_token( { k: "STAR", v: "*" } );\n				i++;\n				next;\n			}\n\n			if ( ch \u2261 "*" ) {\n				if ( i + 1 < n and chars[i + 1] \u2261 "*" ) {\n					push_token( { k: "STARSTAR", v: "**" } );\n					i := i + 2;\n					next;\n				}\n				push_token( { k: "STAR_PATH", v: "*" } );\n				i++;\n				next;\n			}\n\n			if ( self._allows_operator_kind( "ELVIS" ) and ch \u2261 "?" and nxt \u2261 ":" ) {\n				let op_next := i + 2 < n ? chars[i + 2] : null;\n				if ( self._ws_on_both( prev, op_next ) ) {\n					t.push( {\n						k: "ELVIS",\n						v: "?:",\n						ws_before: self._is_ws(prev) ? true : false,\n						ws_after: self._is_ws(op_next) ? true : false,\n					} );\n					i := i + 2;\n					next;\n				}\n				die "Elvis operator \'?:\' requires whitespace around it";\n			}\n\n			if ( ch \u2261 "?" or ch \u2261 ":" ) {\n				if ( self._ws_on_both( prev, nxt ) ) {\n					push_token( { k: ch \u2261 "?" ? "QMARK" : "COLON", v: ch } );\n					i++;\n					next;\n				}\n				die `Ternary operator \'${ch}\' requires whitespace around it`;\n			}\n\n			if ( ch \u2261 "\\"" or ch \u2261 "\'" ) {\n				let quote := ch;\n				i++;\n				let s := "";\n				let esc := false;\n				while ( i < n ) {\n					let cc := chars[i];\n					i++;\n					if ( esc ) {\n						if ( cc \u2261 "\\\\" or cc \u2261 quote or cc \u2261 "\\"" or cc \u2261 "\'" ) {\n							s _= cc;\n						}\n						else {\n							s _= self._unescape_char(cc);\n						}\n						esc := false;\n						next;\n					}\n					if ( cc \u2261 "\\\\" ) { esc := true; next; }\n					last if cc \u2261 quote;\n					s _= cc;\n				}\n				push_token( { k: "STRING", v: s, q: quote } );\n				next;\n			}\n\n			if ( ch \u2261 "#" ) {\n				let j := i + 1;\n				let neg := false;\n				if ( j < n and chars[j] \u2261 "-" ) {\n					neg := true;\n					j++;\n				}\n				die "Invalid index \'#\'" if j >= n or not( chars[j] ~ /\\d/ );\n				let num := "";\n				while ( j < n and chars[j] ~ /\\d/ ) {\n					num _= chars[j];\n					j++;\n				}\n				let parsed := 0 + num;\n				parsed := 0 - parsed if neg;\n				push_token( { k: "INDEX", v: parsed } );\n				i := j;\n				next;\n			}\n\n			if ( ch ~ /[0-9]/ ) {\n				let j := i;\n				let num := "";\n				while ( j < n and chars[j] ~ /[0-9.]/ ) {\n					num _= chars[j];\n					j++;\n				}\n				push_token( { k: "NUMBER", v: 0 + num } );\n				i := j;\n				next;\n			}\n\n			let name := self._read_name( chars, i );\n			if ( name{v} \u2262 "" ) {\n				push_token( { k: "NAME", v: name{v} } );\n				i := name{i};\n				next;\n			}\n\n			die `Unexpected character \'${ch}\' at position ${i}`;\n		}\n\n		t.push( { k: "EOF", v: "" } );\n		return t;\n	}\n\n	method _unescape_char ( c ) {\n		return "\\n" if c \u2261 "n";\n		return "\\r" if c \u2261 "r";\n		return "\\t" if c \u2261 "t";\n		return c;\n	}\n\n	method _read_name ( chars, start_i ) {\n		let n := chars.length();\n		let delim := {\n			"\\n": true,\n			"\\r": true,\n			"\\t": true,\n			"(": true,\n			")": true,\n			"[": true,\n			"]": true,\n			"/": true,\n			",": true,\n			"=": true,\n			"&": true,\n			"|": true,\n			"!": true,\n			"<": true,\n			">": true,\n			"#": true,\n			" ": true,\n		};\n		let buf := "";\n		let esc := false;\n		let i := start_i;\n\n		while ( i < n ) {\n			let c := chars[i];\n			if ( esc ) {\n				buf _= c;\n				esc := false;\n				i++;\n				next;\n			}\n\n			if ( c \u2261 "\\\\" ) {\n				esc := true;\n				i++;\n				next;\n			}\n\n			last if delim.exists(c);\n			last if c ~ /\\s/;\n			buf _= c;\n			i++;\n		}\n\n		return { v: "", i: start_i } if buf \u2261 "";\n		return { v: buf, i: i };\n	}\n}\n';
        virtualFiles["/modules/std/path/z/node.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/path/z/node - Node wrapper used by std/path/z.\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nObjects of this class wrap underlying values and provide traversal and\ncoercion helpers used while evaluating ZPath expressions.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<Node>\n\nBase wrapper for values traversed by ZPath.\n\n=over\n\n=item C<< Node.from_root(obj) >>\n\nParameters: C<obj> is any query root. Returns: C<Node>. Wraps a root\nvalue for traversal.\n\n=item C<< Node.wrap(obj, parent?, key?, ix?) >>\n\nParameters: C<obj> is any value, with optional parent, key, and index\nmetadata. Returns: C<Node>. Wraps a value in the appropriate node\nsubclass.\n\n=item C<< node.hold_parent(owner) >>\n\nParameters: C<owner> is a parent node. Returns: C<Node>. Retains parent\nmetadata on the node.\n\n=item C<< node.raw() >>, C<< node.value() >>, C<< node.primitive_value() >>\n\nParameters: none. Returns: value. Returns the wrapped raw, node, or\nprimitive value.\n\n=item C<< node.parent() >>\n\nParameters: none. Returns: C<Node> or C<null>. Returns the parent node.\n\n=item C<< node.key() >>, C<< node.ix() >>, C<< node.index() >>, C<< node.id() >>\n\nParameters: none. Returns: value. Returns traversal key, index, or\nstable node id metadata.\n\n=item C<< node.type() >>, C<< node.name() >>\n\nParameters: none. Returns: C<String> or C<null>. Returns the node type\nor name.\n\n=item C<< node.tagged() >>\n\nParameters: none. Returns: C<String> or C<null>. Returns a KDL value\ntag when present.\n\n=item C<< node.has_tagged() >>\n\nParameters: none. Returns: C<Boolean>. Returns true when tag metadata is\navailable.\n\n=item C<< node.string_value() >>, C<< node.number_value() >>\n\nParameters: none. Returns: C<String>, C<Number>, or C<null>. Coerces the\nnode for string or numeric ZPath operations.\n\n=item C<< node.can_have_named_children() >>, C<< node.can_have_indexed_children() >>, C<< node.can_have_named_indexed_children() >>\n\nParameters: none. Returns: C<Boolean>. Reports supported child lookup\nmodes.\n\n=item C<< node.named_child(name) >>, C<< node.indexed_child(i) >>, C<< node.named_indexed_child(name, i) >>\n\nParameters: C<name> is a child name and C<i> is an index. Returns:\nC<Node> or C<null>. Looks up child nodes.\n\n=item C<< node.next_child(child) >>, C<< node.prev_child(child) >>, C<< node.next_sibling() >>, C<< node.prev_sibling() >>\n\nParameters: C<child> is a child node where required. Returns: C<Node> or\nC<null>. Traverses adjacent nodes.\n\n=item C<< node.named_attribute(name) >>\n\nParameters: C<name> is an attribute name. Returns: C<Node> or C<null>.\nLooks up one attribute node.\n\n=item C<< node.children() >>, C<< node.attributes() >>\n\nParameters: none. Returns: C<Array>. Returns child or attribute nodes.\n\n=item C<< node.dump() >>\n\nParameters: none. Returns: C<String>. Returns a diagnostic rendering of\nthe node.\n\n=item C<< node.find(zpath) >>\n\nParameters: C<zpath> is a C<ZPath> object or subclass, such as C<ZZPath>.\nReturns: C<Array>. Evaluates a nested path from this node and returns\nselected node objects.\n\n=item C<< node.do_action(action) >>, C<< node.do_action_on_child(child, action) >>\n\nParameters: C<action> is a path action and C<child> is a child node.\nReturns: value. Applies path mutation actions.\n\n=item C<< node.ref() >>, C<< node.ref_on_child(child) >>\n\nParameters: C<child> is a child node where required. Returns:\nC<Function>. Returns a reference-like getter/setter.\n\n=back\n\n=item C<SimpleNode>, C<StringNode>, C<NumberNode>, C<BooleanNode>, C<NullNode>\n\nScalar node wrappers. They inherit the C<Node> API and override\nC<type>, C<string_value>, or C<number_value> where appropriate.\n\n=item C<ArrayNode>, C<SetNode>, C<BagNode>, C<DictNode>, C<PairListNode>, C<PairNode>\n\nCollection node wrappers. They inherit the C<Node> API and override\nchild, attribute, assignment, and reference methods appropriate to their\ncollection type. PairList children are C<PairNode> objects in pair order;\nC<indexed_child> uses global pair index, while C<named_indexed_child> uses\nthe occurrence index among pairs with the same key.\n\n=item C<KDLDocumentNode>, C<KDLNodeNode>, C<KDLValueNode>\n\nKDL node wrappers. They inherit the C<Node> API and expose KDL children,\nattributes, names, value tags, and scalar coercions.\n\n=item C<XmlNodeNode>\n\nXML node wrapper. It inherits the C<Node> API and exposes XML names,\nchildren, attributes, sibling traversal, and scalar text values.\n\n=item C<TimeNode>\n\nC<std/time> wrapper. It inherits the C<Node> API and exposes time\nattributes plus string and numeric values.\n\n=item C<PathNode>\n\nC<std/io> path wrapper. It inherits the C<Node> API and exposes path\nattributes plus string values.\n\n=item C<WidgetNode>\n\nC<std/gui/objects> widget wrapper. It inherits the C<Node> API and\nexposes widget children by widget class name and index, plus public\nwidget properties as assignable attributes.\n\n=back\n\n=head2 Variables\n\n=over\n\n=item C<determine_class>\n\nType: C<Function>. Chooses the concrete node wrapper class for a raw\nvalue.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/path/z/node >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/data/cbor import TaggedValue;\nfrom std/data/kdl import KDLDocument, KDLNode, KDLValue;\nfrom std/internals import class_name, load_module, ref_id;\nfrom std/io try import Path;\nfrom std/math import Math;\nfrom std/string import substr;\nfrom std/time import Time;\n\n\nfunction determine_class;\nlet _widget_class_loaded := false;\nlet _widget_class := null;\n\nconst _WIDGET_ATTRS := [\n	{ name: "id", getter: "id", setter: "set_id" },\n	{ name: "enabled", getter: "enabled", setter: "set_enabled" },\n	{ name: "visible", getter: "visible", setter: "set_visible" },\n	{ name: "width", getter: "width", accessor: true },\n	{ name: "height", getter: "height", accessor: true },\n	{ name: "minwidth", getter: "minwidth", accessor: true },\n	{ name: "minheight", getter: "minheight", accessor: true },\n	{ name: "maxwidth", getter: "maxwidth", accessor: true },\n	{ name: "maxheight", getter: "maxheight", accessor: true },\n	{ name: "classes", getter: "classes" },\n	{ name: "title", getter: "title", setter: "set_title", accessor: true },\n	{ name: "text", getter: "text", setter: "set_text", accessor: true },\n	{ name: "value", getter: "value", setter: "set_value", accessor: true },\n	{ name: "placeholder", getter: "placeholder", setter: "set_placeholder", accessor: true },\n	{ name: "for", getter: "for_id", setter: "set_for_id", accessor: true },\n	{ name: "align", getter: "align", accessor: true },\n	{ name: "gap", getter: "gap", accessor: true },\n	{ name: "padding", getter: "padding", accessor: true },\n	{ name: "label", getter: "label", accessor: true },\n	{ name: "collapsible", getter: "collapsible", accessor: true },\n	{ name: "collapsed", getter: "collapsed", accessor: true },\n	{ name: "wrap", getter: "wrap", accessor: true },\n	{ name: "readonly", getter: "readonly", accessor: true },\n	{ name: "multiline", getter: "multiline", accessor: true },\n	{ name: "password", getter: "password", accessor: true },\n	{ name: "required", getter: "required", accessor: true },\n	{ name: "src", getter: "src", accessor: true },\n	{ name: "alt", getter: "alt", accessor: true },\n	{ name: "fit", getter: "fit", accessor: true },\n	{ name: "checked", getter: "checked", accessor: true },\n	{ name: "indeterminate", getter: "indeterminate", accessor: true },\n	{ name: "name", getter: "name", accessor: true },\n	{ name: "disabled", getter: "disabled", accessor: true },\n	{ name: "group", getter: "group", accessor: true },\n	{ name: "multiple", getter: "multiple", accessor: true },\n	{ name: "min", getter: "min", accessor: true },\n	{ name: "max", getter: "max", accessor: true },\n	{ name: "first_day_of_week", getter: "first_day_of_week", accessor: true },\n	{ name: "orientation", getter: "orientation", accessor: true },\n	{ name: "step", getter: "step", accessor: true },\n	{ name: "show_text", getter: "show_text", accessor: true },\n	{ name: "selected", getter: "selected", accessor: true },\n	{ name: "placement", getter: "placement", accessor: true },\n	{ name: "icon", getter: "icon", setter: "set_icon", accessor: true },\n	{ name: "closable", getter: "closable", accessor: true },\n	{ name: "selected_index", getter: "selected_index", accessor: true },\n	{ name: "selected_path", getter: "selected_path", accessor: true },\n	{ name: "variant", getter: "variant", accessor: true },\n];\n\nfunction _zpath_widget_class () {\n	if ( not _widget_class_loaded ) {\n		_widget_class_loaded := true;\n		try {\n			_widget_class := load_module( "std/gui/objects", "Widget" );\n		}\n		catch {\n			_widget_class := null;\n		}\n	}\n	return _widget_class;\n}\n\nfunction _zpath_is_widget ( obj ) {\n	let Widget := _zpath_widget_class();\n	return Widget \u2262 null and obj instanceof Widget;\n}\n\nfunction _zpath_xml_node_type ( obj ) {\n	return null if not( obj can nodeType );\n	try {\n		return int( "" _ obj.nodeType() );\n	}\n	catch {\n	}\n	return null;\n}\n\nfunction _zpath_is_xml_document ( obj ) {\n	return true if _zpath_xml_node_type(obj) = 9;\n	return false if not( obj can documentElement );\n	try {\n		obj.documentElement();\n		return true;\n	}\n	catch {\n	}\n	return false;\n}\n\nfunction _zpath_is_xml_node ( obj ) {\n	return true if _zpath_xml_node_type(obj) \u2262 null;\n	return _zpath_is_xml_document(obj);\n}\n\nfunction _zpath_widget_attr_name ( name ) {\n	return ( name ~ /^@/ ) ? substr( name, 1 ) : name;\n}\n\nfunction _zpath_widget_attr_spec ( name ) {\n	let attr := _zpath_widget_attr_name(name);\n	return _WIDGET_ATTRS.first( fn spec \u2192 spec{name} \u2261 attr );\n}\n\nfunction _zpath_widget_attr_applies ( widget, spec ) {\n	let attr := spec{name};\n	if ( attr in [\n		"id",\n		"enabled",\n		"visible",\n		"width",\n		"height",\n		"minwidth",\n		"minheight",\n		"maxwidth",\n		"maxheight",\n		"classes",\n	] ) {\n		return true;\n	}\n\n	switch ( class_name(widget) : eq ) {\n		case "Window":\n			return attr in [ "title" ];\n		case "VBox", "HBox":\n			return attr in [ "align", "gap", "padding" ];\n		case "Frame":\n			return attr in [ "label", "collapsible", "collapsed" ];\n		case "Label":\n			return attr in [ "text", "for" ];\n		case "Text":\n			return attr in [ "value", "multiline", "readonly", "wrap" ];\n		case "RichText":\n			return attr in [ "value", "multiline", "readonly" ];\n		case "Image":\n			return attr in [ "src", "alt", "fit" ];\n		case "Input":\n			return attr in [\n				"value",\n				"placeholder",\n				"multiline",\n				"readonly",\n				"password",\n				"required",\n			];\n		case "DatePicker":\n			return attr in [ "value", "min", "max", "first_day_of_week" ];\n		case "Checkbox":\n			return attr in [ "label", "checked", "indeterminate" ];\n		case "Radio":\n			return attr in [ "label", "value", "group", "checked" ];\n		case "RadioGroup":\n			return attr in [ "name", "value" ];\n		case "Select":\n			return attr in [ "value", "multiple" ];\n		case "Menu":\n			return attr in [ "text" ];\n		case "MenuItem":\n			return attr in [ "text", "disabled" ];\n		case "Button":\n			return attr in [ "text", "variant" ];\n		case "Separator":\n			return attr in [ "orientation" ];\n		case "Slider":\n			return attr in [ "value", "min", "max", "step", "orientation", "readonly" ];\n		case "Progress":\n			return attr in [ "value", "min", "max", "indeterminate", "show_text" ];\n		case "Tabs":\n			return attr in [ "selected", "placement" ];\n		case "Tab":\n			return attr in [ "title", "value", "icon", "selected", "closable" ];\n		case "ListView":\n			return attr in [ "selected_index", "multiple" ];\n		case "TreeView":\n			return attr in [ "selected_path", "multiple" ];\n	}\n\n	return false;\n}\n\nfunction _zpath_widget_get_attr ( widget, spec ) {\n	let getter := spec{getter};\n	return widget.(getter)();\n}\n\nfunction _zpath_widget_set_attr ( widget, spec, value ) {\n	let setter := spec.get( "setter", null );\n	if ( setter \u2262 null ) {\n		try {\n			return widget.(setter)(value);\n		}\n		catch {\n		}\n	}\n\n	let getter := spec{getter};\n	if ( spec.get( "accessor", false ) ) {\n		try {\n			return widget.(getter)(value);\n		}\n		catch {\n		}\n	}\n\n	die `Widget attribute @${spec{name}} is not assignable`;\n}\n\nclass Node {\n	let raw with set := null;\n	let parent but weak := null;\n	let _parent_keepalive := null;\n	let key := null;\n	let id := null;\n	let ix := null;\n	let tagged with set, has := null;\n\n	static method _xml_node_type_code ( value ) {\n		try {\n			return int( "" _ value.nodeType() );\n		}\n		catch {\n			return null;\n		}\n	}\n\n	static method from_root ( obj ) {\n		return self.wrap(obj);\n	}\n\n	static method wrap ( _obj, parent?, key?, ix? ) {\n\n		let obj := _obj;\n\n		if ( obj instanceof Node ) {\n			return obj;\n		}\n\n		let Klass := determine_class( obj );\n\n		let n := new Klass(\n			raw: obj,\n			parent: parent,\n			key: key,\n			ix: ix,\n		);\n\n		if ( obj instanceof TaggedValue ) {\n			n.set_tagged(obj);\n			while ( obj instanceof TaggedValue ) {\n				obj := obj{value}\n			}\n			n.set_raw(obj);\n		}\n\n		n._build_id_with_parent(parent);\n\n		return n;\n	}\n\n	method hold_parent ( owner ) {\n		_parent_keepalive := owner;\n		return self;\n	}\n\n	method _use_ref_as_id () {\n		return false;\n	}\n\n	method _build_id () {\n		id := self._generate_id;\n	}\n\n	method _build_id_with_parent ( owner ) {\n		id := self._generate_id_with_parent(owner);\n	}\n\n	method _generate_id () {\n		return self._generate_id_with_parent(parent);\n	}\n\n	method _generate_id_with_parent ( owner ) {\n\n		if ( self._use_ref_as_id ) {\n			return "ref:" _ ref_id(raw);\n		}\n\n		if ( owner \u2261 null ) {\n			return "root";\n		}\n\n		if ( ix \u2262 null ) {\n			if ( key \u2262 null ) {\n				return owner.id _ "/" _ key _ "#" _ ix;\n			}\n			return owner.id _ "/#" _ ix;\n		}\n\n		if ( key \u2262 null ) {\n			return owner.id _ "/" _ key;\n		}\n\n		return "rand:" _ floor( 1000 * 1000 * 1000 * Math.rand() );\n	}\n\n	method raw ()    { return raw; }\n	method parent () { return parent; }\n	method key ()    { return key; }\n	method id ()     { return id; }\n	method ix ()     { return ix; }\n	method index ()  { return ix; }\n	method tagged () { return tagged; }\n\n	method type () {\n		return typeof raw;\n	}\n\n	method value () {\n		return raw;\n	}\n\n	method primitive_value () {\n		return raw;\n	}\n\n	method string_value () {\n		let p := self.primitive_value;\n		return p \u2261 null ? null : "" _ p;\n	}\n\n	method number_value () {\n		let v := self.primitive_value();\n		return 0 + v if v ~ /^-?(?:[0-9]+(?:\\.[0-9]+)?|\\.[0-9]+)$/;\n		return null;\n	}\n\n	method can_have_named_children () {\n		return false;\n	}\n\n	method can_have_indexed_children () {\n		return false;\n	}\n\n	method can_have_named_indexed_children () {\n		return false;\n	}\n\n	method named_child ( name ) {\n		self.children.first( fn kid \u2192 kid.key \u2261 name );\n	}\n\n	method indexed_child ( i ) {\n		self.children.first( fn kid \u2192 kid.ix \u2261 i );\n	}\n\n	method named_indexed_child ( name, i ) {\n		self.children.first( fn kid \u2192 kid.ix \u2261 i and kid.key \u2261 name );\n	}\n\n	method next_child ( child ) {\n		let i := child.ix;\n		return null if i \u2261 null;\n		return self.indexed_child( i + 1 );\n	}\n\n	method prev_child ( child ) {\n		let i := child.ix;\n		return null if i \u2261 null;\n		return null if i = 0;\n		return self.indexed_child( i - 1 );\n	}\n\n	method next_sibling () {\n		return self.parent.next_child( self );\n	}\n\n	method prev_sibling () {\n		return self.parent.prev_child( self );\n	}\n\n	method named_attribute ( name ) {\n		let attrname := ( name ~ /^@/ ) ? name : `@${name}`;\n		self.attributes.first( fn kid \u2192 kid.name \u2261 attrname );\n	}\n\n	method children () {\n		return [];\n	}\n\n	method attributes () {\n		return [];\n	}\n\n	method name () {\n		return key;\n	}\n\n	method dump () {\n		return {\n			"@type": self.type(),\n			"@id": self.id(),\n			"@key": self.key(),\n			"@index": self.index(),\n			"@value": self.primitive_value(),\n			children: self.children().map( fn c -> c.dump() ),\n			attributes: self.attributes().map( fn a -> a.dump() ),\n		};\n	}\n\n	method find ( zpath ) {\n		from std/path/z import ZPath;\n\n		die "Node.find expects a ZPath object"\n			unless zpath instanceof ZPath;\n\n		return zpath.evaluate(self);\n	}\n\n	method do_action ( action ) {\n		const container_node := self.parent();\n		die "Path assignment target has no parent node"\n			if container_node \u2261 null;\n		return container_node.do_action_on_child( self, action );\n	}\n\n	method ref () {\n		const container_node := self.parent();\n		die "Path assignment target has no parent node"\n			if container_node \u2261 null;\n		return container_node.ref_on_child(self);\n	}\n\n	method do_action_on_child ( child, action ) {\n		die `Path assignment target container \'${self.type()}\' is not assignable`;\n	}\n\n	method ref_on_child ( child ) {\n		die `Path assignment target container \'${self.type()}\' is not assignable`;\n	}\n}\n\nclass SimpleNode extends Node {\n}\n\nclass StringNode extends SimpleNode {\n\n	method string_value () {\n		let raw := self.raw;\n		if ( raw instanceof BinaryString ) {\n			return to_string( raw );\n		}\n		return raw;\n	}\n\n	method type () {\n		return "string";\n	}\n}\n\nclass NumberNode extends SimpleNode {\n	method number_value () {\n		let raw := self.raw;\n		return raw;\n	}\n\n	method type () {\n		return "number";\n	}\n}\n\nclass BooleanNode extends SimpleNode {\n	method type () {\n		return "boolean";\n	}\n}\n\nclass NullNode extends SimpleNode {\n	method type () {\n		return "null";\n	}\n}\n\nclass ArrayNode extends Node {\n\n	method _use_ref_as_id () {\n		return true;\n	}\n\n	method type () {\n		return "list";\n	}\n\n	method children () {\n		let raw := self.raw;\n		let out := [];\n		let i := 0;\n		while ( i < raw.length ) {\n			let child := Node.wrap( raw[i], self, null, i );\n			out.push(child);\n			i++;\n		}\n		return out;\n	}\n\n	method can_have_indexed_children () {\n		return false;\n	}\n\n	method do_action_on_child ( child, action ) {\n		return super( child, action ) if action{op} ne ":=";\n\n		const ix := child.ix();\n		die "Path assignment expects numeric array index" if ix \u2261 null;\n		let container := self.raw();\n		container[ix] := action{value};\n		return action{value};\n	}\n\n	method ref_on_child ( child ) {\n		const ix := child.ix();\n		die "Path assignment expects numeric array index" if ix \u2261 null;\n		let container := self.raw();\n		return \\ container[ix];\n	}\n}\n\nclass SetNode extends Node {\n\n	method _use_ref_as_id () {\n		return true;\n	}\n\n	method children () {\n		let raw := self.raw;\n		let out := [];\n		let i := 0;\n		while ( i < raw.length ) {\n			let child := Node.wrap( raw[i], self, null, null );\n			out.push(child);\n			i++;\n		}\n		return out;\n	}\n}\n\nclass BagNode extends Node {\n\n	method _use_ref_as_id () {\n		return true;\n	}\n\n	method children () {\n		let raw := self.raw;\n		let out := [];\n		let i := 0;\n		while ( i < raw.length ) {\n			let child := Node.wrap( raw[i], self, null, null );\n			out.push(child);\n			i++;\n		}\n		return out;\n	}\n}\n\nclass DictNode extends Node {\n\n	method _use_ref_as_id () {\n		return true;\n	}\n\n	method type () {\n		return "map";\n	}\n\n	method children () {\n		let raw := self.raw;\n		let out := [];\n		for ( let k in raw.keys() ) {\n			let child := Node.wrap( raw.get(k), self, k );\n			out.push(child);\n		}\n		return out;\n	}\n\n	method can_have_named_children () {\n		return true;\n	}\n\n	method do_action_on_child ( child, action ) {\n		return super( child, action ) if action{op} ne ":=";\n\n		const key := child.key();\n		die "Path assignment expects string dict key" if key \u2261 null;\n		let container := self.raw();\n		container{(key)} := action{value};\n		return action{value};\n	}\n\n	method ref_on_child ( child ) {\n		const key := child.key();\n		die "Path assignment expects string dict key" if key \u2261 null;\n		let container := self.raw();\n		return \\ container{(key)};\n	}\n}\n\nclass PairListNode extends Node {\n\n	method _use_ref_as_id () {\n		return true;\n	}\n\n	method children () {\n		let raw := self.raw;\n		let pairs := raw.to_Array();\n		let out := [];\n		let i := 0;\n		while ( i < pairs.length() ) {\n			let pair := pairs[i];\n			out.push( Node.wrap( pair, self, pair.key, i ) );\n			i++;\n		}\n		return out;\n	}\n\n	method can_have_named_children () {\n		return true;\n	}\n\n	method can_have_indexed_children () {\n		return true;\n	}\n\n	method can_have_named_indexed_children () {\n		return true;\n	}\n\n	method named_child ( name ) {\n		return self.named_indexed_child( name, 0 );\n	}\n\n	method indexed_child ( i ) {\n		let pairs := self.raw().to_Array();\n		return null if i < 0 or i >= pairs.length();\n		let pair := pairs[i];\n		return Node.wrap( pair, self, pair.key, i );\n	}\n\n	method named_indexed_child ( name, i ) {\n		let pairs := self.raw().to_Array();\n		let seen := 0;\n		let pos := 0;\n		while ( pos < pairs.length() ) {\n			let pair := pairs[pos];\n			if ( pair.key \u2261 name ) {\n				if ( seen = i ) {\n					return Node.wrap( pair, self, pair.key, pos );\n				}\n				seen++;\n			}\n			pos++;\n		}\n		return null;\n	}\n\n	method _replace_value_at ( pair_ix, value ) {\n		let container := self.raw();\n		let pairs := container.to_Array();\n		die "Path assignment expects numeric pairlist index"\n			if pair_ix \u2261 null or pair_ix < 0 or pair_ix >= pairs.length();\n\n		container.clear();\n		let i := 0;\n		while ( i < pairs.length() ) {\n			let pair := pairs[i];\n			container.add( pair.key, i = pair_ix ? value : pair.value );\n			i++;\n		}\n		return value;\n	}\n\n	method do_action_on_child ( child, action ) {\n		return super( child, action ) if action{op} ne ":=";\n\n		return self._replace_value_at( child.ix(), action{value} );\n	}\n\n	method ref_on_child ( child ) {\n		let pair_ix := child.ix();\n		return function ( ... args ) {\n			let current := self.indexed_child(pair_ix);\n			die "Path assignment target pairlist entry no longer exists"\n				if current \u2261 null;\n			return current.raw().value if args.length() = 0;\n			return self._replace_value_at( pair_ix, args[0] );\n		};\n	}\n}\n\nclass PairNode extends Node {\n\n	method attributes () {\n		let raw := self.raw;\n		return [ "key", "value" ]\n			.map( fn a \u2192 Node.wrap( raw.(a)(), self, `@${a}` ) );\n	}\n\n	method do_action_on_child ( child, action ) {\n		return super( child, action ) if action{op} ne ":=";\n		return super( child, action ) if child.key() ne "@value";\n\n		let container := self.parent();\n		return super( child, action )\n			if container \u2261 null or not ( container instanceof PairListNode );\n		return container.do_action_on_child( self, action );\n	}\n\n	method ref_on_child ( child ) {\n		return super(child) if child.key() ne "@value";\n\n		let container := self.parent();\n		return super(child)\n			if container \u2261 null or not ( container instanceof PairListNode );\n		return container.ref_on_child(self);\n	}\n}\n\nclass KDLDocumentNode extends Node {\n\n	method _use_ref_as_id () {\n		return true;\n	}\n\n	method type () {\n		return "document";\n	}\n\n	method children () {\n		let raw := self.raw;\n		let out := [];\n		let i := 0;\n		while ( i < raw.nodes().length() ) {\n			let child := raw.nodes()[i];\n			out.push( Node.wrap( child, self, child.name(), i ) );\n			i++;\n		}\n		return out;\n	}\n\n	method can_have_named_children () {\n		return true;\n	}\n\n	method can_have_indexed_children () {\n		return true;\n	}\n\n	method can_have_named_indexed_children () {\n		return true;\n	}\n\n	method indexed_child ( i ) {\n		return self.children().get( i, null );\n	}\n\n	method named_indexed_child ( name, i ) {\n		let n := 0;\n		for ( let child in self.children() ) {\n			if ( child.key() \u2261 name ) {\n				return child if n \u2261 i;\n				n++;\n			}\n		}\n		return null;\n	}\n}\n\nclass KDLNodeNode extends Node {\n\n	method _use_ref_as_id () {\n		return true;\n	}\n\n	method type () {\n		return "element";\n	}\n\n	method name () {\n		return self.raw().name();\n	}\n\n	method children () {\n		let raw := self.raw;\n		let out := [];\n		let i := 0;\n		for ( let arg in raw.args() ) {\n			out.push( Node.wrap( arg, self, null, i ) );\n			i++;\n		}\n		for ( let child in raw.children() ) {\n			out.push( Node.wrap( child, self, child.name(), i ) );\n			i++;\n		}\n		return out;\n	}\n\n	method attributes () {\n		let raw := self.raw;\n		let out := [];\n		let i := 0;\n		for ( let pair in raw.props().to_Array() ) {\n			out.push( Node.wrap( pair.value, self, "@" _ pair.key, i ) );\n			i++;\n		}\n		return out;\n	}\n\n	method can_have_named_children () {\n		return true;\n	}\n\n	method can_have_indexed_children () {\n		return true;\n	}\n\n	method can_have_named_indexed_children () {\n		return true;\n	}\n\n	method indexed_child ( i ) {\n		return self.children().get( i, null );\n	}\n\n	method named_indexed_child ( name, i ) {\n		let n := 0;\n		for ( let child in self.children() ) {\n			if ( child.key() \u2261 name ) {\n				return child if n \u2261 i;\n				n++;\n			}\n		}\n		return null;\n	}\n}\n\nclass KDLValueNode extends Node {\n\n	method type () {\n		return self.raw().type();\n	}\n\n	method value () {\n		return self.raw().native_value();\n	}\n\n	method primitive_value () {\n		return self.raw().native_value();\n	}\n\n	method string_value () {\n		return self.raw().to_String();\n	}\n\n	method number_value () {\n		try {\n			return self.raw().to_Number();\n		}\n		catch {\n			return null;\n		}\n	}\n\n	method has_tagged () {\n		return true;\n	}\n\n	method tagged () {\n		let ann := self.raw().type_annotation();\n		return {\n			tag: ann \u2261 null ? null : "" _ ann,\n			value: self.raw().native_value(),\n		};\n	}\n}\n\nclass XmlNodeNode extends Node {\n\n	method _generate_id () {\n		return\n			try {\n				let i := self.raw.unique_id;\n				i \u2261 null ? super() : `xml:${i}`;\n			}\n			catch {\n				super();\n			};\n	}\n\n	method type () {\n		let raw := self.raw;\n		if ( _zpath_is_xml_document(raw) ) {\n			return "document";\n		}\n		switch ( Node._xml_node_type_code(raw) ) {\n			case 1:\n				return "element";\n			case 2, 18:\n				return "attr";\n			case 3, 4:\n				return "text";\n			case 8:\n				return "comment";\n			case 9:\n				return "document";\n		}\n\n		return super();\n	}\n\n	method name () {\n		let raw := self.raw;\n		switch ( Node._xml_node_type_code(raw) ) {\n			case 1:\n				return raw.nodeName();\n			case 2, 18:\n				return "@" _ raw.nodeName();\n			case 3, 4:\n				return "#text";\n		}\n\n		return super();\n	}\n\n	method next_child ( child ) {\n		return child.next_sibling;\n	}\n\n	method prev_child ( child ) {\n		return child.prev_sibling;\n	}\n\n	method next_sibling () {\n		let x := self.raw.nextSibling;\n		return null if x \u2261 null;\n		return Node.wrap( x, self.parent, x.nodeName );\n	}\n\n	method prev_sibling () {\n		let x := self.raw.previousSibling;\n		return null if x \u2261 null;\n		return Node.wrap( x, self.parent, x.nodeName );\n	}\n\n	method primitive_value () {\n		let raw := self.raw;\n		if ( _zpath_is_xml_document(raw) ) {\n			let de := raw.documentElement();\n			return de \u2261 null ? null : de.textContent();\n		}\n		switch ( Node._xml_node_type_code(raw) ) {\n			case 1:\n				return raw.textContent;\n			case 2, 18:\n				return raw.nodeValue();\n			case 3, 4, 8:\n				return raw.data;\n			case 9:\n				let de := raw.documentElement();\n				return de \u2261 null ? null : de.textContent();\n		}\n\n		return super();\n	}\n\n	method string_value () {\n		let raw := self.raw;\n		if ( _zpath_is_xml_document(raw) ) {\n			let de := raw.documentElement();\n			return de \u2261 null ? null : de.textContent();\n		}\n		switch ( Node._xml_node_type_code(raw) ) {\n			case 1:\n				return raw.textContent;\n			case 2, 18:\n				return raw.nodeValue();\n			case 3, 4, 8:\n				return raw.data;\n			case 9:\n				let de := raw.documentElement();\n				return de \u2261 null ? null : de.textContent();\n		}\n\n		return super();\n	}\n\n	method can_have_named_children () {\n		return true;\n	}\n\n	method can_have_indexed_children () {\n		return true;\n	}\n\n	method can_have_named_indexed_children () {\n		return true;\n	}\n\n	method children () {\n		let raw := self.raw;\n		if ( _zpath_is_xml_document(raw) ) {\n			let de := raw.documentElement();\n			return de \u2261 null ? []\n				: [ Node.wrap( de, self, de.nodeName(), 0 ) ];\n		}\n		let node_type := Node._xml_node_type_code(raw);\n		if ( node_type = 9 ) {\n			let de := raw.documentElement();\n			return de \u2261 null ? []\n				: [ Node.wrap( de, self, de.nodeName(), 0 ) ];\n		}\n\n		if ( node_type = 1 ) {\n			let kids := [];\n			let count := {};\n			for ( let child in raw.childNodes() ) {\n				let nm := child.nodeName();\n				let n := count.exists(nm) ? count.get( nm ) : 0;\n				count.set( nm, n + 1 );\n				kids.push( Node.wrap( child, self, nm, n ) );\n			}\n			return kids;\n		}\n\n		return [];\n	}\n\n	method attributes () {\n		let raw := self.raw;\n		let out := super();\n		if ( Node._xml_node_type_code(raw) \u2261 1 ) {\n			for ( let attr in raw.attributes() ) {\n				let n := Node.wrap( attr, self, "@" _ attr.nodeName() );\n				out.push(n);\n			}\n		}\n		return out;\n	}\n}\n\nclass TimeNode extends Node {\n\n	method string_value () {\n		let raw := self.raw;\n		return raw.datetime;\n	}\n\n	method number_value () {\n		let raw := self.raw;\n		return raw.epoch;\n	}\n\n	method attributes () {\n		let raw := self.raw;\n		return [ "year", "month", "day", "hour", "min", "sec" ]\n			.map( fn a \u2192 Node.wrap( raw.(a)(), self, `@${a}` ) );\n	}\n}\n\nclass PathNode extends Node {\n\n	method string_value () {\n		let raw := self.raw;\n		return raw.to_String;\n	}\n\n	method attributes () {\n		let raw := self.raw;\n		if ( raw.is_file ) {\n			const stat := raw.stat;\n			return stat.keys.map( fn a \u2192 Node.wrap( stat{a}, self, `@${a}` ) );\n		}\n\n		return super();\n	}\n}\n\nclass WidgetNode extends Node {\n\n	method _use_ref_as_id () {\n		return true;\n	}\n\n	method type () {\n		return "widget";\n	}\n\n	method name () {\n		return class_name( self.raw() ) or? "Widget";\n	}\n\n	method can_have_named_children () {\n		return true;\n	}\n\n	method can_have_indexed_children () {\n		return true;\n	}\n\n	method can_have_named_indexed_children () {\n		return true;\n	}\n\n	method children () {\n		let out := [];\n		let i := 0;\n		for ( let child in self.raw().children() ) {\n			let nm := class_name(child) or? "Widget";\n			out.push( Node.wrap( child, self, nm, i ) );\n			i++;\n		}\n		return out;\n	}\n\n	method indexed_child ( i ) {\n		return self.children().get( i, null );\n	}\n\n	method named_indexed_child ( name, i ) {\n		let n := 0;\n		for ( let child in self.children() ) {\n			if ( child.key() \u2261 name ) {\n				return child if n \u2261 i;\n				n++;\n			}\n		}\n		return null;\n	}\n\n	method attributes () {\n		let raw := self.raw();\n		let out := [];\n		let i := 0;\n		for ( let spec in _WIDGET_ATTRS ) {\n			next unless _zpath_widget_attr_applies( raw, spec );\n			try {\n				let value := _zpath_widget_get_attr( raw, spec );\n				out.push( Node.wrap( value, self, "@" _ spec{name}, i ) );\n				i++;\n			}\n			catch {\n			}\n		}\n		return out;\n	}\n\n	method do_action_on_child ( child, action ) {\n		return super( child, action ) if action{op} ne ":=";\n\n		let spec := _zpath_widget_attr_spec( child.key() );\n		return super( child, action ) if spec \u2261 null;\n\n		_zpath_widget_set_attr( self.raw(), spec, action{value} );\n		return action{value};\n	}\n\n	method ref_on_child ( child ) {\n		let spec := _zpath_widget_attr_spec( child.key() );\n		return super(child) if spec \u2261 null;\n\n		let widget := self.raw();\n		return function ( ... args ) {\n			if ( args.length() = 0 ) {\n				return _zpath_widget_get_attr( widget, spec );\n			}\n			_zpath_widget_set_attr( widget, spec, args[0] );\n			return args[0];\n		};\n	}\n}\n\n// Need to define the body of this function late so it can refer back to\n// classes that have been declared.\n\nfunction determine_class ( obj ) {\n	let Klass;\n\n	let real_obj := obj;\n	while ( real_obj instanceof TaggedValue ) {\n		real_obj := real_obj{value};\n	}\n\n	if ( real_obj instanceof Null ) {\n		Klass := NullNode;\n	}\n	else if ( real_obj instanceof Boolean ) {\n		Klass := BooleanNode;\n	}\n	else if ( real_obj instanceof Number ) {\n		Klass := NumberNode;\n	}\n	else if ( real_obj instanceof String or real_obj instanceof BinaryString ) {\n		Klass := StringNode;\n	}\n	else if ( real_obj instanceof Array ) {\n		Klass := ArrayNode;\n	}\n	else if ( real_obj instanceof Bag ) {\n		Klass := BagNode;\n	}\n	else if ( real_obj instanceof Set ) {\n		Klass := SetNode;\n	}\n	else if ( real_obj instanceof Dict ) {\n		Klass := DictNode;\n	}\n	else if ( real_obj instanceof PairList ) {\n		Klass := PairListNode;\n	}\n	else if ( real_obj instanceof Pair ) {\n		Klass := PairNode;\n	}\n	else if ( real_obj instanceof KDLDocument ) {\n		Klass := KDLDocumentNode;\n	}\n	else if ( real_obj instanceof KDLNode ) {\n		Klass := KDLNodeNode;\n	}\n	else if ( real_obj instanceof KDLValue ) {\n		Klass := KDLValueNode;\n	}\n	else if ( _zpath_is_xml_node(real_obj) ) {\n		Klass := XmlNodeNode;\n	}\n	else if ( real_obj instanceof Time ) {\n		Klass := TimeNode;\n	}\n	else if ( Path and ( real_obj instanceof Path ) ) {\n		Klass := PathNode;\n	}\n	else if ( real_obj instanceof Object ) {\n		if ( real_obj can __zpath_node_class__ ) {\n			Klass = real_obj.__zpath_node_class__;\n		}\n	}\n\n	if ( Klass \u2261 null and _zpath_is_widget(real_obj) ) {\n		Klass := WidgetNode;\n	}\n\n	if ( Klass \u2261 null ) {\n		Klass := XmlNodeNode if _zpath_is_xml_node(real_obj);\n	}\n\n	// The dispatch probe returns a class object or null.\n	return Klass ?: Node;\n}\n';
        virtualFiles["/modules/std/path/z/operators.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/path/z/operators - Operator definitions for ZPath.\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module defines the base ZPath operator model and the standard\noperator table used by C<std/path/z>.\n\n=head1 EXPORTS\n\n=head2 Traits\n\n=over\n\n=item C<EvalHelpers>\n\nShared helpers for operator and function definitions.\n\n=over\n\n=item C<< helper.wrap(value) >>\n\nParameters: C<value> is any value. Returns: C<Array>. Wraps C<value> as\na one-item ZPath node array.\n\n=item C<< helper.wrap_for_array(value) >>\n\nParameters: C<value> is any value. Returns: C<Node>. Wraps C<value> as a\nZPath node for array results.\n\n=back\n\n=back\n\n=head2 Classes\n\n=over\n\n=item C<< Operator({ spelling: String, kind: String, precedence: Number, ... }) >>\n\nConstructs an operator definition. Returns: C<Operator>.\n\n=over\n\n=item C<< operator.is_unary() >>, C<< operator.is_binary() >>\n\nParameters: none. Returns: C<Boolean>. Reports whether the operator is\nunary or binary.\n\n=item C<< operator.requires_whitespace() >>\n\nParameters: none. Returns: C<Boolean>. Reports whether the lexer\nrequires whitespace around the operator.\n\n=item C<< operator.lexer_should_ignore() >>\n\nParameters: none. Returns: C<Boolean>. Reports whether the lexer should\nignore this operator definition.\n\n=item C<< operator.is_right_associative() >>\n\nParameters: none. Returns: C<Boolean>. Reports whether the operator is\nright associative.\n\n=item C<< operator.char_length() >>\n\nParameters: none. Returns: C<Number>. Returns the operator spelling\nlength.\n\n=item C<< operator.precedence_is(lvl) >>\n\nParameters: C<lvl> is a precedence level. Returns: C<Boolean>. Returns\ntrue when the operator has that precedence.\n\n=back\n\n=back\n\n=head2 Constants\n\n=over\n\n=item C<STANDARD_OPERATORS>\n\nType: C<Array>. Standard ZPath operator definitions.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/path/z/operators >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/path/z/node import Node;\n\nfunction _floaty_modulus ( ln, rn ) {\n	let count := floor( ln / rn ); //\n	return ln - ( count * rn );\n}\n\ntrait EvalHelpers {\n	method _handle_numeric_operand ( ev, ctx, expr ) {\n		const result := ev.eval_expr( expr, ev.nested_ctx( ctx ) );\n		return 0 unless result.length;\n		return ev.to_number( result[0] );\n	}\n\n	method _handle_stringy_operand ( ev, ctx, expr ) {\n		const result := ev.eval_expr( expr, ev.nested_ctx( ctx ) );\n		return 0 unless result.length;\n		return ev.to_number( result[0] );\n	}\n\n	method wrap ( value ) {\n		return [ Node.wrap( value ) ];\n	}\n\n	method wrap_for_array ( value ) {\n		return Node.wrap( value );\n	}\n}\n\nclass Operator with EvalHelpers {\n	let String spelling with get;\n	let String alias with get, has;\n	let String kind with get;\n	let Number precedence with get;\n	let Boolean unary      := false;\n	let Boolean require_ws := false;\n	let Boolean lex_ignore := false;\n	let Boolean right_assoc := false;\n	let Function f;\n\n	method is_unary () {\n		return unary;\n	}\n\n	method is_binary () {\n		return not unary;\n	}\n\n	method requires_whitespace () {\n		return require_ws;\n	}\n\n	method lexer_should_ignore () {\n		return lex_ignore;\n	}\n\n	method is_right_associative () {\n		return right_assoc;\n	}\n\n	method char_length () {\n		return length spelling;\n	}\n\n	method precedence_is ( lvl ) {\n		return precedence = lvl;\n	}\n}\n\nconst STANDARD_OPERATORS := [\n	new Operator(\n		spelling: "||",\n		kind: "OROR",\n		precedence: 2,\n		f: function ( op, ev, ast, ctx, left, right ) {\n			const left_val := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n			if ( left_val.length and ev.truthy( left_val[0] ) ) {\n				return op.wrap( true );\n			}\n			const right_val := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n			if ( right_val.length and ev.truthy( right_val[0] ) ) {\n				return op.wrap( true );\n			}\n			return op.wrap( false );\n		},\n	),\n\n	new Operator(\n		spelling: "&&",\n		kind: "ANDAND",\n		precedence: 4,\n		f: function ( op, ev, ast, ctx, left, right ) {\n			const left_val := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n			if ( left_val.length and ev.truthy( left_val[0] ) ) {\n				const right_val := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n				if ( right_val.length and ev.truthy( right_val[0] ) ) {\n					return op.wrap( true );\n				}\n			}\n			return op.wrap( false );\n		},\n	),\n\n	new Operator(\n		spelling: "==",\n		kind: "EQEQ",\n		precedence: 12,\n		f: function ( op, ev, ast, ctx, left, right ) {\n			const left_vals  := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n			const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n			let is_eq := false;\n\n			if ( left_vals and right_vals ) {\n				for ( let ln in left_vals ) {\n					last if is_eq;\n					for ( let rn in right_vals ) {\n						last if is_eq;\n						if ( ev.equals( ln, rn ) ) {\n							is_eq := true;\n						}\n					}\n				}\n			}\n\n			return op.wrap( is_eq );\n		},\n	),\n\n	new Operator(\n		spelling: "!=",\n		kind: "NEQ",\n		precedence: 12,\n		f: function ( op, ev, ast, ctx, left, right ) {\n			const left_vals  := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n			const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n			let is_eq := false;\n\n			if ( left_vals and right_vals ) {\n				for ( let ln in left_vals ) {\n					last if is_eq;\n					for ( let rn in right_vals ) {\n						last if is_eq;\n						if ( ev.equals( ln, rn ) ) {\n							is_eq := true;\n						}\n					}\n				}\n			}\n\n			return op.wrap( not is_eq );\n		},\n	),\n\n	new Operator(\n		spelling: ">=",\n		kind: "GE",\n		precedence: 14,\n		f: function ( op, ev, ast, ctx, left, right ) {\n			let left_val  := op._handle_numeric_operand( ev, ctx, left );\n			let right_val := op._handle_numeric_operand( ev, ctx, right );\n			if ( ( left_val \u2261 null ) or ( right_val \u2261 null ) ) {\n				left_val  := op._handle_stringy_operand( ev, ctx, left );\n				right_val := op._handle_stringy_operand( ev, ctx, right );\n				return op.wrap( left_val ge right_val );\n			}\n			return op.wrap( left_val \u2265 right_val );\n		},\n	),\n\n	new Operator(\n		spelling: "<=",\n		kind: "LE",\n		precedence: 14,\n		f: function ( op, ev, ast, ctx, left, right ) {\n			let left_val  := op._handle_numeric_operand( ev, ctx, left );\n			let right_val := op._handle_numeric_operand( ev, ctx, right );\n			if ( ( left_val \u2261 null ) or ( right_val \u2261 null ) ) {\n				left_val  := op._handle_stringy_operand( ev, ctx, left );\n				right_val := op._handle_stringy_operand( ev, ctx, right );\n				return op.wrap( left_val le right_val );\n			}\n			return op.wrap( left_val \u2264 right_val );\n		},\n	),\n\n	new Operator(\n		spelling: "+",\n		kind: "PLUS",\n		require_ws: true,\n		precedence: 16,\n		f: function ( op, ev, ast, ctx, left, right ) {\n			const left_val  := op._handle_numeric_operand( ev, ctx, left );\n			const right_val := op._handle_numeric_operand( ev, ctx, right );\n			return op.wrap( left_val + right_val );\n		},\n	),\n\n	new Operator(\n		spelling: "-",\n		kind: "MINUS",\n		require_ws: true,\n		precedence: 16,\n		f: function ( op, ev, ast, ctx, left, right ) {\n			const left_val  := op._handle_numeric_operand( ev, ctx, left );\n			const right_val := op._handle_numeric_operand( ev, ctx, right );\n			return op.wrap( left_val - right_val );\n		},\n	),\n\n	new Operator(\n		spelling: "%",\n		kind: "PCT",\n		require_ws: true,\n		precedence: 18,\n		f: function ( op, ev, ast, ctx, left, right ) {\n			const left_val  := op._handle_numeric_operand( ev, ctx, left );\n			const right_val := op._handle_numeric_operand( ev, ctx, right );\n			if ( ( left_val ~ /\\./ ) or ( right_val ~ /\\./ ) ) {\n				return op.wrap( _floaty_modulus( left_val, right_val ) );\n			}\n			return op.wrap( left_val mod right_val );\n		},\n	),\n\n	new Operator(\n		spelling: "*",\n		kind: "TIMES",\n		require_ws: true,\n		precedence: 18,\n		lex_ignore: true,\n		alias: "STAR",\n		f: function ( op, ev, ast, ctx, left, right ) {\n			const left_val  := op._handle_numeric_operand( ev, ctx, left );\n			const right_val := op._handle_numeric_operand( ev, ctx, right );\n			return op.wrap( left_val \xD7 right_val );\n		},\n	),\n\n	new Operator(\n		spelling: "/",\n		kind: "DIVIDE",\n		require_ws: true,\n		precedence: 18,\n		lex_ignore: true,\n		alias: "SLASH",\n		f: function ( op, ev, ast, ctx, left, right ) {\n			const left_val  := op._handle_numeric_operand( ev, ctx, left );\n			const right_val := op._handle_numeric_operand( ev, ctx, right );\n			return op.wrap( left_val \xF7 right_val );\n		},\n	),\n\n	new Operator(\n		spelling: "^",\n		kind: "BXOR",\n		precedence: 8,\n		f: function ( op, ev, ast, ctx, left, right ) {\n			const left_val  := op._handle_numeric_operand( ev, ctx, left );\n			const right_val := op._handle_numeric_operand( ev, ctx, right );\n			return op.wrap( left_val ^ right_val );\n		},\n	),\n\n	new Operator(\n		spelling: "&",\n		kind: "BAND",\n		precedence: 10,\n		f: function ( op, ev, ast, ctx, left, right ) {\n			const left_val  := op._handle_numeric_operand( ev, ctx, left );\n			const right_val := op._handle_numeric_operand( ev, ctx, right );\n			return op.wrap( left_val & right_val );\n		},\n	),\n\n	new Operator(\n		spelling: "|",\n		kind: "BOR",\n		precedence: 6,\n		f: function ( op, ev, ast, ctx, left, right ) {\n			const left_val  := op._handle_numeric_operand( ev, ctx, left );\n			const right_val := op._handle_numeric_operand( ev, ctx, right );\n			return op.wrap( left_val | right_val );\n		},\n	),\n\n	new Operator(\n		spelling: ">",\n		kind: "GT",\n		precedence: 14,\n		f: function ( op, ev, ast, ctx, left, right ) {\n			let left_val  := op._handle_numeric_operand( ev, ctx, left );\n			let right_val := op._handle_numeric_operand( ev, ctx, right );\n			if ( ( left_val \u2261 null ) or ( right_val \u2261 null ) ) {\n				left_val  := op._handle_stringy_operand( ev, ctx, left );\n				right_val := op._handle_stringy_operand( ev, ctx, right );\n				return op.wrap( left_val gt right_val );\n			}\n			return op.wrap( left_val > right_val );\n		},\n	),\n\n	new Operator(\n		spelling: "<",\n		kind: "LT",\n		precedence: 14,\n		f: function ( op, ev, ast, ctx, left, right ) {\n			let left_val  := op._handle_numeric_operand( ev, ctx, left );\n			let right_val := op._handle_numeric_operand( ev, ctx, right );\n			if ( ( left_val \u2261 null ) or ( right_val \u2261 null ) ) {\n				left_val  := op._handle_stringy_operand( ev, ctx, left );\n				right_val := op._handle_stringy_operand( ev, ctx, right );\n				return op.wrap( left_val le right_val );\n			}\n			return op.wrap( left_val < right_val );\n		},\n	),\n\n	new Operator(\n		spelling: "!",\n		kind: "NOT",\n		unary: true,\n		precedence: 20,\n		f: function ( op, ev, ast, ctx, expr ) {\n			const got := ev.eval_expr( expr, ctx );\n			const value := got.length() > 0 ? got[0] : null;\n			return op.wrap( not ev.truthy(value) );\n		},\n	),\n\n	new Operator(\n		spelling: "~",\n		kind: "BNOT",\n		unary: true,\n		precedence: 20,\n		f: function ( op, ev, ast, ctx, expr ) {\n			const value := op._handle_numeric_operand( ev, ctx, expr );\n			return op.wrap( ~value );\n		},\n	),\n];\n';
        virtualFiles["/modules/std/path/z/parser.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/path/z/parser - Pure Zuzu parser for ZPath expressions.\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module provides the pure-Zuzu parser used by ZPath.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<< Parser({ lexer_class?, allowed_operators }) >>\n\nConstructs a ZPath parser. Returns: C<Parser>.\n\n=over\n\n=item C<< parser.parse_top_level_terms(src) >>\n\nParameters: C<src> is a ZPath expression string. Returns: C<Array>.\nParses comma-separated top-level expression terms.\n\n=item C<< parser.parse_expression(lx) >>\n\nParameters: C<lx> is a C<Lexer>. Returns: C<Dict>. Parses an expression.\n\n=item C<< parser.parse_ternary(lx) >>\n\nParameters: C<lx> is a C<Lexer>. Returns: C<Dict>. Parses ternary and\nElvis expressions.\n\n=item C<< parser.parse_subexpression(lx, min_prec) >>\n\nParameters: C<lx> is a C<Lexer> and C<min_prec> is a precedence floor.\nReturns: C<Dict>. Parses a precedence-climbing subexpression.\n\n=item C<< parser.parse_primary(lx) >>\n\nParameters: C<lx> is a C<Lexer>. Returns: C<Dict>. Parses a primary\nexpression.\n\n=back\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/path/z/parser >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/string import trim;\nfrom std/path/z/lexer import Lexer;\n\nclass Parser {\n	let lexer_class;\n	let allowed_operators;\n	let _binop_prec := {};\n	let _unop_prec  := {};\n	let _need_ws    := {};\n	let _right_assoc := {};\n	let _path_terminators := {};\n	let _allow_elvis := false;\n\n	method __build__ () {\n		lexer_class ?:= Lexer;\n		self._init_path_terminators();\n		for ( let op in allowed_operators ) {\n			let spell := op.get_spelling();\n			if ( op.is_unary() ) {\n				_unop_prec.set( spell, op.get_precedence() );\n			}\n			else {\n				if ( op.get_kind() \u2261 "ELVIS" ) {\n					_allow_elvis := true;\n					_path_terminators.set( op.get_kind(), true );\n					next;\n				}\n				_binop_prec.set( spell, op.get_precedence() );\n				_path_terminators.set( op.get_kind(), true );\n				if ( op.has_alias() ) {\n					_path_terminators.set( op.get_alias(), true );\n				}\n				if ( op.requires_whitespace() ) {\n					_need_ws.set( spell, true );\n				}\n				if ( op.is_right_associative() ) {\n					_right_assoc.set( spell, true );\n				}\n			}\n		}\n	}\n\n	method _init_path_terminators () {\n		for ( let k in [\n			"EOF",\n			"COMMA",\n			"RPAREN",\n			"RBRACK",\n			"QMARK",\n			"COLON",\n		] ) {\n			_path_terminators.set( k, true );\n		}\n	}\n\n	method parse_top_level_terms ( src ) {\n		let terms := [];\n		let lexer := new lexer_class(\n			src:               src,\n			allowed_operators: allowed_operators,\n		);\n\n		while ( true ) {\n			let expr := self.parse_expression(lexer);\n			terms.push(expr);\n			if ( lexer.peek_kind() \u2261 "COMMA" ) {\n				lexer.next_tok();\n				next;\n			}\n			lexer.expect("EOF");\n			last;\n		}\n\n		return terms;\n	}\n\n	method _trim ( s ) {\n		return trim(s);\n	}\n\n	method parse_expression ( lx ) {\n		return self.parse_ternary(lx);\n	}\n\n	method parse_ternary ( lx ) {\n		let cond := self.parse_subexpression( lx, 1 );\n\n		if ( lx.peek_kind() \u2261 "QMARK" ) {\n			lx.next_tok();\n			let then := self.parse_expression(lx); // ZZPath should use: self.parse_subexpression( lx, 1 )\n			lx.expect("COLON");\n			let els := self.parse_expression(lx);\n			return { t: "ternary", c: cond, a: then, b: els };\n		}\n		if ( _allow_elvis and lx.peek_kind() \u2261 "ELVIS" ) {\n			lx.next_tok();\n			let fallback := self.parse_expression(lx);\n			return { t: "elvis", c: cond, b: fallback };\n		}\n\n		return cond;\n	}\n\n	method parse_subexpression ( lx, min_prec ) {\n		let left := self._parse_maybe_unary( lx, min_prec );\n\n		while ( true ) {\n			let spell := lx.peek{v};\n			let op_prec := _binop_prec.get( spell, null );\n			last if op_prec \u2261 null or op_prec < min_prec;\n\n			let op := lx.next_tok;\n			if ( _need_ws.exists( spell ) ) {\n				if ( not ( op{ws_before} and op{ws_after} ) ) {\n					die `Binary operator \'${spell}\' requires whitespace around it`;\n				}\n			}\n\n			let next_min := _right_assoc.exists(spell) ? op_prec : op_prec + 1;\n			let right := self.parse_subexpression( lx, next_min );\n			left := { t: "bin", op: spell, l: left, r: right };\n		}\n\n		return left;\n	}\n\n	method _parse_maybe_unary ( lx, min_prec ) {\n		let spell := lx.peek{v};\n		let op_prec := _unop_prec.get( spell, null );\n		if ( op_prec \u2262 null and op_prec >= min_prec ) {\n			let op := lx.next_tok{v};\n			let e  := self._parse_maybe_unary( lx, op_prec );\n			return { t: "un", op: op, e: e };\n		}\n		return self.parse_primary( lx );\n	}\n\n	method parse_primary ( lx ) {\n		let k := lx.peek_kind;\n\n		if ( k \u2261 "NUMBER" ) {\n			return { t: "num", v: lx.next_tok(){v} };\n		}\n		if ( k \u2261 "STRING" ) {\n			return { t: "str", v: lx.next_tok(){v} };\n		}\n		if ( k \u2261 "LPAREN" ) {\n			lx.next_tok();\n			let e := self.parse_expression(lx);\n			lx.expect("RPAREN");\n			return e;\n		}\n\n		if ( k \u2261 "NAME" and lx.peek_kind_n(1) \u2261 "LPAREN" ) {\n			let name := lx.next_tok(){v};\n			lx.expect("LPAREN");\n			let args := [];\n			if ( lx.peek_kind() \u2262 "RPAREN" ) {\n				args.push( self.parse_expression(lx) );\n				while ( lx.peek_kind() \u2261 "COMMA" ) {\n					lx.next_tok();\n					args.push( self.parse_expression(lx) );\n				}\n			}\n			lx.expect("RPAREN");\n			return { t: "fn", n: name, a: args };\n		}\n\n		return self._parse_path_expr(lx);\n	}\n\n	method _is_path_terminator ( k ) {\n		return _path_terminators.exists(k);\n	}\n\n	method _parse_path_expr ( lx ) {\n		let segs := [];\n\n		if ( lx.peek_kind() \u2261 "SLASH_PATH" ) {\n			lx.next_tok();\n			let root := { k: "root", q: [] };\n			segs.push(root);\n\n			if ( lx.peek_kind() \u2261 "LBRACK" ) {\n				root{q} := self._parse_qualifiers(lx);\n			}\n\n			if ( self._is_path_terminator( lx.peek_kind() ) ) {\n				return { t: "path", s: segs };\n			}\n		}\n		else if ( lx.peek_kind() \u2261 "LBRACK" ) {\n			let seg := { k: "dot", q: self._parse_qualifiers(lx) };\n			segs.push(seg);\n			if ( self._is_path_terminator( lx.peek_kind() ) ) {\n				return { t: "path", s: segs };\n			}\n		}\n\n		if (\n			lx.peek_kind() \u2262 "SLASH_PATH"\n			and not self._is_path_terminator( lx.peek_kind() )\n		) {\n			segs.push( self._parse_path_segment(lx) );\n		}\n\n		while ( lx.peek_kind() \u2261 "SLASH_PATH" ) {\n			lx.next_tok();\n			if ( lx.peek_kind() \u2261 "LBRACK" ) {\n				let seg := { k: "star", q: [] };\n				seg{q} := self._parse_qualifiers(lx);\n				segs.push(seg);\n				next;\n			}\n			segs.push( self._parse_path_segment(lx) );\n		}\n\n		return { t: "path", s: segs };\n	}\n\n	method _parse_path_segment ( lx ) {\n		let k := lx.peek_kind();\n		let seg := null;\n\n		if ( k \u2261 "DOT" ) {\n			lx.next_tok();\n			seg := { k: "dot" };\n		}\n		else if ( k \u2261 "DOTDOT" ) {\n			lx.next_tok();\n			seg := { k: "parent" };\n		}\n		else if ( k \u2261 "DOTDOTSTAR" ) {\n			lx.next_tok();\n			seg := { k: "ancestors" };\n		}\n		else if ( k \u2261 "STAR_PATH" ) {\n			lx.next_tok();\n			seg := { k: "star" };\n		}\n		else if ( k \u2261 "STARSTAR" ) {\n			lx.next_tok();\n			seg := { k: "desc" };\n		}\n		else if ( k \u2261 "INDEX" ) {\n			let i := lx.next_tok(){v};\n			seg := { k: "index", i: i };\n		}\n		else if ( k \u2261 "NUMBER" ) {\n			let i := lx.next_tok(){v};\n			seg := { k: "index", i: i };\n		}\n		else if ( k \u2261 "NAME" and lx.peek_kind_n(1) \u2261 "LPAREN" ) {\n			let name := lx.next_tok(){v};\n			lx.expect("LPAREN");\n			let args := [];\n			if ( lx.peek_kind() \u2262 "RPAREN" ) {\n				args.push( self.parse_expression(lx) );\n				while ( lx.peek_kind() \u2261 "COMMA" ) {\n					lx.next_tok();\n					args.push( self.parse_expression(lx) );\n				}\n			}\n			lx.expect("RPAREN");\n			seg := { k: "fnseg", n: name, a: args };\n		}\n		else if ( k \u2261 "NAME" ) {\n			let n := lx.next_tok(){v};\n			seg := { k: "name", n: n };\n		}\n		else {\n			die `Unexpected token in path segment: ${k}`;\n		}\n\n		if ( seg{k} \u2261 "name" and lx.peek_kind() \u2261 "INDEX" ) {\n			seg{i} := lx.next_tok(){v};\n		}\n\n		seg{q} := self._parse_qualifiers(lx);\n		return seg;\n	}\n\n	method _parse_qualifiers ( lx ) {\n		let q := [];\n\n		while ( lx.peek_kind() \u2261 "LBRACK" ) {\n			lx.next_tok();\n			let e := self.parse_expression(lx);\n			lx.expect("RBRACK");\n			q.push(e);\n		}\n\n		return q;\n	}\n}\n';
        virtualFiles["/modules/std/path/zz.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/path/zz - ZuzuScript-flavoured path selectors.\n\n=head1 SYNOPSIS\n\n  from std/path/zz import ZZPath;\n\n  let data := { users: [ { name: "Ada" } ] };\n  say( ( new ZZPath( path: "/users/#0/name" ) ).first(data) );\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module provides the public C<ZZPath> class. It currently reuses the\nZPath traversal, parser, lexer, assignment, and reference\nmachinery while routing expression operators through\nC<std/path/zz/operators> and expression functions through\nC<std/path/zz/functions>.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<ZZEvaluator>\n\nEvaluator class that supplies ZZPath operators and functions.\n\n=over\n\n=item C<< evaluator.operator_definitions() >>\n\nParameters: none. Returns: C<Array>. Returns ZZPath operator\ndefinitions.\n\n=item C<< evaluator.function_definitions() >>\n\nParameters: none. Returns: C<Array>. Returns ZZPath function\ndefinitions.\n\n=back\n\n=item C<< ZZPath({ path: String }) >>\n\nConstructs a ZZPath query object. Returns: C<ZZPath>. Inherits the\npublic query, assignment, and reference methods from C<ZPath>.\n\n=over\n\n=item C<< path.get_evaluator() >>\n\nParameters: none. Returns: C<ZZEvaluator>. Returns the evaluator used\nfor this path.\n\n=item C<< node.find(path) >>\n\nC<ZZPath> inherits from C<ZPath>, so a C<ZZPath> object can be passed to\nC<std/path/z/node> C<Node.find()>.\n\n=back\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/path/zz >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/path/z import ZPath;\nfrom std/path/z/evaluate import Evaluator as ZEvaluator;\n\nclass ZZEvaluator extends ZEvaluator {\n	method operator_definitions () {\n		from std/path/zz/operators import STANDARD_OPERATORS;\n		return STANDARD_OPERATORS;\n	}\n\n	method function_definitions () {\n		from std/path/zz/functions import STANDARD_FUNCTIONS;\n		return STANDARD_FUNCTIONS;\n	}\n}\n\nclass ZZPath extends ZPath {\n	method get_evaluator () {\n		return new ZZEvaluator();\n	}\n}\n';
        virtualFiles["/modules/std/path/zz/functions.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/path/zz/functions - Function definitions for ZZPath expressions.\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module extends the base ZPath function table with\nZuzuScript-flavoured path expression helpers.\n\n=head1 EXPORTS\n\n=head2 Constants\n\n=over\n\n=item C<STANDARD_FUNCTION_NAMES>\n\nType: C<Array>. Names of inherited ZPath functions available to ZZPath.\n\n=item C<STANDARD_FUNCTIONS>\n\nType: C<Array>. Complete ZZPath function definition table.\n\n=back\n\n=head2 Functions\n\n=over\n\n=item C<< first_arg_node(name, ev, ctx, args) >>\n\nParameters: function name, evaluator, context, and argument AST nodes.\nReturns: C<Node> or C<null>. Resolves the first argument or current\ncontext node.\n\n=item C<< first_number_arg(name, ev, ctx, args) >>, C<< nth_number_arg(name, ev, ctx, args, i) >>\n\nParameters: function name, evaluator, context, arguments, and optional\nindex. Returns: C<Number>. Resolves an argument as a number.\n\n=item C<< first_string_arg(name, ev, ctx, args) >>, C<< nth_string_arg(name, ev, ctx, args, i) >>\n\nParameters: function name, evaluator, context, arguments, and optional\nindex. Returns: C<String>. Resolves an argument as a string.\n\n=item C<< nth_value_arg(name, ev, ctx, args, i) >>\n\nParameters: function name, evaluator, context, arguments, and index.\nReturns: value. Resolves an argument as a primitive value.\n\n=item C<< nth_array_arg(name, ev, ctx, args, i) >>\n\nParameters: function name, evaluator, context, arguments, and index.\nReturns: C<Array>. Resolves an argument as an array value.\n\n=item C<< number_args(ev, ctx, args) >>\n\nParameters: evaluator, context, and argument AST nodes. Returns:\nC<Array>. Resolves all arguments as numbers.\n\n=item C<< first_arg_value(name, ev, ctx, args) >>\n\nParameters: function name, evaluator, context, and arguments. Returns:\nvalue. Resolves the first argument as a primitive value.\n\n=item C<< z_function(spelling) >>\n\nParameters: C<spelling> is a base ZPath function name. Returns:\nC<Function>. Returns the inherited function implementation.\n\n=item C<< string_index_of(funk, ev, ast, ctx, args) >>\n\nParameters: standard ZPath function callback arguments. Returns:\nC<Array>. Implements string C<index-of>.\n\n=item C<< string_rindex(funk, ev, ast, ctx, args) >>\n\nParameters: standard ZPath function callback arguments. Returns:\nC<Array>. Implements string reverse-index lookup.\n\n=item C<< defined_function(funk, ev, ast, ctx, args) >>\n\nParameters: standard ZPath function callback arguments. Returns:\nC<Array>. Implements defined-value testing.\n\n=item C<< empty_function(funk, ev, ast, ctx, args) >>\n\nParameters: standard ZPath function callback arguments. Returns:\nC<Array>. Implements empty-value testing.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/path/zz/functions >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/path/z/functions import Func, STANDARD_FUNCTIONS as Z_STANDARD_FUNCTIONS;\n\n\nconst STANDARD_FUNCTION_NAMES := [\n	"true",\n	"false",\n	"null",\n	"tag",\n	"url",\n	"local-name",\n	"key",\n	"value",\n	"index",\n	"count",\n	"is-first",\n	"is-last",\n	"next",\n	"prev",\n];\n\nfunction first_arg_node ( name, ev, ctx, args ) {\n	if ( args.length() = 0 ) {\n		return ctx.nodeset.get( 0, null );\n	}\n	if ( args.length() = 1 ) {\n		const got := ev.eval_expr( args[0], ev.nested_ctx( ctx ) );\n		return got.get( 0, null );\n	}\n	die `Too many arguments for ${name}()`;\n}\n\nfunction first_number_arg ( name, ev, ctx, args ) {\n	const node := first_arg_node( name, ev, ctx, args );\n	// Numeric coercion may produce 0; only null falls back.\n	return ev.to_number(node) ?: 0;\n}\n\nfunction nth_number_arg ( name, ev, ctx, args, i ) {\n	die `Not enough arguments for ${name}()` if args.length() <= i;\n	const got := ev.eval_expr( args[i], ev.nested_ctx( ctx ) );\n	// Numeric coercion may produce 0; only null falls back.\n	return ev.to_number( got.get( 0, null ) ) ?: 0;\n}\n\nfunction nth_string_arg ( name, ev, ctx, args, i ) {\n	die `Not enough arguments for ${name}()` if args.length() <= i;\n	const got := ev.eval_expr( args[i], ev.nested_ctx( ctx ) );\n	const value := ev.to_string( got.get( 0, null ) );\n	return value \u2261 null ? "" : "" _ value;\n}\n\nfunction nth_value_arg ( name, ev, ctx, args, i ) {\n	die `Not enough arguments for ${name}()` if args.length() <= i;\n	const got := ev.eval_expr( args[i], ev.nested_ctx( ctx ) );\n	const node := got.get( 0, null );\n	return node \u2261 null ? null : node.primitive_value();\n}\n\nfunction nth_array_arg ( name, ev, ctx, args, i ) {\n	die `Not enough arguments for ${name}()` if args.length() <= i;\n	const got := ev.eval_expr( args[i], ev.nested_ctx( ctx ) );\n	if ( got.length() = 1 ) {\n		const one := got[0].primitive_value();\n		return one if one instanceof Array;\n	}\n	return got.map( fn node \u2192 node.primitive_value() );\n}\n\nfunction number_args ( ev, ctx, args ) {\n	let nums := [];\n	if ( args.length() = 0 ) {\n		for ( let node in ctx.nodeset ) {\n			const value := ev.to_number(node);\n			nums.push(value) if value instanceof Number;\n		}\n		return nums;\n	}\n	for ( let arg in args ) {\n		const got := ev.eval_expr( arg, ev.nested_ctx( ctx ) );\n		for ( let node in got ) {\n			const value := ev.to_number(node);\n			nums.push(value) if value instanceof Number;\n		}\n	}\n	return nums;\n}\n\nfunction first_string_arg ( name, ev, ctx, args ) {\n	const node := first_arg_node( name, ev, ctx, args );\n	const value := ev.to_string(node);\n	return value \u2261 null ? "" : "" _ value;\n}\n\nfunction first_arg_value ( name, ev, ctx, args ) {\n	const node := first_arg_node( name, ev, ctx, args );\n	return node \u2261 null ? null : node.primitive_value();\n}\n\nfunction z_function ( spelling ) {\n	const func := Z_STANDARD_FUNCTIONS.first( fn f \u2192 f.has_name(spelling) );\n	die `std/path/z/functions is missing ${spelling}()` if func \u2261 null;\n	return func;\n}\n\nfunction string_index_of ( funk, ev, ast, ctx, args ) {\n	from std/string import index;\n	die "Too many arguments for index-of()" if args.length() > 3;\n	if ( args.length() = 2 ) {\n		return funk.wrap( index(\n			nth_string_arg( "index-of", ev, ctx, args, 0 ),\n			nth_string_arg( "index-of", ev, ctx, args, 1 ),\n		) );\n	}\n	return funk.wrap( index(\n		nth_string_arg( "index-of", ev, ctx, args, 0 ),\n		nth_string_arg( "index-of", ev, ctx, args, 1 ),\n		nth_number_arg( "index-of", ev, ctx, args, 2 ),\n	) );\n}\n\nfunction string_rindex ( funk, ev, ast, ctx, args ) {\n	from std/string import rindex;\n	const name := funk.get_spelling;\n	die `Too many arguments for ${name}()` if args.length() > 3;\n	if ( args.length() = 2 ) {\n		return funk.wrap( rindex(\n			nth_string_arg( name, ev, ctx, args, 0 ),\n			nth_string_arg( name, ev, ctx, args, 1 ),\n		) );\n	}\n	return funk.wrap( rindex(\n		nth_string_arg( name, ev, ctx, args, 0 ),\n		nth_string_arg( name, ev, ctx, args, 1 ),\n		nth_number_arg( name, ev, ctx, args, 2 ),\n	) );\n}\n\nfunction defined_function ( funk, ev, ast, ctx, args ) {\n	const node := first_arg_node( "defined", ev, ctx, args );\n	return funk.wrap( node \u2262 null and node.primitive_value() \u2262 null );\n}\n\nfunction empty_function ( funk, ev, ast, ctx, args ) {\n	const value := first_arg_value( "empty", ev, ctx, args );\n	return funk.wrap( true ) if value \u2261 null;\n\n	if (\n		value instanceof Array or\n		value instanceof Bag or\n		value instanceof Set or\n		value instanceof Dict or\n		value instanceof PairList\n	) {\n		return funk.wrap( value.length() = 0 );\n	}\n\n	die `empty() expects a Collection or null, got ${typeof value}`;\n}\n\n// Start with a base of functions inherited from ZPath:\nconst STANDARD_FUNCTIONS := STANDARD_FUNCTION_NAMES.map( fn n \u2192 z_function(n) );\n\n// Add equivalents for ZuzuScript word-like unary operators:\nSTANDARD_FUNCTIONS.push(\n	new Func(\n		spelling: "abs",\n		f: function ( funk, ev, ast, ctx, args ) {\n			return funk.wrap( abs first_number_arg( "abs", ev, ctx, args ) );\n		},\n	),\n	new Func(\n		spelling: "floor",\n		f: function ( funk, ev, ast, ctx, args ) {\n			return funk.wrap( floor first_number_arg( "floor", ev, ctx, args ) );\n		},\n	),\n	new Func(\n		spelling: "ceil",\n		f: function ( funk, ev, ast, ctx, args ) {\n			return funk.wrap( ceil first_number_arg( "ceil", ev, ctx, args ) );\n		},\n	),\n	new Func(\n		spelling: "round",\n		f: function ( funk, ev, ast, ctx, args ) {\n			return funk.wrap( round first_number_arg( "round", ev, ctx, args ) );\n		},\n	),\n	new Func(\n		spelling: "int",\n		f: function ( funk, ev, ast, ctx, args ) {\n			return funk.wrap( int first_number_arg( "int", ev, ctx, args ) );\n		},\n	),\n	new Func(\n		spelling: "sqrt",\n		f: function ( funk, ev, ast, ctx, args ) {\n			return funk.wrap( sqrt first_number_arg( "sqrt", ev, ctx, args ) );\n		},\n	),\n	new Func(\n		spelling: "uc",\n		f: function ( funk, ev, ast, ctx, args ) {\n			return funk.wrap( uc first_string_arg( "uc", ev, ctx, args ) );\n		},\n	),\n	new Func(\n		spelling: "lc",\n		f: function ( funk, ev, ast, ctx, args ) {\n			return funk.wrap( lc first_string_arg( "lc", ev, ctx, args ) );\n		},\n	),\n	new Func(\n		spelling: "length",\n		f: function ( funk, ev, ast, ctx, args ) {\n			return funk.wrap( length first_string_arg( "length", ev, ctx, args ) );\n		},\n	),\n	new Func(\n		spelling: "not",\n		f: function ( funk, ev, ast, ctx, args ) {\n			const node := first_arg_node( "not", ev, ctx, args );\n			return funk.wrap( not ev.truthy(node) );\n		},\n	),\n	new Func(\n		spelling: "typeof",\n		f: function ( funk, ev, ast, ctx, args ) {\n			const node := first_arg_node( "typeof", ev, ctx, args );\n			const value := node \u2261 null ? null : node.primitive_value();\n			return funk.wrap( typeof value );\n		},\n	),\n	new Func(\n		spelling: "defined",\n		f: defined_function,\n	),\n	new Func(\n		spelling: "empty",\n		f: empty_function,\n	),\n);\n\n// Functions from std/internals:\nSTANDARD_FUNCTIONS.push(\n	new Func(\n		spelling: "string",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/internals import to_String;\n			return funk.wrap( to_String( first_arg_value(\n				"string",\n				ev,\n				ctx,\n				args,\n			) ) );\n		},\n	),\n	new Func(\n		spelling: "number",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/internals import to_Number;\n			return funk.wrap( to_Number( first_arg_value(\n				"number",\n				ev,\n				ctx,\n				args,\n			) ) );\n		},\n	),\n	new Func(\n		spelling: "boolean",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/internals import to_Boolean;\n			return funk.wrap( to_Boolean( first_arg_value(\n				"boolean",\n				ev,\n				ctx,\n				args,\n			) ) );\n		},\n	),\n	new Func(\n		spelling: "regexp",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/internals import to_Regexp;\n			return funk.wrap( to_Regexp( first_arg_value(\n				"regexp",\n				ev,\n				ctx,\n				args,\n			) ) );\n		},\n	),\n);\n\n// Functions from std/math:\nSTANDARD_FUNCTIONS.push(\n	new Func(\n		spelling: "sum",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/math import Math;\n			return funk.wrap( Math.sum( number_args( ev, ctx, args ) ) );\n		},\n	),\n	new Func(\n		spelling: "min",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/math import Math;\n			return funk.wrap( Math.min( number_args( ev, ctx, args ) ) );\n		},\n	),\n	new Func(\n		spelling: "max",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/math import Math;\n			return funk.wrap( Math.max( number_args( ev, ctx, args ) ) );\n		},\n	),\n	new Func(\n		spelling: "clamp",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/math import Math;\n			die "Too many arguments for clamp()" if args.length() > 3;\n			return funk.wrap( Math.clamp(\n				nth_number_arg( "clamp", ev, ctx, args, 0 ),\n				nth_number_arg( "clamp", ev, ctx, args, 1 ),\n				nth_number_arg( "clamp", ev, ctx, args, 2 ),\n			) );\n		},\n	),\n);\n\n// Functions from std/string:\nSTANDARD_FUNCTIONS.push(\n	new Func(\n		spelling: "substr",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import substr;\n			die "Too many arguments for substr()" if args.length() > 3;\n			if ( args.length() = 2 ) {\n				return funk.wrap( substr(\n					nth_string_arg( "substr", ev, ctx, args, 0 ),\n					nth_number_arg( "substr", ev, ctx, args, 1 ),\n				) );\n			}\n			return funk.wrap( substr(\n				nth_string_arg( "substr", ev, ctx, args, 0 ),\n				nth_number_arg( "substr", ev, ctx, args, 1 ),\n				nth_number_arg( "substr", ev, ctx, args, 2 ),\n			) );\n		},\n	),\n	new Func(\n		spelling: "index-of",\n		f: string_index_of,\n	),\n	new Func(\n		spelling: "rindex",\n		f: string_rindex,\n	),\n	new Func(\n		spelling: "last-index-of",\n		f: string_rindex,\n	),\n	new Func(\n		spelling: "contains",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import contains;\n			die "Too many arguments for contains()" if args.length() > 2;\n			return funk.wrap( contains(\n				nth_string_arg( "contains", ev, ctx, args, 0 ),\n				nth_string_arg( "contains", ev, ctx, args, 1 ),\n			) );\n		},\n	),\n	new Func(\n		spelling: "chr",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import chr;\n			die "Too many arguments for chr()" if args.length() > 1;\n			return funk.wrap( chr( nth_number_arg(\n				"chr",\n				ev,\n				ctx,\n				args,\n				0,\n			) ) );\n		},\n	),\n	new Func(\n		spelling: "ord",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import ord;\n			die "Too many arguments for ord()" if args.length() > 2;\n			if ( args.length() = 1 ) {\n				return funk.wrap( ord( nth_string_arg(\n					"ord",\n					ev,\n					ctx,\n					args,\n					0,\n				) ) );\n			}\n			return funk.wrap( ord(\n				nth_string_arg( "ord", ev, ctx, args, 0 ),\n				nth_number_arg( "ord", ev, ctx, args, 1 ),\n			) );\n		},\n	),\n	new Func(\n		spelling: "replace",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import replace;\n			die "Too many arguments for replace()" if args.length() > 4;\n			if ( args.length() = 3 ) {\n				return funk.wrap( replace(\n					nth_string_arg( "replace", ev, ctx, args, 0 ),\n					nth_value_arg( "replace", ev, ctx, args, 1 ),\n					nth_string_arg( "replace", ev, ctx, args, 2 ),\n				) );\n			}\n			return funk.wrap( replace(\n				nth_string_arg( "replace", ev, ctx, args, 0 ),\n				nth_value_arg( "replace", ev, ctx, args, 1 ),\n				nth_string_arg( "replace", ev, ctx, args, 2 ),\n				nth_string_arg( "replace", ev, ctx, args, 3 ),\n			) );\n		},\n	),\n	new Func(\n		spelling: "search",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import search;\n			die "Too many arguments for search()" if args.length() > 3;\n			if ( args.length() = 2 ) {\n				return funk.wrap( search(\n					nth_string_arg( "search", ev, ctx, args, 0 ),\n					nth_value_arg( "search", ev, ctx, args, 1 ),\n				) );\n			}\n			return funk.wrap( search(\n				nth_string_arg( "search", ev, ctx, args, 0 ),\n				nth_value_arg( "search", ev, ctx, args, 1 ),\n				nth_string_arg( "search", ev, ctx, args, 2 ),\n			) );\n		},\n	),\n	new Func(\n		spelling: "starts_with",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import starts_with;\n			die "Too many arguments for starts_with()" if args.length() > 2;\n			return funk.wrap( starts_with(\n				nth_string_arg( "starts_with", ev, ctx, args, 0 ),\n				nth_string_arg( "starts_with", ev, ctx, args, 1 ),\n			) );\n		},\n	),\n	new Func(\n		spelling: "ends_with",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import ends_with;\n			die "Too many arguments for ends_with()" if args.length() > 2;\n			return funk.wrap( ends_with(\n				nth_string_arg( "ends_with", ev, ctx, args, 0 ),\n				nth_string_arg( "ends_with", ev, ctx, args, 1 ),\n			) );\n		},\n	),\n	new Func(\n		spelling: "matches",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import matches;\n			die "Too many arguments for matches()" if args.length() > 3;\n			if ( args.length() = 2 ) {\n				return funk.wrap( matches(\n					nth_string_arg( "matches", ev, ctx, args, 0 ),\n					nth_value_arg( "matches", ev, ctx, args, 1 ),\n				) );\n			}\n			return funk.wrap( matches(\n				nth_string_arg( "matches", ev, ctx, args, 0 ),\n				nth_value_arg( "matches", ev, ctx, args, 1 ),\n				nth_string_arg( "matches", ev, ctx, args, 2 ),\n			) );\n		},\n	),\n	new Func(\n		spelling: "pattern_to_regexp",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import pattern_to_regexp;\n			die "Too many arguments for pattern_to_regexp()"\n				if args.length() > 2;\n			if ( args.length() = 1 ) {\n				return funk.wrap( pattern_to_regexp(\n					nth_string_arg( "pattern_to_regexp", ev, ctx, args, 0 ),\n				) );\n			}\n			return funk.wrap( pattern_to_regexp(\n				nth_string_arg( "pattern_to_regexp", ev, ctx, args, 0 ),\n				nth_value_arg( "pattern_to_regexp", ev, ctx, args, 1 ),\n			) );\n		},\n	),\n	new Func(\n		spelling: "quotemeta",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import quotemeta;\n			die "Too many arguments for quotemeta()" if args.length() > 1;\n			return funk.wrap( quotemeta(\n				nth_string_arg( "quotemeta", ev, ctx, args, 0 ),\n			) );\n		},\n	),\n	new Func(\n		spelling: "sprint",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import sprint;\n			die "Not enough arguments for sprint()" if args.length() = 0;\n			die "Too many arguments for sprint()" if args.length() > 8;\n\n			const fmt := nth_string_arg( "sprint", ev, ctx, args, 0 );\n			if ( args.length() = 1 ) {\n				return funk.wrap( sprint(fmt) );\n			}\n			if ( args.length() = 2 ) {\n				return funk.wrap( sprint(\n					fmt,\n					nth_value_arg( "sprint", ev, ctx, args, 1 ),\n				) );\n			}\n			if ( args.length() = 3 ) {\n				return funk.wrap( sprint(\n					fmt,\n					nth_value_arg( "sprint", ev, ctx, args, 1 ),\n					nth_value_arg( "sprint", ev, ctx, args, 2 ),\n				) );\n			}\n			if ( args.length() = 4 ) {\n				return funk.wrap( sprint(\n					fmt,\n					nth_value_arg( "sprint", ev, ctx, args, 1 ),\n					nth_value_arg( "sprint", ev, ctx, args, 2 ),\n					nth_value_arg( "sprint", ev, ctx, args, 3 ),\n				) );\n			}\n			if ( args.length() = 5 ) {\n				return funk.wrap( sprint(\n					fmt,\n					nth_value_arg( "sprint", ev, ctx, args, 1 ),\n					nth_value_arg( "sprint", ev, ctx, args, 2 ),\n					nth_value_arg( "sprint", ev, ctx, args, 3 ),\n					nth_value_arg( "sprint", ev, ctx, args, 4 ),\n				) );\n			}\n			if ( args.length() = 6 ) {\n				return funk.wrap( sprint(\n					fmt,\n					nth_value_arg( "sprint", ev, ctx, args, 1 ),\n					nth_value_arg( "sprint", ev, ctx, args, 2 ),\n					nth_value_arg( "sprint", ev, ctx, args, 3 ),\n					nth_value_arg( "sprint", ev, ctx, args, 4 ),\n					nth_value_arg( "sprint", ev, ctx, args, 5 ),\n				) );\n			}\n			if ( args.length() = 7 ) {\n				return funk.wrap( sprint(\n					fmt,\n					nth_value_arg( "sprint", ev, ctx, args, 1 ),\n					nth_value_arg( "sprint", ev, ctx, args, 2 ),\n					nth_value_arg( "sprint", ev, ctx, args, 3 ),\n					nth_value_arg( "sprint", ev, ctx, args, 4 ),\n					nth_value_arg( "sprint", ev, ctx, args, 5 ),\n					nth_value_arg( "sprint", ev, ctx, args, 6 ),\n				) );\n			}\n			return funk.wrap( sprint(\n				fmt,\n				nth_value_arg( "sprint", ev, ctx, args, 1 ),\n				nth_value_arg( "sprint", ev, ctx, args, 2 ),\n				nth_value_arg( "sprint", ev, ctx, args, 3 ),\n				nth_value_arg( "sprint", ev, ctx, args, 4 ),\n				nth_value_arg( "sprint", ev, ctx, args, 5 ),\n				nth_value_arg( "sprint", ev, ctx, args, 6 ),\n				nth_value_arg( "sprint", ev, ctx, args, 7 ),\n			) );\n		},\n	),\n	new Func(\n		spelling: "split",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import split;\n			die "Too many arguments for split()" if args.length() > 3;\n			if ( args.length() = 2 ) {\n				return funk.wrap( split(\n					nth_string_arg( "split", ev, ctx, args, 0 ),\n					nth_value_arg( "split", ev, ctx, args, 1 ),\n				) );\n			}\n			return funk.wrap( split(\n				nth_string_arg( "split", ev, ctx, args, 0 ),\n				nth_value_arg( "split", ev, ctx, args, 1 ),\n				nth_number_arg( "split", ev, ctx, args, 2 ),\n			) );\n		},\n	),\n	new Func(\n		spelling: "join",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import join;\n			die "Too many arguments for join()" if args.length() > 2;\n			return funk.wrap( join(\n				nth_string_arg( "join", ev, ctx, args, 0 ),\n				nth_array_arg( "join", ev, ctx, args, 1 ),\n			) );\n		},\n	),\n	new Func(\n		spelling: "trim",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import trim;\n			die "Too many arguments for trim()" if args.length() > 1;\n			return funk.wrap( trim( first_string_arg(\n				"trim",\n				ev,\n				ctx,\n				args,\n			) ) );\n		},\n	),\n	new Func(\n		spelling: "pad",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import pad;\n			die "Too many arguments for pad()" if args.length() > 4;\n			if ( args.length() = 2 ) {\n				return funk.wrap( pad(\n					nth_string_arg( "pad", ev, ctx, args, 0 ),\n					nth_number_arg( "pad", ev, ctx, args, 1 ),\n				) );\n			}\n			if ( args.length() = 3 ) {\n				return funk.wrap( pad(\n					nth_string_arg( "pad", ev, ctx, args, 0 ),\n					nth_number_arg( "pad", ev, ctx, args, 1 ),\n					nth_string_arg( "pad", ev, ctx, args, 2 ),\n				) );\n			}\n			return funk.wrap( pad(\n				nth_string_arg( "pad", ev, ctx, args, 0 ),\n				nth_number_arg( "pad", ev, ctx, args, 1 ),\n				nth_string_arg( "pad", ev, ctx, args, 2 ),\n				nth_string_arg( "pad", ev, ctx, args, 3 ),\n			) );\n		},\n	),\n	new Func(\n		spelling: "chomp",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import chomp;\n			die "Too many arguments for chomp()" if args.length() > 1;\n			return funk.wrap( chomp( first_string_arg(\n				"chomp",\n				ev,\n				ctx,\n				args,\n			) ) );\n		},\n	),\n	new Func(\n		spelling: "title",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import title;\n			die "Too many arguments for title()" if args.length() > 1;\n			return funk.wrap( title( first_string_arg(\n				"title",\n				ev,\n				ctx,\n				args,\n			) ) );\n		},\n	),\n	new Func(\n		spelling: "snake",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import snake;\n			die "Too many arguments for snake()" if args.length() > 1;\n			return funk.wrap( snake( first_string_arg(\n				"snake",\n				ev,\n				ctx,\n				args,\n			) ) );\n		},\n	),\n	new Func(\n		spelling: "kebab",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import kebab;\n			die "Too many arguments for kebab()" if args.length() > 1;\n			return funk.wrap( kebab( first_string_arg(\n				"kebab",\n				ev,\n				ctx,\n				args,\n			) ) );\n		},\n	),\n	new Func(\n		spelling: "camel",\n		f: function ( funk, ev, ast, ctx, args ) {\n			from std/string import camel;\n			die "Too many arguments for camel()" if args.length() > 1;\n			return funk.wrap( camel( first_string_arg(\n				"camel",\n				ev,\n				ctx,\n				args,\n			) ) );\n		},\n	),\n);\n';
        virtualFiles["/modules/std/path/zz/operators.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/path/zz/operators - Operator definitions for ZZPath expressions.\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module extends the base ZPath operator model with\nZuzuScript-flavoured expression operators.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<Operator>\n\nZZPath operator class extending C<std/path/z/operators> C<Operator>.\n\n=back\n\n=head2 Functions\n\n=over\n\n=item C<< string_operand(ev, ctx, expr) >>, C<< string_operands(ev, ctx, left, right) >>\n\nParameters: evaluator, context, and expression AST nodes. Returns:\nC<String> or C<Array>. Evaluates one or two operands as strings.\n\n=item C<< first_eval_value(values) >>, C<< primitive_eval_value(values) >>\n\nParameters: C<values> is an evaluated node array. Returns: value.\nExtracts the first or primitive value used by ZZPath operators.\n\n=item C<< collection_operand(ev, ctx, expr) >>\n\nParameters: evaluator, context, and expression AST node. Returns:\ncollection value. Evaluates an operand for collection operators.\n\n=item C<< builtin_can(value, method_name) >>\n\nParameters: C<value> is any value and C<method_name> is a method name.\nReturns: C<Boolean>. Tests whether built-in values support a method.\n\n=back\n\n=head2 Constants\n\n=over\n\n=item C<STANDARD_OPERATORS>\n\nType: C<Array>. Complete ZZPath operator definition table.\n\n=item C<logical_negation>, C<logical_and>, C<logical_nand>, C<logical_butnot>, C<logical_xor>, C<logical_nor>, C<logical_xnor>, C<logical_onlyif>, C<logical_or>, C<logical_and_value>, C<logical_nand_value>, C<logical_butnot_value>, C<logical_xor_value>, C<logical_nor_value>, C<logical_xnor_value>, C<logical_onlyif_value>, C<logical_or_value>\n\nType: C<Function>. Logical operator implementations.\n\n=item C<numeric_power>, C<numeric_multiplication>, C<numeric_division>, C<numeric_modulus>, C<numeric_addition>, C<numeric_subtraction>, C<numeric_left_shift>, C<numeric_right_shift>, C<numeric_equality>, C<numeric_inequality>, C<numeric_less_than>, C<numeric_greater_than>, C<numeric_less_than_or_equal>, C<numeric_greater_than_or_equal>, C<numeric_compare>, C<numeric_divides>, C<numeric_not_divides>\n\nType: C<Function>. Numeric operator implementations.\n\n=item C<string_concatenation>, C<string_equality>, C<string_inequality>, C<string_greater_than>, C<string_greater_than_or_equal>, C<string_less_than>, C<string_less_than_or_equal>, C<string_compare>, C<string_equality_insensitive>, C<string_inequality_insensitive>, C<string_greater_than_insensitive>, C<string_greater_than_or_equal_insensitive>, C<string_less_than_insensitive>, C<string_less_than_or_equal_insensitive>, C<string_compare_insensitive>\n\nType: C<Function>. String operator implementations.\n\n=item C<regexp_match>, C<bitwise_and>, C<bitwise_xor>, C<bitwise_or>, C<set_union>, C<set_intersection>, C<set_difference>, C<collection_membership>, C<collection_non_membership>, C<set_subsetof>, C<set_supersetof>, C<set_equivalentof>, C<type_aware_equality>, C<type_aware_inequality>, C<object_can>\n\nType: C<Function>. Regular expression, bitwise, collection, type-aware,\nand object capability operator implementations.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/path/zz/operators >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/path/z/operators import Operator as ZOperator;\n\n\nclass Operator extends ZOperator;\n\nconst logical_negation := function ( op, ev, ast, ctx, expr ) {\n	const got := ev.eval_expr( expr, ev.nested_ctx( ctx ) );\n	const value := got.length() > 0 ? got[0] : null;\n	return op.wrap( not ev.truthy(value) );\n};\n\nconst numeric_power := function ( op, ev, ast, ctx, left, right ) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val ** right_val );\n};\n\nconst numeric_multiplication := function ( op, ev, ast, ctx, left, right ) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val \xD7 right_val );\n};\n\nconst numeric_division := function ( op, ev, ast, ctx, left, right ) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val \xF7 right_val );\n};\n\nconst numeric_modulus := function ( op, ev, ast, ctx, left, right ) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val mod right_val );\n};\n\nconst numeric_left_shift := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	const first := left_vals.length() > 0 ? left_vals[0] : null;\n	const left_val := first \u2261 null ? null : first.primitive_value();\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val \xAB right_val );\n};\n\nconst numeric_right_shift := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	const first := left_vals.length() > 0 ? left_vals[0] : null;\n	const left_val := first \u2261 null ? null : first.primitive_value();\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val \xBB right_val );\n};\n\nconst numeric_addition := function ( op, ev, ast, ctx, left, right ) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val + right_val );\n};\n\nconst numeric_subtraction := function ( op, ev, ast, ctx, left, right ) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val - right_val );\n};\n\nconst numeric_equality := function ( op, ev, ast, ctx, left, right ) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val = right_val );\n};\n\nconst numeric_inequality := function ( op, ev, ast, ctx, left, right ) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val \u2260 right_val );\n};\n\nconst numeric_less_than := function ( op, ev, ast, ctx, left, right ) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val < right_val );\n};\n\nconst numeric_greater_than := function ( op, ev, ast, ctx, left, right ) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val > right_val );\n};\n\nconst numeric_less_than_or_equal := function (\n	op,\n	ev,\n	ast,\n	ctx,\n	left,\n	right,\n) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val \u2264 right_val );\n};\n\nconst numeric_greater_than_or_equal := function (\n	op,\n	ev,\n	ast,\n	ctx,\n	left,\n	right,\n) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val \u2265 right_val );\n};\n\nconst numeric_compare := function ( op, ev, ast, ctx, left, right ) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val <=> right_val );\n};\n\nconst numeric_divides := function ( op, ev, ast, ctx, left, right ) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( right_val mod left_val = 0 );\n};\n\nconst numeric_not_divides := function ( op, ev, ast, ctx, left, right ) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( right_val mod left_val );\n};\n\nfunction string_operand ( ev, ctx, expr ) {\n	const result := ev.eval_expr( expr, ev.nested_ctx( ctx ) );\n	return "" unless result.length;\n	const value := ev.to_string( result[0] );\n	return value \u2261 null ? "" : "" _ value;\n}\n\nfunction string_operands ( ev, ctx, left, right ) {\n	return [\n		string_operand( ev, ctx, left ),\n		string_operand( ev, ctx, right ),\n	];\n}\n\nconst string_concatenation := function ( op, ev, ast, ctx, left, right ) {\n	const values := string_operands( ev, ctx, left, right );\n	return op.wrap( values[0] _ values[1] );\n};\n\nconst string_equality := function ( op, ev, ast, ctx, left, right ) {\n	const values := string_operands( ev, ctx, left, right );\n	return op.wrap( values[0] eq values[1] );\n};\n\nconst string_inequality := function ( op, ev, ast, ctx, left, right ) {\n	const values := string_operands( ev, ctx, left, right );\n	return op.wrap( values[0] ne values[1] );\n};\n\nconst string_greater_than := function ( op, ev, ast, ctx, left, right ) {\n	const values := string_operands( ev, ctx, left, right );\n	return op.wrap( values[0] gt values[1] );\n};\n\nconst string_greater_than_or_equal := function ( op, ev, ast, ctx, left, right ) {\n	const values := string_operands( ev, ctx, left, right );\n	return op.wrap( values[0] ge values[1] );\n};\n\nconst string_less_than := function ( op, ev, ast, ctx, left, right ) {\n	const values := string_operands( ev, ctx, left, right );\n	return op.wrap( values[0] lt values[1] );\n};\n\nconst string_less_than_or_equal := function ( op, ev, ast, ctx, left, right ) {\n	const values := string_operands( ev, ctx, left, right );\n	return op.wrap( values[0] le values[1] );\n};\n\nconst string_compare := function ( op, ev, ast, ctx, left, right ) {\n	const values := string_operands( ev, ctx, left, right );\n	return op.wrap( values[0] cmp values[1] );\n};\n\nconst string_equality_insensitive := function ( op, ev, ast, ctx, left, right ) {\n	const values := string_operands( ev, ctx, left, right );\n	const left_val := lc values[0];\n	const right_val := lc values[1];\n	return op.wrap( left_val eq right_val );\n};\n\nconst string_inequality_insensitive := function ( op, ev, ast, ctx, left, right ) {\n	const values := string_operands( ev, ctx, left, right );\n	const left_val := lc values[0];\n	const right_val := lc values[1];\n	return op.wrap( left_val ne right_val );\n};\n\nconst string_greater_than_insensitive := function ( op, ev, ast, ctx, left, right ) {\n	const values := string_operands( ev, ctx, left, right );\n	const left_val := lc values[0];\n	const right_val := lc values[1];\n	return op.wrap( left_val gt right_val );\n};\n\nconst string_greater_than_or_equal_insensitive := function (\n	op,\n	ev,\n	ast,\n	ctx,\n	left,\n	right,\n) {\n	const values := string_operands( ev, ctx, left, right );\n	const left_val := lc values[0];\n	const right_val := lc values[1];\n	return op.wrap( left_val ge right_val );\n};\n\nconst string_less_than_insensitive := function ( op, ev, ast, ctx, left, right ) {\n	const values := string_operands( ev, ctx, left, right );\n	const left_val := lc values[0];\n	const right_val := lc values[1];\n	return op.wrap( left_val lt right_val );\n};\n\nconst string_less_than_or_equal_insensitive := function (\n	op,\n	ev,\n	ast,\n	ctx,\n	left,\n	right,\n) {\n	const values := string_operands( ev, ctx, left, right );\n	const left_val := lc values[0];\n	const right_val := lc values[1];\n	return op.wrap( left_val le right_val );\n};\n\nconst string_compare_insensitive := function ( op, ev, ast, ctx, left, right ) {\n	const values := string_operands( ev, ctx, left, right );\n	const left_val := lc values[0];\n	const right_val := lc values[1];\n	return op.wrap( left_val cmp right_val );\n};\n\nconst regexp_match := function ( op, ev, ast, ctx, left, right ) {\n	const values := string_operands( ev, ctx, left, right );\n	return op.wrap( values[0] ~ values[1] );\n};\n\nconst bitwise_and := function ( op, ev, ast, ctx, left, right ) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val & right_val );\n};\n\nconst bitwise_xor := function ( op, ev, ast, ctx, left, right ) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val ^ right_val );\n};\n\nconst bitwise_or := function ( op, ev, ast, ctx, left, right ) {\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\n	return op.wrap( left_val | right_val );\n};\n\nfunction first_eval_value ( values ) {\n	return values.length() > 0 ? values[0] : null;\n}\n\nfunction primitive_eval_value ( values ) {\n	const first := first_eval_value(values);\n	return first \u2261 null ? null : first.primitive_value();\n}\n\nfunction collection_operand ( ev, ctx, expr ) {\n	const values := ev.eval_expr( expr, ev.nested_ctx( ctx ) );\n	if ( values.length() = 1 ) {\n		return values[0].primitive_value();\n	}\n	return values.map( fn value \u2192 value.primitive_value() );\n}\n\nconst logical_and := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	if ( ev.truthy( first_eval_value(left_vals) ) ) {\n		return ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	}\n	return op.wrap(false);\n};\n\nconst logical_nand := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	if ( not ev.truthy( first_eval_value(left_vals) ) ) {\n		return op.wrap(true);\n	}\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	return op.wrap( ev.truthy( first_eval_value(right_vals) ) ? false : true );\n};\n\nconst logical_butnot := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	if ( not ev.truthy( first_eval_value(left_vals) ) ) {\n		return op.wrap(false);\n	}\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	return op.wrap( ev.truthy( first_eval_value(right_vals) ) ? false : true );\n};\n\nconst logical_xor := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	const left_truth := ev.truthy( first_eval_value(left_vals) );\n	const right_truth := ev.truthy( first_eval_value(right_vals) );\n	return op.wrap( ( left_truth xor right_truth ) ? true : false );\n};\n\nconst logical_nor := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	if ( ev.truthy( first_eval_value(left_vals) ) ) {\n		return op.wrap(false);\n	}\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	return op.wrap( ev.truthy( first_eval_value(right_vals) ) ? false : true );\n};\n\nconst logical_xnor := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	const left_truth := ev.truthy( first_eval_value(left_vals) );\n	const right_truth := ev.truthy( first_eval_value(right_vals) );\n	return op.wrap( left_truth \u2261 right_truth );\n};\n\nconst logical_onlyif := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	if ( not ev.truthy( first_eval_value(left_vals) ) ) {\n		return op.wrap(true);\n	}\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	return op.wrap( ev.truthy( first_eval_value(right_vals) ) ? true : false );\n};\n\nconst logical_or := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	if ( ev.truthy( first_eval_value(left_vals) ) ) {\n		return op.wrap(true);\n	}\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	return op.wrap( ev.truthy( first_eval_value(right_vals) ) ? true : false );\n};\n\nconst logical_and_value := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	if ( ev.truthy( first_eval_value(left_vals) ) ) {\n		return ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	}\n	return left_vals;\n};\n\nconst logical_nand_value := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	const left_truth := ev.truthy( first_eval_value(left_vals) );\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	const right_truth := ev.truthy( first_eval_value(right_vals) );\n	if ( left_truth and right_truth ) {\n		return op.wrap(false);\n	}\n	return right_vals if not left_truth and right_truth;\n	return op.wrap(true);\n};\n\nconst logical_butnot_value := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	const left_truth := ev.truthy( first_eval_value(left_vals) );\n	return left_vals unless left_truth;\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	return ev.truthy( first_eval_value(right_vals) )\n		? op.wrap(false)\n		: left_vals;\n};\n\nconst logical_xor_value := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	const left_truth := ev.truthy( first_eval_value(left_vals) );\n	const right_truth := ev.truthy( first_eval_value(right_vals) );\n	if ( left_truth xor right_truth ) {\n		return left_truth ? left_vals : right_vals;\n	}\n	return op.wrap(false);\n};\n\nconst logical_nor_value := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	const left_truth := ev.truthy( first_eval_value(left_vals) );\n	const right_truth := ev.truthy( first_eval_value(right_vals) );\n	return op.wrap(false) if left_truth and right_truth;\n	return right_vals if left_truth and not right_truth;\n	return left_vals if not left_truth and right_truth;\n	return op.wrap(true);\n};\n\nconst logical_xnor_value := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	const left_truth := ev.truthy( first_eval_value(left_vals) );\n	const right_truth := ev.truthy( first_eval_value(right_vals) );\n	if ( left_truth \u2261 right_truth ) {\n		return left_truth ? right_vals : op.wrap(true);\n	}\n	return left_truth ? right_vals : left_vals;\n};\n\nconst logical_onlyif_value := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	if ( not ev.truthy( first_eval_value(left_vals) ) ) {\n		return op.wrap(true);\n	}\n	return ev.eval_expr( right, ev.nested_ctx( ctx ) );\n};\n\nconst logical_or_value := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	if ( ev.truthy( first_eval_value(left_vals) ) ) {\n		return left_vals;\n	}\n	return ev.eval_expr( right, ev.nested_ctx( ctx ) );\n};\n\nconst set_union := function ( op, ev, ast, ctx, left, right ) {\n	const left_val := collection_operand( ev, ctx, left );\n	const right_val := collection_operand( ev, ctx, right );\n	return op.wrap( left_val union right_val );\n};\n\nconst set_intersection := function ( op, ev, ast, ctx, left, right ) {\n	const left_val := collection_operand( ev, ctx, left );\n	const right_val := collection_operand( ev, ctx, right );\n	return op.wrap( left_val intersection right_val );\n};\n\nconst set_difference := function ( op, ev, ast, ctx, left, right ) {\n	const left_val := collection_operand( ev, ctx, left );\n	const right_val := collection_operand( ev, ctx, right );\n	return op.wrap( left_val \u2216 right_val );\n};\n\nconst collection_membership := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	const left_val := primitive_eval_value(left_vals);\n	const right_val := collection_operand( ev, ctx, right );\n	return op.wrap( left_val in right_val );\n};\n\nconst collection_non_membership := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	const left_val := primitive_eval_value(left_vals);\n	const right_val := collection_operand( ev, ctx, right );\n	return op.wrap( left_val \u2209 right_val );\n};\n\nconst set_subsetof := function ( op, ev, ast, ctx, left, right ) {\n	const left_val := collection_operand( ev, ctx, left );\n	const right_val := collection_operand( ev, ctx, right );\n	return op.wrap( left_val subsetof right_val );\n};\n\nconst set_supersetof := function ( op, ev, ast, ctx, left, right ) {\n	const left_val := collection_operand( ev, ctx, left );\n	const right_val := collection_operand( ev, ctx, right );\n	return op.wrap( left_val supersetof right_val );\n};\n\nconst set_equivalentof := function ( op, ev, ast, ctx, left, right ) {\n	const left_val := collection_operand( ev, ctx, left );\n	const right_val := collection_operand( ev, ctx, right );\n	return op.wrap( left_val equivalentof right_val );\n};\n\nconst type_aware_equality := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	return op.wrap( ev.equals(\n		first_eval_value(left_vals),\n		first_eval_value(right_vals),\n	) );\n};\n\nconst type_aware_inequality := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	return op.wrap( not ev.equals(\n		first_eval_value(left_vals),\n		first_eval_value(right_vals),\n	) );\n};\n\nfunction builtin_can ( value, method_name ) {\n	return false if value \u2261 null\n		or method_name \u2261 null\n		or method_name eq "";\n\n	if ( value instanceof Array or value instanceof Bag or value instanceof Set ) {\n		return method_name in [\n			"length",\n			"empty",\n			"contains",\n			"push",\n			"to_Array",\n			"to_Bag",\n			"to_Set",\n		];\n	}\n	if ( value instanceof Dict or value instanceof PairList ) {\n		return method_name in [\n			"length",\n			"empty",\n			"exists",\n			"keys",\n			"values",\n			"to_Array",\n		];\n	}\n	if ( value instanceof String or value instanceof BinaryString ) {\n		return method_name in [ "length" ];\n	}\n	return false;\n}\n\nconst object_can := function ( op, ev, ast, ctx, left, right ) {\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\n	const left_val := primitive_eval_value(left_vals);\n	const right_val := primitive_eval_value(right_vals);\n	return op.wrap(\n		( left_val can (right_val) ) or builtin_can( left_val, right_val )\n	);\n};\n\nconst STANDARD_OPERATORS := [\n	new Operator(\n		spelling: "?:",\n		kind: "ELVIS",\n		precedence: 2,\n		lex_ignore: true,\n	),\n\n	new Operator(\n		spelling: "+",\n		kind: "UPLUS",\n		unary: true,\n		precedence: 40,\n		f: function ( op, ev, ast, ctx, expr ) {\n			const value := op._handle_numeric_operand( ev, ctx, expr );\n			return op.wrap( +value );\n		},\n	),\n\n	new Operator(\n		spelling: "-",\n		kind: "UMINUS",\n		unary: true,\n		precedence: 40,\n		f: function ( op, ev, ast, ctx, expr ) {\n			const value := op._handle_numeric_operand( ev, ctx, expr );\n			return op.wrap( -value );\n		},\n	),\n\n	new Operator(\n		spelling: "\u221A",\n		kind: "SQRT",\n		unary: true,\n		precedence: 40,\n		f: function ( op, ev, ast, ctx, expr ) {\n			const value := op._handle_numeric_operand( ev, ctx, expr );\n			return op.wrap( sqrt value );\n		},\n	),\n\n	new Operator(\n		spelling: "!",\n		kind: "NOT",\n		unary: true,\n		precedence: 40,\n		f: logical_negation,\n	),\n\n	new Operator(\n		spelling: "\xAC",\n		kind: "NOTSYM",\n		unary: true,\n		precedence: 40,\n		f: logical_negation,\n	),\n\n	new Operator(\n		spelling: "**",\n		kind: "POW",\n		require_ws: true,\n		right_assoc: true,\n		precedence: 26,\n		f: numeric_power,\n	),\n\n	new Operator(\n		spelling: "\xD7",\n		kind: "TIMES_SIGN",\n		precedence: 24,\n		f: numeric_multiplication,\n	),\n\n	new Operator(\n		spelling: "*",\n		kind: "TIMES",\n		require_ws: true,\n		precedence: 24,\n		lex_ignore: true,\n		alias: "STAR",\n		f: numeric_multiplication,\n	),\n\n	new Operator(\n		spelling: "\xF7",\n		kind: "DIVIDE_SIGN",\n		precedence: 24,\n		f: numeric_division,\n	),\n\n	new Operator(\n		spelling: "/",\n		kind: "DIVIDE",\n		require_ws: true,\n		precedence: 24,\n		lex_ignore: true,\n		alias: "SLASH",\n		f: numeric_division,\n	),\n\n	new Operator(\n		spelling: "mod",\n		kind: "MOD",\n		precedence: 24,\n		f: numeric_modulus,\n	),\n\n	new Operator(\n		spelling: "+",\n		kind: "PLUS",\n		require_ws: true,\n		precedence: 22,\n		f: numeric_addition,\n	),\n\n	new Operator(\n		spelling: "-",\n		kind: "MINUS",\n		require_ws: true,\n		precedence: 22,\n		f: numeric_subtraction,\n	),\n\n	new Operator(\n		spelling: "=",\n		kind: "EQ",\n		precedence: 10,\n		f: numeric_equality,\n	),\n\n	new Operator(\n		spelling: "\u2260",\n		kind: "NE",\n		precedence: 10,\n		f: numeric_inequality,\n	),\n\n	new Operator(\n		spelling: "<",\n		kind: "LT",\n		precedence: 10,\n		f: numeric_less_than,\n	),\n\n	new Operator(\n		spelling: ">",\n		kind: "GT",\n		precedence: 10,\n		f: numeric_greater_than,\n	),\n\n	new Operator(\n		spelling: "\u2264",\n		kind: "LE_SIGN",\n		precedence: 10,\n		f: numeric_less_than_or_equal,\n	),\n\n	new Operator(\n		spelling: "<=",\n		kind: "LE",\n		precedence: 10,\n		f: numeric_less_than_or_equal,\n	),\n\n	new Operator(\n		spelling: "\u2265",\n		kind: "GE_SIGN",\n		precedence: 10,\n		f: numeric_greater_than_or_equal,\n	),\n\n	new Operator(\n		spelling: ">=",\n		kind: "GE",\n		precedence: 10,\n		f: numeric_greater_than_or_equal,\n	),\n\n	new Operator(\n		spelling: "\u2276",\n		kind: "CMP_SIGN",\n		precedence: 10,\n		f: numeric_compare,\n	),\n\n	new Operator(\n		spelling: "<=>",\n		kind: "CMP",\n		precedence: 10,\n		f: numeric_compare,\n	),\n\n	new Operator(\n		spelling: "\u2277",\n		kind: "CMP_REV_SIGN",\n		precedence: 10,\n		f: numeric_compare,\n	),\n\n	new Operator(\n		spelling: "\u2223",\n		kind: "DIVIDES_SIGN",\n		precedence: 10,\n		f: numeric_divides,\n	),\n\n	new Operator(\n		spelling: "divides",\n		kind: "DIVIDES",\n		precedence: 10,\n		f: numeric_divides,\n	),\n\n	new Operator(\n		spelling: "\u2224",\n		kind: "NOT_DIVIDES_SIGN",\n		precedence: 10,\n		f: numeric_not_divides,\n	),\n\n	new Operator(\n		spelling: "_",\n		kind: "CONCAT",\n		require_ws: true,\n		precedence: 21,\n		f: string_concatenation,\n	),\n\n	new Operator(\n		spelling: "eq",\n		kind: "STR_EQ",\n		precedence: 10,\n		f: string_equality,\n	),\n\n	new Operator(\n		spelling: "ne",\n		kind: "STR_NE",\n		precedence: 10,\n		f: string_inequality,\n	),\n\n	new Operator(\n		spelling: "gt",\n		kind: "STR_GT",\n		precedence: 10,\n		f: string_greater_than,\n	),\n\n	new Operator(\n		spelling: "ge",\n		kind: "STR_GE",\n		precedence: 10,\n		f: string_greater_than_or_equal,\n	),\n\n	new Operator(\n		spelling: "lt",\n		kind: "STR_LT",\n		precedence: 10,\n		f: string_less_than,\n	),\n\n	new Operator(\n		spelling: "le",\n		kind: "STR_LE",\n		precedence: 10,\n		f: string_less_than_or_equal,\n	),\n\n	new Operator(\n		spelling: "cmp",\n		kind: "STR_CMP",\n		precedence: 10,\n		f: string_compare,\n	),\n\n	new Operator(\n		spelling: "eqi",\n		kind: "STR_EQI",\n		precedence: 10,\n		f: string_equality_insensitive,\n	),\n\n	new Operator(\n		spelling: "nei",\n		kind: "STR_NEI",\n		precedence: 10,\n		f: string_inequality_insensitive,\n	),\n\n	new Operator(\n		spelling: "gti",\n		kind: "STR_GTI",\n		precedence: 10,\n		f: string_greater_than_insensitive,\n	),\n\n	new Operator(\n		spelling: "gei",\n		kind: "STR_GEI",\n		precedence: 10,\n		f: string_greater_than_or_equal_insensitive,\n	),\n\n	new Operator(\n		spelling: "lti",\n		kind: "STR_LTI",\n		precedence: 10,\n		f: string_less_than_insensitive,\n	),\n\n	new Operator(\n		spelling: "lei",\n		kind: "STR_LEI",\n		precedence: 10,\n		f: string_less_than_or_equal_insensitive,\n	),\n\n	new Operator(\n		spelling: "cmpi",\n		kind: "STR_CMPI",\n		precedence: 10,\n		f: string_compare_insensitive,\n	),\n\n	new Operator(\n		spelling: "~",\n		kind: "REGEXP_MATCH",\n		precedence: 10,\n		f: regexp_match,\n	),\n\n	new Operator(\n		spelling: "\xAB",\n		kind: "LSHIFT_SIGN",\n		precedence: 18,\n		f: numeric_left_shift,\n	),\n\n	new Operator(\n		spelling: "<<",\n		kind: "LSHIFT",\n		precedence: 18,\n		f: numeric_left_shift,\n	),\n\n	new Operator(\n		spelling: "\xBB",\n		kind: "RSHIFT_SIGN",\n		precedence: 18,\n		f: numeric_right_shift,\n	),\n\n	new Operator(\n		spelling: ">>",\n		kind: "RSHIFT",\n		precedence: 18,\n		f: numeric_right_shift,\n	),\n\n	new Operator(\n		spelling: "&",\n		kind: "BAND",\n		precedence: 16,\n		f: bitwise_and,\n	),\n\n	new Operator(\n		spelling: "^",\n		kind: "BXOR",\n		precedence: 14,\n		f: bitwise_xor,\n	),\n\n	new Operator(\n		spelling: "|",\n		kind: "BOR",\n		precedence: 12,\n		f: bitwise_or,\n	),\n\n	new Operator(\n		spelling: "\u22C0",\n		kind: "LAND_SIGN",\n		precedence: 7,\n		f: logical_and,\n	),\n\n	new Operator(\n		spelling: "and",\n		kind: "LAND",\n		precedence: 7,\n		f: logical_and,\n	),\n\n	new Operator(\n		spelling: "\u22C0?",\n		kind: "LAND_VALUE_SIGN",\n		precedence: 7,\n		f: logical_and_value,\n	),\n\n	new Operator(\n		spelling: "and?",\n		kind: "LAND_VALUE",\n		precedence: 7,\n		f: logical_and_value,\n	),\n\n	new Operator(\n		spelling: "\u22BC",\n		kind: "LNAND_SIGN",\n		precedence: 7,\n		f: logical_nand,\n	),\n\n	new Operator(\n		spelling: "nand",\n		kind: "LNAND",\n		precedence: 7,\n		f: logical_nand,\n	),\n\n	new Operator(\n		spelling: "\u22BC?",\n		kind: "LNAND_VALUE_SIGN",\n		precedence: 7,\n		f: logical_nand_value,\n	),\n\n	new Operator(\n		spelling: "nand?",\n		kind: "LNAND_VALUE",\n		precedence: 7,\n		f: logical_nand_value,\n	),\n\n	new Operator(\n		spelling: "\u22AD",\n		kind: "LBUTNOT_SIGN",\n		precedence: 7,\n		f: logical_butnot,\n	),\n\n	new Operator(\n		spelling: "butnot",\n		kind: "LBUTNOT",\n		precedence: 7,\n		f: logical_butnot,\n	),\n\n	new Operator(\n		spelling: "\u22AD?",\n		kind: "LBUTNOT_VALUE_SIGN",\n		precedence: 7,\n		f: logical_butnot_value,\n	),\n\n	new Operator(\n		spelling: "butnot?",\n		kind: "LBUTNOT_VALUE",\n		precedence: 7,\n		f: logical_butnot_value,\n	),\n\n	new Operator(\n		spelling: "\u22BB",\n		kind: "LXOR_SIGN",\n		precedence: 5,\n		f: logical_xor,\n	),\n\n	new Operator(\n		spelling: "xor",\n		kind: "LXOR",\n		precedence: 5,\n		f: logical_xor,\n	),\n\n	new Operator(\n		spelling: "\u22BB?",\n		kind: "LXOR_VALUE_SIGN",\n		precedence: 5,\n		f: logical_xor_value,\n	),\n\n	new Operator(\n		spelling: "xor?",\n		kind: "LXOR_VALUE",\n		precedence: 5,\n		f: logical_xor_value,\n	),\n\n	new Operator(\n		spelling: "\u22BD",\n		kind: "LNOR_SIGN",\n		precedence: 5,\n		f: logical_nor,\n	),\n\n	new Operator(\n		spelling: "nor",\n		kind: "LNOR",\n		precedence: 5,\n		f: logical_nor,\n	),\n\n	new Operator(\n		spelling: "\u22BD?",\n		kind: "LNOR_VALUE_SIGN",\n		precedence: 5,\n		f: logical_nor_value,\n	),\n\n	new Operator(\n		spelling: "nor?",\n		kind: "LNOR_VALUE",\n		precedence: 5,\n		f: logical_nor_value,\n	),\n\n	new Operator(\n		spelling: "\u2194",\n		kind: "LXNOR_SIGN",\n		precedence: 5,\n		f: logical_xnor,\n	),\n\n	new Operator(\n		spelling: "xnor",\n		kind: "LXNOR",\n		precedence: 5,\n		f: logical_xnor,\n	),\n\n	new Operator(\n		spelling: "\u2194?",\n		kind: "LXNOR_VALUE_SIGN",\n		precedence: 5,\n		f: logical_xnor_value,\n	),\n\n	new Operator(\n		spelling: "xnor?",\n		kind: "LXNOR_VALUE",\n		precedence: 5,\n		f: logical_xnor_value,\n	),\n\n	new Operator(\n		spelling: "\u22A8",\n		kind: "LONLYIF_SIGN",\n		precedence: 4,\n		right_assoc: true,\n		f: logical_onlyif,\n	),\n\n	new Operator(\n		spelling: "onlyif",\n		kind: "LONLYIF",\n		precedence: 4,\n		right_assoc: true,\n		f: logical_onlyif,\n	),\n\n	new Operator(\n		spelling: "\u22A8?",\n		kind: "LONLYIF_VALUE_SIGN",\n		precedence: 4,\n		right_assoc: true,\n		f: logical_onlyif_value,\n	),\n\n	new Operator(\n		spelling: "onlyif?",\n		kind: "LONLYIF_VALUE",\n		precedence: 4,\n		right_assoc: true,\n		f: logical_onlyif_value,\n	),\n\n	new Operator(\n		spelling: "\u22C1",\n		kind: "LOR_SIGN",\n		precedence: 2,\n		f: logical_or,\n	),\n\n	new Operator(\n		spelling: "or",\n		kind: "LOR",\n		precedence: 2,\n		f: logical_or,\n	),\n\n	new Operator(\n		spelling: "\u22C1?",\n		kind: "LOR_VALUE_SIGN",\n		precedence: 2,\n		f: logical_or_value,\n	),\n\n	new Operator(\n		spelling: "or?",\n		kind: "LOR_VALUE",\n		precedence: 2,\n		f: logical_or_value,\n	),\n\n	new Operator(\n		spelling: "\u22C3",\n		kind: "SET_UNION_SIGN",\n		precedence: 20,\n		f: set_union,\n	),\n\n	new Operator(\n		spelling: "union",\n		kind: "SET_UNION",\n		precedence: 20,\n		f: set_union,\n	),\n\n	new Operator(\n		spelling: "\u22C2",\n		kind: "SET_INTERSECTION_SIGN",\n		precedence: 20,\n		f: set_intersection,\n	),\n\n	new Operator(\n		spelling: "intersection",\n		kind: "SET_INTERSECTION",\n		precedence: 20,\n		f: set_intersection,\n	),\n\n	new Operator(\n		spelling: "\u2216",\n		kind: "SET_DIFFERENCE_SIGN",\n		precedence: 20,\n		f: set_difference,\n	),\n\n	new Operator(\n		spelling: "\\\\",\n		kind: "SET_DIFFERENCE",\n		precedence: 20,\n		require_ws: true,\n		f: set_difference,\n	),\n\n	new Operator(\n		spelling: "\u2208",\n		kind: "MEMBER_SIGN",\n		precedence: 10,\n		f: collection_membership,\n	),\n\n	new Operator(\n		spelling: "in",\n		kind: "MEMBER",\n		precedence: 10,\n		f: collection_membership,\n	),\n\n	new Operator(\n		spelling: "\u2209",\n		kind: "NOT_MEMBER_SIGN",\n		precedence: 10,\n		f: collection_non_membership,\n	),\n\n	new Operator(\n		spelling: "\u2282",\n		kind: "SUBSETOF_SIGN",\n		precedence: 10,\n		f: set_subsetof,\n	),\n\n	new Operator(\n		spelling: "subsetof",\n		kind: "SUBSETOF",\n		precedence: 10,\n		f: set_subsetof,\n	),\n\n	new Operator(\n		spelling: "\u2283",\n		kind: "SUPERSETOF_SIGN",\n		precedence: 10,\n		f: set_supersetof,\n	),\n\n	new Operator(\n		spelling: "supersetof",\n		kind: "SUPERSETOF",\n		precedence: 10,\n		f: set_supersetof,\n	),\n\n	new Operator(\n		spelling: "\u2282\u2283",\n		kind: "EQUIVALENTOF_SIGN",\n		precedence: 10,\n		f: set_equivalentof,\n	),\n\n	new Operator(\n		spelling: "equivalentof",\n		kind: "EQUIVALENTOF",\n		precedence: 10,\n		f: set_equivalentof,\n	),\n\n	new Operator(\n		spelling: "\u2261",\n		kind: "TYPE_EQ_SIGN",\n		precedence: 8,\n		f: type_aware_equality,\n	),\n\n	new Operator(\n		spelling: "==",\n		kind: "TYPE_EQ",\n		precedence: 8,\n		f: type_aware_equality,\n	),\n\n	new Operator(\n		spelling: "\u2262",\n		kind: "TYPE_NE_SIGN",\n		precedence: 8,\n		f: type_aware_inequality,\n	),\n\n	new Operator(\n		spelling: "!=",\n		kind: "TYPE_NE",\n		precedence: 8,\n		f: type_aware_inequality,\n	),\n\n	new Operator(\n		spelling: "can",\n		kind: "CAN",\n		precedence: 10,\n		f: object_can,\n	),\n\n	new Operator(\n		spelling: "~",\n		kind: "BNOT",\n		unary: true,\n		precedence: 40,\n		f: function ( op, ev, ast, ctx, expr ) {\n			const value := op._handle_numeric_operand( ev, ctx, expr );\n			return op.wrap( ~value );\n		},\n	),\n];\n';
        virtualFiles["/modules/std/template/z.zzm"] = '=encoding utf8\n\n=head1 NAME\n\nstd/template/z - Pure ZuzuScript template engine.\n\n=head1 SYNOPSIS\n\n  from std/template/z import ZTemplate;\n\n  let inline := new ZTemplate(\n    string: "Hello {{ user/name }}!",\n  );\n  say( inline.process( { user: { name: "Ada" } } ) );\n\n  let file_tmpl := new ZTemplate(\n    file: "templates/page.zt",\n    escape: "html",\n  );\n  say( file_tmpl.process( data ) );\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Node and\nElectron. It is partially supported by zuzu-js in the browser: complex,\nHTTP/JSON/ZPath pipeline, self-contained, and trait-object rendering\ncoverage passes, but filesystem-backed template loading and database row\nrendering coverage are unsupported.\n\n=head1 DESCRIPTION\n\nC<std/template/z> is a pure ZuzuScript template renderer.\n\nThe module compiles template text into a cached parse tree and renders\nit against data using C<std/path/z> expressions.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<< ZTemplate({ string?: String, file?, escape?: String, includes?: Boolean }) >>\n\nConstructs a template from inline text or a file path. Returns:\nC<ZTemplate>.\n\n=over\n\n=item C<< template.process(data) >>\n\nParameters: C<data> is the model used for path lookups. Returns:\nC<String>. Renders the template.\n\n=back\n\n=back\n\n=head1 TAG FORMS\n\n=over 4\n\n=item * C<{{ expr }}>\n\nRender expression output using template default escaping.\n\n=item * C<{{ expr :: raw }}>, C<{{ expr :: html }}>\n\nRender expression output using per-tag escape override.\n\n=item * C<{{# expr }}> ... C<{{/expr}}>\n\nBlock form. Each truthy match renders child nodes.\n\n=item * C<{{> include.zt }}>\n\nInclude another template file. Relative include paths resolve from the\ncurrent template\'s file directory.\n\n=back\n\n=head1 ESCAPING\n\nDefault escape mode is C<html>. Supported escape modes are C<html> and\nC<raw>.\n\nC<html> escapes C<&>, C<< < >>, C<E<gt>>, double quotes, and single\nquotes.\n\n=head1 INCLUDE RULES\n\n=over 4\n\n=item * Include processing is enabled by default.\n\n=item * Pass C<includes: false> to disable include tags.\n\n=item * Relative includes require a file-backed template source.\n\n=item * Circular include chains throw a deterministic error.\n\n=back\n\n=head1 KNOWN DIFFERENCES\n\nThis module is implemented on top of C<std/path/z>. Parser/rendering\ndeltas across runtimes are covered in ztests and should be treated as\nimplementation bugs unless explicitly documented.\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/template/z >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/string import index, substr, trim;\nfrom std/path/z import ZPath;\n\nclass ZTemplate {\n	let string;\n	let file;\n	let String escape := "html";\n	let includes := true;\n	let source_file := null;\n	let Array tree := [];\n	let compiled_paths := {};\n\n	method __build__ () {\n		let has_string := string \u2262 null;\n		let has_file := file \u2262 null;\n\n		if ( has_string and has_file ) {\n			die "Specify only one of \\"string\\" or \\"file\\"";\n		}\n		if ( not has_string and not has_file ) {\n			die "Missing template source: provide \\"string\\" or \\"file\\"";\n		}\n\n		escape := lc( "" _ escape );\n		if ( escape \u2262 "html" and escape \u2262 "raw" ) {\n			die `Invalid escape mode "${escape}"`;\n		}\n\n		if ( has_file ) {\n			let loaded := self._read_template_file(file);\n			string := loaded{text};\n			source_file := loaded{file};\n		}\n\n		tree := self._parse_template(\n			template: string \u2261 null ? "": string,\n			current_file: source_file,\n			seen_files: {},\n			includes: includes,\n		);\n	}\n\n	method process ( data ) {\n		die "process() requires a data model" if data \u2261 null;\n\n		return self._render_nodes(\n			nodes: tree,\n			context: data,\n			eval_meta: {},\n			default_escape: escape,\n		);\n	}\n\n	method _parse_template ( ... PairList args ) {\n		let template := args.get( "template", "" );\n		let current_file := args.get( "current_file", null );\n		let seen_files := args.get( "seen_files", {} );\n		let includes_enabled := args.get( "includes", true );\n		let root := [];\n\n		let stack := [\n			{\n				expr: null,\n				nodes: root,\n			},\n		];\n\n		let pos := 0;\n		while ( true ) {\n			let tag_open := index( template, "{{", pos );\n			last if tag_open < 0;\n\n			let text := substr( template, pos, tag_open - pos );\n			self._push_text( stack[ stack.length() - 1 ]{nodes}, text );\n\n			let tag_close := index( template, "}}", tag_open + 2 );\n			if ( tag_close < 0 ) {\n				die `Unterminated tag at character ${tag_open}`;\n			}\n\n			let raw := substr( template, tag_open + 2, tag_close - tag_open - 2 );\n			let tagged := trim(raw);\n\n			if ( substr( tagged, 0, 1 ) \u2261 "#" ) {\n				let inner := trim( substr( tagged, 1 ) );\n				let parsed := self._parse_expression_spec(inner);\n				let block := {\n					type: "block",\n					expr_src: parsed{expr},\n					nodes: [],\n				};\n				stack[ stack.length() - 1 ]{nodes}.push(block);\n				stack.push( {\n					expr: parsed{expr},\n					nodes: block{nodes},\n				} );\n			}\n			else if ( substr( tagged, 0, 1 ) \u2261 "/" ) {\n				let inner := trim( substr( tagged, 1 ) );\n				let current := stack.pop();\n				if ( current \u2261 null or current{expr} \u2261 null ) {\n					die `Mismatched close tag {{/${inner}}}`;\n				}\n				if ( inner \u2262 "" ) {\n					let parsed := self._parse_expression_spec(inner);\n					if ( current{expr} \u2262 parsed{expr} ) {\n						die `Mismatched close tag {{/${inner}}} for {{${current{expr}}}}`;\n					}\n				}\n			}\n			else if ( tagged \u2262 "" ) {\n				if ( substr( tagged, 0, 1 ) \u2261 ">" ) {\n					die "Template includes are disabled"\n						if not includes_enabled;\n\n					let include_path := trim( substr( tagged, 1 ) );\n					die "Empty include path in template tag"\n						if include_path \u2261 "";\n\n					let resolved := self._resolve_include_path(\n						include_path: include_path,\n						current_file: current_file,\n					);\n\n					let key := self._canonical_path(resolved);\n					if ( seen_files.exists(key) and seen_files.get(key) ) {\n						die `Circular include detected for "${resolved}"`;\n					}\n\n					seen_files.set( key, true );\n					let loaded := self._read_template_file(resolved);\n					let include_nodes := self._parse_template(\n						template: loaded{text},\n						current_file: loaded{file},\n						seen_files: seen_files,\n						includes: includes_enabled,\n					);\n					seen_files.remove(key);\n\n					for ( let node in include_nodes ) {\n						stack[ stack.length() - 1 ]{nodes}.push(node);\n					}\n				}\n				else {\n					let parsed := self._parse_expression_spec(tagged);\n					stack[ stack.length() - 1 ]{nodes}.push( {\n						type: "expr",\n						expr_src: parsed{expr},\n						escape: parsed{escape},\n					} );\n				}\n			}\n\n			pos := tag_close + 2;\n		}\n\n		let tail := substr( template, pos );\n		self._push_text( stack[ stack.length() - 1 ]{nodes}, tail );\n\n		if ( stack.length() > 1 ) {\n			let missing := stack[ stack.length() - 1 ]{expr};\n			die `Missing close tag for {{${missing}}}`;\n		}\n\n		return root;\n	}\n\n	method _push_text ( nodes, text ) {\n		if ( text \u2262 "" ) {\n			nodes.push( {\n				type: "text",\n				text: text,\n			} );\n		}\n	}\n\n	method _read_template_file ( raw_file ) {\n		let path_obj := self._to_path(raw_file);\n		let text := path_obj.slurp_utf8();\n		let canonical := self._canonical_path(path_obj);\n\n		return {\n			text: text,\n			file: canonical,\n		};\n	}\n\n	method _to_path ( raw_file ) {\n		from std/io import Path;\n		if ( raw_file instanceof Path ) {\n			return raw_file;\n		}\n		return new Path( "" _ raw_file );\n	}\n\n	method _canonical_path ( path_obj ) {\n		let obj := self._to_path(path_obj);\n		let canonical := obj.realpath();\n		if ( canonical \u2261 null ) {\n			canonical := obj.absolute();\n		}\n		if ( canonical \u2261 null ) {\n			return obj.to_String;\n		}\n		from std/io import Path;\n		if ( canonical instanceof Path ) {\n			return canonical.to_String;\n		}\n		return "" _ canonical;\n	}\n\n	method _resolve_include_path ( ... PairList args ) {\n		let include_path := args.get( "include_path" );\n		let current_file := args.get( "current_file" );\n\n		let include_obj := self._to_path(include_path);\n		if ( include_obj.is_absolute() ) {\n			return include_obj.to_String;\n		}\n\n		if ( current_file \u2261 null ) {\n			die `Relative include path "${include_path}" requires file-based template source`;\n		}\n\n		let base := self._to_path(current_file).parent();\n		return base.child( include_obj.to_String ).to_String;\n	}\n\n	method _parse_expression_spec ( raw ) {\n		let expr := raw;\n		let escape_mode := null;\n\n		let split := self._find_escape_separator(raw);\n		if ( split \u2262 null ) {\n			let lhs := split[0];\n			let rhs := split[1];\n			if ( rhs \u2261 "html" or rhs \u2261 "raw" ) {\n				expr := lhs;\n				escape_mode := rhs;\n			}\n		}\n\n		expr := trim(expr);\n		if ( expr \u2261 "" ) {\n			die "Empty expression in template tag";\n		}\n\n		return {\n			expr: expr,\n			escape: escape_mode,\n		};\n	}\n\n	method _find_escape_separator ( text ) {\n		let quote := "";\n		let i := 0;\n		while ( i < length text ) {\n			let ch := substr( text, i, 1 );\n			if ( quote \u2262 "" ) {\n				if ( ch \u2261 "\\\\" ) {\n					i += 2;\n					next;\n				}\n				if ( ch \u2261 quote ) {\n					quote := "";\n				}\n				i++;\n				next;\n			}\n\n			if ( ch \u2261 "\\"" or ch \u2261 "\'" ) {\n				quote := ch;\n				i++;\n				next;\n			}\n\n			if ( ch \u2261 ":" and substr( text, i, 2 ) \u2261 "::" ) {\n				let lhs := trim( substr( text, 0, i ) );\n				let rhs := lc( trim( substr( text, i + 2 ) ) );\n				return [ lhs, rhs ];\n			}\n\n			i++;\n		}\n\n		return null;\n	}\n\n	method _render_nodes ( ... PairList args ) {\n		let nodes := args.get( "nodes", [] );\n		let context := args.get( "context", null );\n		let eval_meta := args.get( "eval_meta", {} );\n		let default_escape := args.get( "default_escape", "html" );\n		let out := "";\n\n		for ( let node in nodes ) {\n			if ( node{type} \u2261 "text" ) {\n				out _= node{text};\n			}\n			else if ( node{type} \u2261 "expr" ) {\n				let results := self._evaluate_expression(\n					expr_src: node{expr_src},\n					context: context,\n					eval_meta: eval_meta,\n				);\n				let value := "";\n				for ( let matched in results ) {\n					let sv := matched.string_value();\n					value _= sv \u2261 null ? "" : sv;\n				}\n\n				let escape_mode := node{escape};\n				if ( escape_mode \u2261 null ) {\n					escape_mode := default_escape;\n				}\n\n				if ( escape_mode \u2261 "html" ) {\n					out _= self._escape_html(value);\n				}\n				else {\n					out _= value;\n				}\n			}\n			else if ( node{type} \u2261 "block" ) {\n				let results := self._evaluate_expression(\n					expr_src: node{expr_src},\n					context: context,\n					eval_meta: eval_meta,\n				);\n				for ( let matched in results ) {\n					let primitive := matched.primitive_value();\n					next if not self._truthy(primitive);\n\n					let inner_context := context;\n					let inner_meta := eval_meta;\n					if ( self._node_has_identity(matched) ) {\n						inner_context := matched;\n						inner_meta := { parentset: results };\n					}\n\n					out _= self._render_nodes(\n						nodes: node{nodes},\n						context: inner_context,\n						eval_meta: inner_meta,\n						default_escape: default_escape,\n					);\n				}\n			}\n		}\n\n		return out;\n	}\n\n	method _evaluate_expression ( ... PairList args ) {\n		let expr_src := args.get( "expr_src" );\n		let context := args.get( "context" );\n		let eval_meta := args.get( "eval_meta", {} );\n		if ( not compiled_paths.exists(expr_src) ) {\n			compiled_paths.set(\n				expr_src,\n				self._compile_path(expr_src),\n			);\n		}\n		let zpath := compiled_paths.get(expr_src);\n		return zpath.evaluate( context, eval_meta );\n	}\n\n	method _compile_path ( expr_src ) {\n		return new ZPath( path: expr_src );\n	}\n\n	method _node_has_identity ( node ) {\n		let parent := node.parent();\n		if ( parent \u2261 null ) {\n			return false;\n		}\n\n		return true;\n	}\n\n	method _truthy ( value ) {\n		return value ? true : false;\n	}\n\n	method _escape_html ( text ) {\n		let out := "";\n		let i := 0;\n		while ( i < length text ) {\n			let ch := substr( text, i, 1 );\n			if ( ch \u2261 "&" ) {\n				out _= "&amp;";\n			}\n			else if ( ch \u2261 "<" ) {\n				out _= "&lt;";\n			}\n			else if ( ch \u2261 ">" ) {\n				out _= "&gt;";\n			}\n			else if ( ch \u2261 "\\"" ) {\n				out _= "&quot;";\n			}\n			else if ( ch \u2261 "\'" ) {\n				out _= "&#39;";\n			}\n			else {\n				out _= ch;\n			}\n			i++;\n		}\n		return out;\n	}\n}\n';
        virtualFiles["/modules/std/template/zz.zzm"] = `=encoding utf8

=head1 NAME

std/template/zz - ZZPath-backed template engine.

=head1 SYNOPSIS

  from std/template/zz import ZZTemplate;

  let tmpl := new ZZTemplate(
    string: "Hello {{ name ?: \\"friend\\" }}!",
  );
  say( tmpl.process( { name: "Ada" } ) );

=head1 IMPLEMENTATION SUPPORT

This module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Node and
Electron. It is partially supported by zuzu-js in the browser:
filesystem-backed template loading is unsupported.

=head1 DESCRIPTION

C<std/template/zz> provides C<ZZTemplate>, a subclass of
C<std/template/z>'s C<ZTemplate> which renders template expressions
using C<std/path/zz> instead of C<std/path/z>.

The parser, escaping, include handling, and rendering machinery are
inherited from C<ZTemplate>.

=head1 EXPORTS

=head2 Classes

=over

=item C<< ZZTemplate({ string?: String, file?, escape?: String, includes?: Boolean }) >>

Constructs a template that evaluates expressions with C<std/path/zz>.
Returns: C<ZZTemplate>. It inherits C<process(data)> from C<ZTemplate>,
which takes a model value and returns rendered C<String> output.

=back

=head1 COPYRIGHT AND LICENCE

B<< std/template/zz >> is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under
the terms of either the Artistic License 1.0 or the GNU General Public
License version 2.

=cut

from std/template/z import ZTemplate;
from std/path/zz import ZZPath;

class ZZTemplate extends ZTemplate {
	method _compile_path ( expr_src ) {
		return new ZZPath( path: expr_src );
	}
}
`;
        return {
          repoRoot: "/",
          includePaths: [],
          jsModules,
          virtualFiles
        };
      }
      module2.exports = {
        createBrowserStdlib
      };
    }
  });

  // ../../../../../tmp/zuzu-browser-build.UGYrnC/browser-worker-source.generated.js
  var require_browser_worker_source_generated = __commonJS({
    "../../../../../tmp/zuzu-browser-build.UGYrnC/browser-worker-source.generated.js"(exports2, module2) {
      "use strict";
      module2.exports = {
        browserWorkerSource: '"use strict";\n(() => {\n  var __getOwnPropNames = Object.getOwnPropertyNames;\n  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {\n    get: (a, b) => (typeof require !== "undefined" ? require : a)[b]\n  }) : x)(function(x) {\n    if (typeof require !== "undefined") return require.apply(this, arguments);\n    throw Error(\'Dynamic require of "\' + x + \'" is not supported\');\n  });\n  var __commonJS = (cb, mod) => function __require2() {\n    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\n  };\n\n  // modules/javascript.js\n  var require_javascript = __commonJS({\n    "modules/javascript.js"(exports2, module2) {\n      "use strict";\n      function isPlainObject2(value) {\n        return value != null && typeof value === "object" && !Array.isArray(value) && Object.prototype.toString.call(value) === "[object Object]";\n      }\n      function decorateDict(value) {\n        if (!isPlainObject2(value)) {\n          return value;\n        }\n        for (const [name2, fn2] of [\n          ["length", function _length() {\n            return Object.keys(this).length;\n          }],\n          ["count", function _count() {\n            return Object.keys(this).length;\n          }],\n          ["empty", function _empty() {\n            return Object.keys(this).length === 0 ? 1 : 0;\n          }],\n          ["keys", function _keys() {\n            return Object.keys(this);\n          }],\n          ["values", function _values() {\n            return Object.keys(this).map((key) => this[key]);\n          }],\n          ["has", function _has(key) {\n            return Object.prototype.hasOwnProperty.call(this, String(key)) ? 1 : 0;\n          }],\n          ["contains", function _contains(key) {\n            return this.has(key);\n          }],\n          ["exists", function _exists(key) {\n            return this.has(key);\n          }],\n          ["defined", function _defined(key) {\n            return this.has(key) && this[String(key)] != null ? 1 : 0;\n          }],\n          ["get", function _get(key, fallback = null) {\n            return this.has(key) ? this[String(key)] : fallback;\n          }],\n          ["add", function _add(key, inner) {\n            this[String(key)] = inner;\n            return this;\n          }],\n          ["set", function _set(key, inner) {\n            return this.add(key, inner);\n          }],\n          ["to_Iterator", function _to_iterator() {\n            return this.keys()[Symbol.iterator]();\n          }]\n        ]) {\n          if (!Object.prototype.hasOwnProperty.call(value, name2)) {\n            Object.defineProperty(value, name2, {\n              value: fn2,\n              enumerable: false,\n              configurable: true,\n              writable: true\n            });\n          }\n        }\n        for (const key of Object.keys(value)) {\n          value[key] = convertSafeValue(value[key]);\n        }\n        return value;\n      }\n      function convertSafeValue(value) {\n        if (value == null) {\n          return null;\n        }\n        if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {\n          return value;\n        }\n        if (Array.isArray(value)) {\n          for (let i = 0; i < value.length; i++) {\n            value[i] = convertSafeValue(value[i]);\n          }\n          return value;\n        }\n        if (isPlainObject2(value)) {\n          return decorateDict(value);\n        }\n        return value;\n      }\n      function isSafeValue(value, seen = /* @__PURE__ */ new Set()) {\n        if (value == null) {\n          return true;\n        }\n        if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {\n          return true;\n        }\n        if (typeof value === "bigint" || typeof value === "function" || typeof value === "symbol") {\n          return false;\n        }\n        if (seen.has(value)) {\n          return false;\n        }\n        seen.add(value);\n        try {\n          if (Array.isArray(value)) {\n            return value.every((item) => isSafeValue(item, seen));\n          }\n          if (isPlainObject2(value)) {\n            return Object.values(value).every((item) => isSafeValue(item, seen));\n          }\n          return false;\n        } finally {\n          seen.delete(value);\n        }\n      }\n      function jsonValue(value, seen = /* @__PURE__ */ new Set()) {\n        if (value == null) {\n          return null;\n        }\n        if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {\n          return value;\n        }\n        if (typeof value === "bigint") {\n          return value.toString();\n        }\n        if (typeof value === "function" || typeof value === "symbol") {\n          return null;\n        }\n        if (seen.has(value)) {\n          throw new Error("Exception: circular JavaScript value cannot be encoded as JSON");\n        }\n        seen.add(value);\n        try {\n          if (Array.isArray(value)) {\n            return value.map((item) => jsonValue(item, seen));\n          }\n          if (isPlainObject2(value)) {\n            const out = {};\n            for (const [key, inner] of Object.entries(value)) {\n              out[key] = jsonValue(inner, seen);\n            }\n            return out;\n          }\n          if (typeof value.toJSON === "function") {\n            return jsonValue(value.toJSON(), seen);\n          }\n          return String(value);\n        } finally {\n          seen.delete(value);\n        }\n      }\n      function evaluate(code, thisValue) {\n        const src = String(code ?? "");\n        return Function(\n          "code",\n          "return (function () { return eval( code ); }).call( this );"\n        ).call(thisValue, src);\n      }\n      var JSResult = class _JSResult {\n        constructor(value) {\n          this._value = value;\n        }\n        eval(code) {\n          return new _JSResult(evaluate(code, this._value));\n        }\n        isSafe() {\n          return isSafeValue(this._value) ? 1 : 0;\n        }\n        value() {\n          if (!this.isSafe()) {\n            throw new Error("Exception: JavaScript value is not safely representable in Zuzu");\n          }\n          return convertSafeValue(this._value);\n        }\n        toJSON() {\n          return JSON.stringify(jsonValue(this._value));\n        }\n        to_String() {\n          if (this._value == null) {\n            return "null";\n          }\n          return String(this._value);\n        }\n      };\n      var JS = {\n        eval(code) {\n          return new JSResult(evaluate(code, globalThis));\n        },\n        version() {\n          return String(globalThis.process && globalThis.process.version ? globalThis.process.version : "javascript");\n        }\n      };\n      module2.exports = {\n        JS,\n        JSResult\n      };\n    }\n  });\n\n  // lib/collections.js\n  var require_collections = __commonJS({\n    "lib/collections.js"(exports2, module2) {\n      "use strict";\n      function runtimeHelpers() {\n        return require_runtime_helpers();\n      }\n      function retainCollectionValue(collection, value) {\n        return runtimeHelpers().retainCollectionValue(collection, value);\n      }\n      function releaseCollectionValue(collection, value) {\n        return runtimeHelpers().releaseCollectionValue(collection, value);\n      }\n      function releaseCollectionValues(collection) {\n        return runtimeHelpers().releaseCollectionValues(collection);\n      }\n      function makeArray(values) {\n        return runtimeHelpers().makeArray(values);\n      }\n      function makeSet(values) {\n        return runtimeHelpers().makeSet(values);\n      }\n      function operatorString(value) {\n        return runtimeHelpers().operatorString(value);\n      }\n      function stringSortComparator(a, b) {\n        return runtimeHelpers().stringSortComparator(a, b);\n      }\n      var ZuzuBag = class _ZuzuBag {\n        constructor(...items) {\n          let values;\n          if (items.length === 0) {\n            this.items = [];\n            return;\n          }\n          if (items.length > 1) {\n            values = items;\n          } else {\n            const first = items[0];\n            if (Array.isArray(first)) {\n              values = first;\n            } else if (first != null && typeof first !== "string" && typeof first[Symbol.iterator] === "function") {\n              values = Array.from(first);\n            } else {\n              values = [first];\n            }\n          }\n          this.items = values.map((value) => retainCollectionValue(this, value));\n        }\n        length() {\n          return this.items.length;\n        }\n        count(value) {\n          if (arguments.length === 0) {\n            return this.items.length;\n          }\n          return this.items.filter((item) => item === value).length;\n        }\n        empty() {\n          return this.items.length === 0 ? 1 : 0;\n        }\n        is_empty() {\n          return this.empty();\n        }\n        contains(value) {\n          return this.items.includes(value) ? 1 : 0;\n        }\n        add(...values) {\n          this.items.push(...values.map((value) => retainCollectionValue(this, value)));\n          return this;\n        }\n        push(...values) {\n          return this.add(...values);\n        }\n        remove(value) {\n          for (let idx = this.items.length - 1; idx >= 0; idx--) {\n            if (this.items[idx] === value) {\n              releaseCollectionValue(this, this.items[idx]);\n              this.items.splice(idx, 1);\n            }\n          }\n          return this;\n        }\n        remove_first(value) {\n          const idx = this.items.indexOf(value);\n          if (idx >= 0) {\n            releaseCollectionValue(this, this.items[idx]);\n            this.items.splice(idx, 1);\n          }\n          return this;\n        }\n        remove_if(fn2) {\n          this.items = this.items.filter((item) => {\n            if (fn2(item)) {\n              releaseCollectionValue(this, item);\n              return false;\n            }\n            return true;\n          });\n          return this;\n        }\n        map(fn2) {\n          return new _ZuzuBag(this.items.map(fn2));\n        }\n        grep(fn2) {\n          return new _ZuzuBag(this.items.filter(fn2));\n        }\n        any(fn2) {\n          return this.items.some(fn2) ? 1 : 0;\n        }\n        all(fn2) {\n          return this.items.every(fn2) ? 1 : 0;\n        }\n        first(fn2) {\n          for (const item of this.items) {\n            if (fn2(item)) {\n              return item;\n            }\n          }\n          return null;\n        }\n        for_each_value(fn2) {\n          this.items.forEach(fn2);\n          return this;\n        }\n        to_Array() {\n          return makeArray(this.items);\n        }\n        to_Set() {\n          return makeSet(this.items);\n        }\n        to_Iterator() {\n          return this.items[Symbol.iterator]();\n        }\n        copy() {\n          return new _ZuzuBag(this.items);\n        }\n        uniq() {\n          return new _ZuzuBag([...new Set(this.items)]);\n        }\n        sum() {\n          return this.items.reduce((a, b) => Number(a) + Number(b), 0);\n        }\n        product() {\n          return this.items.reduce((a, b) => Number(a) * Number(b), 1);\n        }\n        sort(fn2) {\n          return this.to_Array().sort(fn2);\n        }\n        sortstr() {\n          return this.to_Array().sort(stringSortComparator);\n        }\n        sortnum() {\n          return this.to_Array().map((item) => Number(item)).sort((a, b) => a - b);\n        }\n        clear() {\n          releaseCollectionValues(this);\n          this.items = [];\n          return this;\n        }\n        [Symbol.iterator]() {\n          return this.items[Symbol.iterator]();\n        }\n      };\n      var Pair = class {\n        constructor(options = {}) {\n          this.pair = options.pair || [];\n        }\n        key() {\n          return this.pair[0] ?? null;\n        }\n        value() {\n          return this.pair[1] ?? null;\n        }\n      };\n      var PairList = class _PairList {\n        constructor(...options) {\n          this.list = [];\n          if (options.length > 1) {\n            this.list = options.filter((entry) => Array.isArray(entry) && entry.length >= 2).map(\n              (entry) => [String(entry[0]), retainCollectionValue(this, entry[1])]\n            );\n            return;\n          }\n          const first = options.length === 0 ? {} : options[0];\n          if (Array.isArray(first)) {\n            const entries = Array.isArray(first[0]) ? first : [first];\n            this.list = entries.filter((entry) => Array.isArray(entry) && entry.length >= 2).map(\n              (entry) => [String(entry[0]), retainCollectionValue(this, entry[1])]\n            );\n            return;\n          }\n          if (Array.isArray(first.list)) {\n            this.list = first.list.filter((entry) => Array.isArray(entry) && entry.length >= 2).map(\n              (entry) => [String(entry[0]), retainCollectionValue(this, entry[1])]\n            );\n          }\n          return new Proxy(this, {\n            get(target, prop, receiver) {\n              if (typeof prop === "symbol" || prop in target) {\n                return Reflect.get(target, prop, receiver);\n              }\n              if (typeof prop === "string") {\n                return target.get(prop, null);\n              }\n              return void 0;\n            },\n            set(target, prop, value, receiver) {\n              if (typeof prop === "symbol" || prop in target) {\n                return Reflect.set(target, prop, value, receiver);\n              }\n              if (typeof prop === "string") {\n                const idx = target.list.findIndex((pair) => pair[0] === String(prop));\n                if (idx >= 0) {\n                  releaseCollectionValue(target, target.list[idx][1]);\n                  target.list[idx][1] = retainCollectionValue(target, value);\n                } else {\n                  target.list.push([\n                    String(prop),\n                    retainCollectionValue(target, value)\n                  ]);\n                }\n                return true;\n              }\n              return false;\n            }\n          });\n        }\n        length() {\n          return this.list.length;\n        }\n        count() {\n          return this.list.length;\n        }\n        empty() {\n          return this.list.length === 0 ? 1 : 0;\n        }\n        is_empty() {\n          return this.empty();\n        }\n        keys() {\n          return this.list.map((pair) => pair[0]);\n        }\n        values() {\n          return this.list.map((pair) => pair[1]);\n        }\n        enumerate() {\n          return this.to_Array();\n        }\n        has(key) {\n          return this.list.some((pair) => pair[0] === String(key)) ? 1 : 0;\n        }\n        exists(key) {\n          return this.has(key);\n        }\n        defined(key) {\n          const found = this.list.find((pair) => pair[0] === String(key));\n          return found ? found[1] == null ? 0 : 1 : 0;\n        }\n        get(key, fallback = null) {\n          const found = this.list.find((pair) => pair[0] === String(key));\n          return found ? found[1] : fallback;\n        }\n        get_all(key) {\n          return this.list.filter((pair) => pair[0] === String(key)).map((pair) => pair[1]);\n        }\n        all(key) {\n          return this.get_all(key);\n        }\n        add(key, value) {\n          this.list.push([String(key), retainCollectionValue(this, value)]);\n          return this;\n        }\n        set(key, value) {\n          return this.add(key, value);\n        }\n        kv() {\n          const out = [];\n          for (const [key, value] of this.list) {\n            out.push(key, value);\n          }\n          return out;\n        }\n        sorted_keys() {\n          return this.keys().slice().sort();\n        }\n        remove(key) {\n          if (typeof key === "function") {\n            this.list = this.list.filter((pair) => {\n              if (key(new Pair({ pair: pair.slice() }))) {\n                releaseCollectionValue(this, pair[1]);\n                return false;\n              }\n              return true;\n            });\n            return this;\n          }\n          const normalized = String(key);\n          this.list = this.list.filter((pair) => {\n            if (pair[0] === normalized) {\n              releaseCollectionValue(this, pair[1]);\n              return false;\n            }\n            return true;\n          });\n          return this;\n        }\n        for_each_key(fn2) {\n          for (const key of this.keys()) {\n            fn2(key);\n          }\n          return this;\n        }\n        for_each_value(fn2) {\n          for (const value of this.values()) {\n            fn2(value);\n          }\n          return this;\n        }\n        for_each_pair(fn2) {\n          for (const pair of this.list) {\n            fn2(new Pair({ pair: pair.slice() }));\n          }\n          return this;\n        }\n        to_Array() {\n          return this.list.map((pair) => new Pair({ pair: pair.slice() }));\n        }\n        to_Iterator() {\n          return this.keys()[Symbol.iterator]();\n        }\n        copy() {\n          return new _PairList({ list: this.list.map(([k, v]) => [k, v]) });\n        }\n        clear() {\n          releaseCollectionValues(this);\n          this.list = [];\n          return this;\n        }\n      };\n      Object.defineProperty(PairList.prototype, "__zuzu_builtin_type", {\n        value: "PairList",\n        enumerable: false,\n        configurable: true\n      });\n      function withArrayMethods() {\n        const nativeJoin = Array.prototype.join;\n        const define = (name2, fn2) => {\n          if (!Object.prototype.hasOwnProperty.call(Array.prototype, name2)) {\n            const desc = /* @__PURE__ */ Object.create(null);\n            desc.value = fn2;\n            desc.enumerable = false;\n            Object.defineProperty(Array.prototype, name2, desc);\n          }\n        };\n        if (Array.prototype.join.__zuzu_array_join !== true) {\n          const desc = /* @__PURE__ */ Object.create(null);\n          desc.value = function _join(separator, fallback) {\n            const hasFallback = arguments.length > 1;\n            let fallbackString;\n            const sep = operatorString(separator);\n            const out = [];\n            for (const value of this) {\n              try {\n                out.push(operatorString(value));\n              } catch (err) {\n                if (!hasFallback) {\n                  throw err;\n                }\n                if (typeof fallback === "function") {\n                  out.push(operatorString(fallback(value)));\n                } else {\n                  if (fallbackString === void 0) {\n                    fallbackString = operatorString(fallback);\n                  }\n                  out.push(fallbackString);\n                }\n              }\n            }\n            return nativeJoin.call(out, sep);\n          };\n          desc.value.__zuzu_array_join = true;\n          desc.enumerable = false;\n          desc.configurable = true;\n          desc.writable = true;\n          Object.defineProperty(Array.prototype, "join", desc);\n        }\n        define("count", function _count() {\n          return this.length;\n        });\n        define("empty", function _empty() {\n          return this.length === 0 ? 1 : 0;\n        });\n        define("is_empty", function _is_empty() {\n          return this.empty();\n        });\n        define("append", function _append(...values) {\n          this.push(...values.map((value) => retainCollectionValue(this, value)));\n          return this;\n        });\n        define("add", function _add(...values) {\n          this.push(...values.map((value) => retainCollectionValue(this, value)));\n          return this;\n        });\n        define("prepend", function _prepend(...values) {\n          this.unshift(...values.map((value) => retainCollectionValue(this, value)));\n          return this;\n        });\n        define("get", function _get(idx, fallback = null) {\n          return idx >= 0 && idx < this.length ? this[idx] : fallback;\n        });\n        define("set", function _set(idx, value) {\n          releaseCollectionValue(this, this[idx]);\n          this[idx] = retainCollectionValue(this, value);\n          return this;\n        });\n        define("grep", function _grep(fn2) {\n          return this.filter(fn2);\n        });\n        define("any", function _any(fn2) {\n          return this.some(fn2) ? 1 : 0;\n        });\n        define("all", function _all(fn2) {\n          return this.every(fn2) ? 1 : 0;\n        });\n        define("first", function _first(fn2) {\n          return this.find(fn2) ?? null;\n        });\n        define("remove", function _remove(fn2) {\n          for (let i = this.length - 1; i >= 0; i--) {\n            if (fn2(this[i])) {\n              releaseCollectionValue(this, this[i]);\n              this.splice(i, 1);\n            }\n          }\n          return this;\n        });\n        define("contains", function _contains(value) {\n          return this.includes(value) ? 1 : 0;\n        });\n        define("first_index", function _first_index(fn2) {\n          return this.findIndex(fn2);\n        });\n        define("reductions", function _reductions(fn2) {\n          const out = [];\n          for (const item of this) {\n            if (out.length === 0) {\n              out.push(item);\n            } else {\n              out.push(fn2(out[out.length - 1], item));\n            }\n          }\n          return out;\n        });\n        define("head", function _head(n) {\n          return this.slice(0, n);\n        });\n        define("tail", function _tail(n) {\n          return this.slice(n - 1);\n        });\n        define("sum", function _sum() {\n          return this.reduce((a, b) => Number(a) + Number(b), 0);\n        });\n        define("product", function _product() {\n          return this.reduce((a, b) => Number(a) * Number(b), 1);\n        });\n        define("shuffle", function _shuffle() {\n          return this.slice();\n        });\n        define("sample", function _sample(n) {\n          return this.slice(0, n);\n        });\n        define("for_each_value", function _for_each_value(fn2) {\n          this.forEach(fn2);\n          return this;\n        });\n        define("sortstr", function _sortstr() {\n          return this.slice().sort(stringSortComparator);\n        });\n        define(\n          "sortnum",\n          function _sortnum() {\n            return this.map((item) => Number(item)).sort((a, b) => a - b);\n          }\n        );\n        define("to_Array", function _to_array() {\n          return makeArray(this);\n        });\n        define("to_Set", function _to_set() {\n          return makeSet(this);\n        });\n        define("to_Bag", function _to_bag() {\n          return new ZuzuBag(this);\n        });\n        define("to_Iterator", function _to_iterator() {\n          return this[Symbol.iterator]();\n        });\n        define("copy", function _copy() {\n          return makeArray(this);\n        });\n        define("clear", function _clear() {\n          releaseCollectionValues(this);\n          this.splice(0, this.length);\n          return this;\n        });\n      }\n      module2.exports = {\n        ZuzuBag,\n        Pair,\n        PairList,\n        withArrayMethods\n      };\n    }\n  });\n\n  // lib/runtime-helpers.js\n  var require_runtime_helpers = __commonJS({\n    "lib/runtime-helpers.js"(exports2, module2) {\n      "use strict";\n      var { ZuzuBag, Pair, PairList, withArrayMethods } = require_collections();\n      var ZuzuBinary = class _ZuzuBinary {\n        constructor(bytes = []) {\n          if (bytes instanceof _ZuzuBinary) {\n            this.bytes = new Uint8Array(bytes.bytes);\n            return;\n          }\n          if (bytes instanceof Uint8Array) {\n            this.bytes = new Uint8Array(bytes);\n            return;\n          }\n          if (Array.isArray(bytes)) {\n            this.bytes = Uint8Array.from(bytes.map((item) => Number(item) & 255));\n            return;\n          }\n          this.bytes = new Uint8Array(0);\n        }\n        get length() {\n          return this.bytes.length;\n        }\n        byteLength() {\n          return this.bytes.length;\n        }\n        isAscii() {\n          for (const byte of this.bytes) {\n            if (byte > 127) {\n              return 0;\n            }\n          }\n          return 1;\n        }\n        slice(start, end) {\n          return new this.constructor(this.bytes.slice(start, end));\n        }\n        at(index) {\n          let idx = Number(index);\n          if (idx < 0) {\n            idx = this.bytes.length + idx;\n          }\n          if (idx < 0 || idx >= this.bytes.length) {\n            return null;\n          }\n          return new this.constructor([this.bytes[idx]]);\n        }\n        to_String() {\n          let out = "";\n          for (const byte of this.bytes) {\n            out += String.fromCharCode(byte);\n          }\n          return out;\n        }\n        toString() {\n          return this.to_String();\n        }\n        [Symbol.toPrimitive](hint) {\n          if (hint === "number") {\n            return NaN;\n          }\n          return this.to_String();\n        }\n      };\n      var BinaryString2 = class extends ZuzuBinary {\n        constructor(bytes) {\n          super(bytes);\n        }\n      };\n      var weakStates = /* @__PURE__ */ new WeakMap();\n      var retainedCollectionValues = /* @__PURE__ */ new WeakMap();\n      var ZuzuWeakCell = class {\n        constructor(value) {\n          this.value = value;\n        }\n        deref() {\n          const value = this.value;\n          if (!isWeakableValue(value)) {\n            return value;\n          }\n          const state = weakStates.get(value);\n          return state && state.strong > 0 ? value : null;\n        }\n      };\n      function isWeakCell(value) {\n        return value instanceof ZuzuWeakCell;\n      }\n      function isWeakableValue(value) {\n        if (value == null) {\n          return false;\n        }\n        if (typeof value === "boolean" || typeof value === "number" || typeof value === "string") {\n          return false;\n        }\n        const tag = Object.prototype.toString.call(value);\n        if (tag === "[object Boolean]" || tag === "[object Number]" || tag === "[object String]" || tag === "[object RegExp]") {\n          return false;\n        }\n        if (value instanceof ZuzuBinary) {\n          return false;\n        }\n        return typeof value === "object" || typeof value === "function";\n      }\n      function resolveWeakValue(value) {\n        return isWeakCell(value) ? value.deref() : value;\n      }\n      function makeWeakValue(value) {\n        return new ZuzuWeakCell(resolveWeakValue(value));\n      }\n      function retainValue(value) {\n        const resolved = resolveWeakValue(value);\n        if (isWeakableValue(resolved)) {\n          const state = weakStates.get(resolved) || { strong: 0 };\n          state.strong += 1;\n          weakStates.set(resolved, state);\n        }\n        return resolved;\n      }\n      function strongReferenceCount(value) {\n        const resolved = resolveWeakValue(value);\n        if (!isWeakableValue(resolved)) {\n          return 0;\n        }\n        const state = weakStates.get(resolved);\n        return state ? state.strong : 0;\n      }\n      function retainedValuesForCollection(collection, create = false) {\n        const resolved = resolveWeakValue(collection);\n        if (!isWeakableValue(resolved)) {\n          return null;\n        }\n        let values = retainedCollectionValues.get(resolved);\n        if (!values && create) {\n          values = [];\n          retainedCollectionValues.set(resolved, values);\n        }\n        return values || null;\n      }\n      function retainCollectionValue(collection, value) {\n        if (isWeakCell(value)) {\n          return value;\n        }\n        const retained = retainValue(value);\n        const values = retainedValuesForCollection(collection, true);\n        if (values) {\n          values.push(retained);\n        }\n        return retained;\n      }\n      function releaseCollectionValue(collection, value) {\n        const values = retainedValuesForCollection(collection);\n        if (!values) {\n          return false;\n        }\n        const idx = values.indexOf(value);\n        if (idx < 0) {\n          return false;\n        }\n        values.splice(idx, 1);\n        releaseValue(value);\n        return true;\n      }\n      function releaseCollectionValues(collection) {\n        const resolved = resolveWeakValue(collection);\n        if (!isWeakableValue(resolved)) {\n          return null;\n        }\n        const values = retainedCollectionValues.get(resolved);\n        if (!values) {\n          return null;\n        }\n        retainedCollectionValues.delete(resolved);\n        while (values.length > 0) {\n          releaseValue(values.pop());\n        }\n        return null;\n      }\n      function releaseValue(value, options = {}) {\n        if (isWeakCell(value)) {\n          return null;\n        }\n        const resolved = resolveWeakValue(value);\n        if (isWeakableValue(resolved)) {\n          const state = weakStates.get(resolved);\n          if (state) {\n            const wasStrong = state.strong;\n            state.strong = Math.max(0, state.strong - 1);\n            if (wasStrong > 0 && state.strong === 0) {\n              if (!options.preserveCollectionValues) {\n                releaseCollectionValues(resolved);\n              }\n              if (!options.suppressDemolish && typeof resolved.__demolish__ === "function") {\n                resolved.__demolish__();\n              }\n            }\n          }\n        }\n        return null;\n      }\n      function assignStrongValue(oldValue, newValue) {\n        releaseValue(oldValue);\n        return retainValue(newValue);\n      }\n      function assignWeakValue(oldValue, newValue) {\n        releaseValue(oldValue);\n        return makeWeakValue(newValue);\n      }\n      function isSetLike(value) {\n        return Object.prototype.toString.call(value) === "[object Set]";\n      }\n      function isPairListLike(value) {\n        if (value == null) {\n          return false;\n        }\n        if (value instanceof PairList) {\n          return true;\n        }\n        if (value.__zuzu_builtin_type === "PairList") {\n          return true;\n        }\n        const ctorName = value.constructor && value.constructor.name;\n        return ctorName === "PairList" || ctorName === "_PairList";\n      }\n      function collectTopLevelDeclarations(source, stripPod) {\n        const stripped = stripPod(source);\n        const masked = [];\n        let depth = 0;\n        let inSingle = false;\n        let inDouble = false;\n        let inBacktick = false;\n        let inRegex = false;\n        let inRegexClass = false;\n        let inLineComment = false;\n        let inBlockComment = false;\n        let escape = false;\n        for (let i = 0; i < stripped.length; i++) {\n          const ch = stripped[i];\n          const next = stripped[i + 1] || "";\n          if (inLineComment) {\n            if (ch === "\\n") {\n              inLineComment = false;\n              masked.push("\\n");\n            } else {\n              masked.push(" ");\n            }\n            continue;\n          }\n          if (inBlockComment) {\n            if (ch === "*" && next === "/") {\n              inBlockComment = false;\n              masked.push(" ");\n              i++;\n              masked.push(" ");\n              continue;\n            }\n            masked.push(ch === "\\n" ? "\\n" : " ");\n            continue;\n          }\n          if (inRegex) {\n            if (escape) {\n              escape = false;\n              masked.push(" ");\n              continue;\n            }\n            if (ch === "\\\\") {\n              escape = true;\n              masked.push(" ");\n              continue;\n            }\n            if (ch === "[") {\n              inRegexClass = true;\n              masked.push(" ");\n              continue;\n            }\n            if (ch === "]") {\n              inRegexClass = false;\n              masked.push(" ");\n              continue;\n            }\n            if (ch === "/" && !inRegexClass) {\n              inRegex = false;\n              masked.push(" ");\n              continue;\n            }\n            masked.push(ch === "\\n" ? "\\n" : " ");\n            continue;\n          }\n          if (inSingle || inDouble || inBacktick) {\n            if (escape) {\n              escape = false;\n              masked.push(" ");\n              continue;\n            }\n            if (ch === "\\\\") {\n              escape = true;\n              masked.push(" ");\n              continue;\n            }\n            if (inSingle && ch === "\'") {\n              inSingle = false;\n            } else if (inDouble && ch === \'"\') {\n              inDouble = false;\n            } else if (inBacktick && ch === "`") {\n              inBacktick = false;\n            }\n            masked.push(ch === "\\n" ? "\\n" : " ");\n            continue;\n          }\n          if (ch === "/" && next === "/") {\n            inLineComment = true;\n            masked.push(" ");\n            i++;\n            masked.push(" ");\n            continue;\n          }\n          if (ch === "/" && next === "*") {\n            inBlockComment = true;\n            masked.push(" ");\n            i++;\n            masked.push(" ");\n            continue;\n          }\n          if (ch === "/" && looksLikeRegexLiteralStart(stripped, i)) {\n            inRegex = true;\n            inRegexClass = false;\n            masked.push(" ");\n            continue;\n          }\n          if (ch === "\'") {\n            inSingle = true;\n            masked.push(" ");\n            continue;\n          }\n          if (ch === \'"\') {\n            inDouble = true;\n            masked.push(" ");\n            continue;\n          }\n          if (ch === "`") {\n            inBacktick = true;\n            masked.push(" ");\n            continue;\n          }\n          if (ch === "{") {\n            depth++;\n            masked.push(" ");\n            continue;\n          }\n          if (ch === "}") {\n            if (depth > 0) {\n              depth--;\n            }\n            masked.push(" ");\n            continue;\n          }\n          masked.push(depth === 0 ? ch : ch === "\\n" ? "\\n" : " ");\n        }\n        const topLevel = masked.join("");\n        const names = /* @__PURE__ */ new Set();\n        const patterns = [\n          /(?:^|[;\\n])\\s*(?:export\\s+)?(?:async\\s+)?function\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*(?:\\(|\\b)/gm,\n          /(?:^|[;\\n])\\s*(?:export\\s+)?(?:async\\s+)?fn\\s+(?:[A-Za-z_][A-Za-z0-9_]*\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*(?:\\(|\\b)/gm,\n          /(?:^|[;\\n])\\s*(?:export\\s+)?class\\s+([A-Za-z_][A-Za-z0-9_]*)\\b/gm,\n          /(?:^|[;\\n])\\s*(?:export\\s+)?trait\\s+([A-Za-z_][A-Za-z0-9_]*)\\b/gm,\n          /(?:^|[;\\n])\\s*(?:export\\s+)?(?:let|const)\\s+(?:[A-Za-z_][A-Za-z0-9_]*\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*(?::=|=|;)/gm\n        ];\n        for (const rx of patterns) {\n          let match = rx.exec(topLevel);\n          while (match) {\n            names.add(match[1]);\n            match = rx.exec(topLevel);\n          }\n        }\n        for (const name2 of collectTopLevelUnpackDeclarationNames(stripped, topLevel)) {\n          names.add(name2);\n        }\n        const importRx = /(?:^|[;\\n])\\s*from\\s+[^;\\n]+?\\s+(?:try\\s+)?import\\s+([\\s\\S]*?);/gm;\n        let importMatch = importRx.exec(topLevel);\n        while (importMatch) {\n          for (const rawPart of importMatch[1].split(",")) {\n            const part = rawPart.trim();\n            if (!part || part === "*") {\n              continue;\n            }\n            const alias = part.match(/\\bas\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*$/u);\n            if (alias) {\n              names.add(alias[1]);\n              continue;\n            }\n            const direct = part.match(/^([A-Za-z_][A-Za-z0-9_]*)\\b/u);\n            if (direct) {\n              names.add(direct[1]);\n            }\n          }\n          importMatch = importRx.exec(topLevel);\n        }\n        return [...names];\n      }\n      function looksLikeRegexLiteralStart(source, index) {\n        let pos = index - 1;\n        while (pos >= 0 && /\\s/u.test(source[pos])) {\n          pos--;\n        }\n        if (pos < 0) {\n          return true;\n        }\n        const previous = source[pos];\n        return /[({[=,:;!~?&|+\\-*%^<>]/u.test(previous);\n      }\n      function collectTopLevelUnpackDeclarationNames(source, topLevelMask) {\n        const names = [];\n        const rx = /(?:^|[;\\n])\\s*(?:export\\s+)?(?:let|const)\\b/gm;\n        let match = rx.exec(topLevelMask);\n        while (match) {\n          let cursor = rx.lastIndex;\n          while (/\\s/u.test(source[cursor] || "")) {\n            cursor++;\n          }\n          if (source[cursor] !== "{") {\n            match = rx.exec(topLevelMask);\n            continue;\n          }\n          const end = findMatchingBrace(source, cursor);\n          if (end !== -1) {\n            const pattern = source.slice(cursor + 1, end);\n            names.push(...extractUnpackBindingNames(pattern));\n            rx.lastIndex = end + 1;\n          }\n          match = rx.exec(topLevelMask);\n        }\n        return names;\n      }\n      function findMatchingBrace(source, start) {\n        let depth = 0;\n        let quote = null;\n        let escape = false;\n        for (let i = start; i < source.length; i++) {\n          const ch = source[i];\n          if (quote) {\n            if (escape) {\n              escape = false;\n            } else if (ch === "\\\\") {\n              escape = true;\n            } else if (ch === quote) {\n              quote = null;\n            }\n            continue;\n          }\n          if (ch === \'"\' || ch === "\'" || ch === "`") {\n            quote = ch;\n            continue;\n          }\n          if (ch === "{") {\n            depth++;\n          } else if (ch === "}") {\n            depth--;\n            if (depth === 0) {\n              return i;\n            }\n          }\n        }\n        return -1;\n      }\n      function extractUnpackBindingNames(pattern) {\n        const names = [];\n        for (const entry of splitTopLevel(pattern, ",")) {\n          const beforeDefault = splitFirstTopLevelOperator(entry, ":=")[0].trim();\n          if (!beforeDefault) {\n            continue;\n          }\n          const beforeWeak = beforeDefault.replace(/\\s+but\\s+weak\\s*$/u, "");\n          const aliasParts = splitFirstTopLevelOperator(beforeWeak, ":");\n          const binding = (aliasParts.length > 1 ? aliasParts[1] : aliasParts[0]).trim();\n          const match = binding.match(/(?:^|\\s)([A-Za-z_][A-Za-z0-9_]*)\\s*$/u);\n          if (match) {\n            names.push(match[1]);\n          }\n        }\n        return names;\n      }\n      function splitTopLevel(source, delimiter) {\n        const parts = [];\n        let start = 0;\n        let depth = 0;\n        let quote = null;\n        let escape = false;\n        for (let i = 0; i < source.length; i++) {\n          const ch = source[i];\n          if (quote) {\n            if (escape) {\n              escape = false;\n            } else if (ch === "\\\\") {\n              escape = true;\n            } else if (ch === quote) {\n              quote = null;\n            }\n            continue;\n          }\n          if (ch === \'"\' || ch === "\'" || ch === "`") {\n            quote = ch;\n            continue;\n          }\n          if (ch === "(" || ch === "[" || ch === "{") {\n            depth++;\n            continue;\n          }\n          if (ch === ")" || ch === "]" || ch === "}") {\n            depth = Math.max(0, depth - 1);\n            continue;\n          }\n          if (depth === 0 && source.slice(i, i + delimiter.length) === delimiter) {\n            parts.push(source.slice(start, i));\n            i += delimiter.length - 1;\n            start = i + 1;\n          }\n        }\n        parts.push(source.slice(start));\n        return parts;\n      }\n      function splitFirstTopLevelOperator(source, operator) {\n        const parts = splitTopLevel(source, operator);\n        if (parts.length <= 1) {\n          return [source];\n        }\n        return [parts[0], parts.slice(1).join(operator)];\n      }\n      function buildComparator(name2) {\n        if (name2 === "eq") {\n          return (left, right) => String(left) === String(right);\n        }\n        if (name2 === "eqi") {\n          return (left, right) => String(left).toLowerCase() === String(right).toLowerCase();\n        }\n        if (name2 === "~") {\n          return (left, right) => {\n            if (right && typeof right.test === "function") {\n              return right.test(String(left));\n            }\n            return false;\n          };\n        }\n        return (left, right) => left == right;\n      }\n      function switchTruthy(value) {\n        return !!value;\n      }\n      function runSwitch(value, cmpName, cases, defaultBody) {\n        const cmp = buildComparator(cmpName);\n        let runNext = false;\n        for (const section of cases) {\n          let matched = false;\n          if (Array.isArray(section.tests)) {\n            matched = section.tests.some((test) => switchTruthy(test(value)));\n          } else {\n            matched = section.values.some((item) => cmp(value, item));\n          }\n          if (matched || runNext) {\n            const result = section.body();\n            runNext = result === true;\n            if (!runNext && result && typeof result === "object" && result.__zuzu_return) {\n              return result;\n            }\n            if (!runNext) {\n              return;\n            }\n          }\n        }\n        if (defaultBody) {\n          const result = defaultBody();\n          if (result && typeof result === "object" && result.__zuzu_return) {\n            return result;\n          }\n        }\n      }\n      function runMatch(left, right) {\n        if (right && typeof right.test === "function") {\n          const flags = typeof right.flags === "string" ? right.flags : "";\n          const clone = new RegExp(right.source || operatorString(right), flags);\n          const input2 = operatorString(left);\n          if (flags.includes("g")) {\n            return [...input2.matchAll(clone)];\n          }\n          const matched2 = input2.match(clone);\n          return matched2 || false;\n        }\n        const input = operatorString(left);\n        const pattern = operatorRegexp(right);\n        const matched = input.match(pattern);\n        return matched || false;\n      }\n      function toArrayLike(value) {\n        if (value instanceof ZuzuBag) {\n          return value.to_Array();\n        }\n        if (isSetLike(value)) {\n          return [...value];\n        }\n        if (Array.isArray(value)) {\n          return value.slice();\n        }\n        if (value && typeof value === "object") {\n          return Object.keys(value);\n        }\n        return [];\n      }\n      function contains(collection, item) {\n        collection = resolveWeakValue(collection);\n        item = resolveWeakValue(item);\n        if (collection instanceof ZuzuBag) {\n          return collection.contains(item);\n        }\n        if (isSetLike(collection)) {\n          for (const value of collection) {\n            if (resolveWeakValue(value) === item) {\n              return 1;\n            }\n          }\n          return 0;\n        }\n        if (Array.isArray(collection)) {\n          return collection.some((value) => resolveWeakValue(value) === item) ? 1 : 0;\n        }\n        if (collection && typeof collection === "object") {\n          return Object.prototype.hasOwnProperty.call(collection, String(item)) ? 1 : 0;\n        }\n        return 0;\n      }\n      function makeLike(left, values) {\n        if (left instanceof ZuzuBag) {\n          return new ZuzuBag(values);\n        }\n        if (isSetLike(left)) {\n          return new Set(values);\n        }\n        if (Array.isArray(left)) {\n          return [...new Set(values)];\n        }\n        if (left && typeof left === "object") {\n          const out = {};\n          for (const key of values) {\n            out[String(key)] = true;\n          }\n          const desc = /* @__PURE__ */ Object.create(null);\n          desc.value = function _containsKey(key) {\n            return Object.prototype.hasOwnProperty.call(out, String(key)) ? 1 : 0;\n          };\n          desc.enumerable = false;\n          Object.defineProperty(out, "contains", desc);\n          return out;\n        }\n        return values;\n      }\n      function collectionUnion(left, right) {\n        const merged = [...toArrayLike(left), ...toArrayLike(right)];\n        const deduped = [...new Set(merged)];\n        return makeLike(left, deduped);\n      }\n      function collectionIntersection(left, right) {\n        const rightArr = toArrayLike(right);\n        return makeLike(left, toArrayLike(left).filter((item) => rightArr.includes(item)));\n      }\n      function collectionDifference(left, right) {\n        const rightArr = toArrayLike(right);\n        return makeLike(left, toArrayLike(left).filter((item) => !rightArr.includes(item)));\n      }\n      function collectionSubsetOf(left, right) {\n        const rightArr = toArrayLike(right);\n        return toArrayLike(left).every((item) => rightArr.includes(item)) ? 1 : 0;\n      }\n      function collectionSupersetOf(left, right) {\n        return collectionSubsetOf(right, left);\n      }\n      function collectionEquivalentOf(left, right) {\n        return collectionSubsetOf(left, right) && collectionSubsetOf(right, left) ? 1 : 0;\n      }\n      function makeArray(values) {\n        const array = [];\n        for (const value of values) {\n          array.push(retainCollectionValue(array, value));\n        }\n        return array;\n      }\n      function makeSet(values) {\n        const set = /* @__PURE__ */ new Set();\n        for (const value of values) {\n          addSetValue(set, value);\n        }\n        if (typeof set.to_Iterator !== "function") {\n          const desc = /* @__PURE__ */ Object.create(null);\n          desc.value = function _toIterator() {\n            return this.values();\n          };\n          desc.enumerable = false;\n          Object.defineProperty(set, "to_Iterator", desc);\n        }\n        return set;\n      }\n      function addSetValue(set, value) {\n        if (set.has(value)) {\n          return value;\n        }\n        const retained = retainCollectionValue(set, value);\n        set.add(retained);\n        return retained;\n      }\n      function makeBag(values) {\n        const bag = new ZuzuBag();\n        bag.items = values.map((value) => retainCollectionValue(bag, value));\n        return bag;\n      }\n      function makePairList(entries = []) {\n        const pairs = new PairList();\n        pairs.list = entries.map(\n          (entry) => [String(entry[0]), retainCollectionValue(pairs, entry[1])]\n        );\n        return pairs;\n      }\n      function makeTemporaryPairList(entries = []) {\n        const pairs = makePairList(entries);\n        Object.defineProperty(pairs, "__zuzu_temporary_call_args", {\n          value: true,\n          enumerable: false,\n          configurable: true\n        });\n        return pairs;\n      }\n      function lengthOf(value) {\n        if (value instanceof ZuzuBinary) {\n          return value.byteLength();\n        }\n        if (value && value.bytes instanceof Uint8Array) {\n          return value.bytes.length;\n        }\n        if (isPairListLike(value)) {\n          return value.length();\n        }\n        if (value instanceof ZuzuBag) {\n          return value.length();\n        }\n        if (isSetLike(value)) {\n          return value.size;\n        }\n        if (typeof value === "string") {\n          return [...value].length;\n        }\n        if (Array.isArray(value)) {\n          return value.length;\n        }\n        if (value && typeof value === "object") {\n          return Object.keys(value).length;\n        }\n        return 0;\n      }\n      function typeName2(value) {\n        value = resolveWeakValue(value);\n        if (value == null) {\n          return "Null";\n        }\n        if (value instanceof ZuzuBinary) {\n          return "BinaryString";\n        }\n        if (isPairListLike(value)) {\n          return "PairList";\n        }\n        if (value instanceof ZuzuBag) {\n          return "Bag";\n        }\n        if (isSetLike(value)) {\n          return "Set";\n        }\n        if (Array.isArray(value)) {\n          return "Array";\n        }\n        if (value instanceof Pair) {\n          return "Pair";\n        }\n        if (value instanceof RegExp || Object.prototype.toString.call(value) === "[object RegExp]") {\n          return "Regexp";\n        }\n        if (typeof value === "boolean" || Object.prototype.toString.call(value) === "[object Boolean]") {\n          return "Boolean";\n        }\n        if (typeof value === "number" || Object.prototype.toString.call(value) === "[object Number]") {\n          return "Number";\n        }\n        if (typeof value === "string" || Object.prototype.toString.call(value) === "[object String]") {\n          return "String";\n        }\n        if (typeof value === "function") {\n          const source = Function.prototype.toString.call(value);\n          return /^\\s*class\\b/.test(source) ? "Class" : "Function";\n        }\n        if (value && value.constructor && value.constructor.name) {\n          const name2 = value.constructor.name;\n          return name2 === "Object" ? "Dict" : name2;\n        }\n        return "Object";\n      }\n      function renderNumber(value) {\n        if (Object.is(value, -0)) {\n          return "0";\n        }\n        return String(value);\n      }\n      function operatorString(value) {\n        value = resolveWeakValue(value);\n        if (value == null) {\n          return "";\n        }\n        if (typeof value === "string" || Object.prototype.toString.call(value) === "[object String]") {\n          return String(value);\n        }\n        if (typeof value === "number" || Object.prototype.toString.call(value) === "[object Number]") {\n          return renderNumber(Number(value));\n        }\n        if (typeof value === "boolean" || Object.prototype.toString.call(value) === "[object Boolean]") {\n          return value.valueOf() ? "true" : "false";\n        }\n        if (value instanceof RegExp || Object.prototype.toString.call(value) === "[object RegExp]") {\n          return value.source || "";\n        }\n        if (value instanceof ZuzuBinary) {\n          throw new Error(`TypeException: cannot coerce ${typeName2(value)} to String`);\n        }\n        if (typeof value === "function" || value.__zuzu_method === true || value.constructor && value.constructor.name === "ZuzuMethod") {\n          throw new Error(`TypeException: cannot coerce ${typeName2(value)} to String`);\n        }\n        if (value && typeof value.to_String === "function") {\n          return operatorString(value.to_String());\n        }\n        throw new Error(`TypeException: cannot coerce ${typeName2(value)} to String`);\n      }\n      var surrogatePattern = /[\\uD800-\\uDFFF]/;\n      function codePointStringCompare(left, right) {\n        if (left === right) {\n          return 0;\n        }\n        if (surrogatePattern.test(left) || surrogatePattern.test(right)) {\n          const leftPoints = Array.from(left);\n          const rightPoints = Array.from(right);\n          const shared = Math.min(leftPoints.length, rightPoints.length);\n          for (let i = 0; i < shared; i++) {\n            const a = leftPoints[i].codePointAt(0);\n            const b = rightPoints[i].codePointAt(0);\n            if (a !== b) {\n              return a < b ? -1 : 1;\n            }\n          }\n          if (leftPoints.length === rightPoints.length) {\n            return 0;\n          }\n          return leftPoints.length < rightPoints.length ? -1 : 1;\n        }\n        return left < right ? -1 : 1;\n      }\n      function stringSortComparator(a, b) {\n        return codePointStringCompare(String(a), String(b));\n      }\n      function operatorRegexp(value) {\n        value = resolveWeakValue(value);\n        if (value instanceof RegExp || Object.prototype.toString.call(value) === "[object RegExp]") {\n          const flags = typeof value.flags === "string" ? value.flags : "";\n          return new RegExp(value.source || "", flags);\n        }\n        return new RegExp(operatorString(value));\n      }\n      module2.exports = {\n        collectTopLevelDeclarations,\n        runSwitch,\n        runMatch,\n        toArrayLike,\n        contains,\n        collectionUnion,\n        collectionIntersection,\n        collectionDifference,\n        collectionSubsetOf,\n        collectionSupersetOf,\n        collectionEquivalentOf,\n        makeArray,\n        makeSet,\n        makeBag,\n        makePairList,\n        makeTemporaryPairList,\n        lengthOf,\n        operatorString,\n        operatorRegexp,\n        codePointStringCompare,\n        stringSortComparator,\n        ZuzuBinary,\n        BinaryString: BinaryString2,\n        ZuzuWeakCell,\n        isWeakCell,\n        isWeakableValue,\n        isPairListLike,\n        makeWeakValue,\n        resolveWeakValue,\n        retainValue,\n        releaseValue,\n        strongReferenceCount,\n        retainCollectionValue,\n        releaseCollectionValue,\n        releaseCollectionValues,\n        addSetValue,\n        assignStrongValue,\n        assignWeakValue,\n        ZuzuBag,\n        Pair,\n        PairList,\n        withArrayMethods\n      };\n    }\n  });\n\n  // modules/std/string.js\n  var require_string = __commonJS({\n    "modules/std/string.js"(exports2, module2) {\n      "use strict";\n      var { BinaryString: BinaryString2 } = require_runtime_helpers();\n      function toStringValue(value) {\n        if (value instanceof RegExp) {\n          return value.source;\n        }\n        if (value && typeof value.to_String === "function") {\n          return String(value.to_String());\n        }\n        if (value instanceof Error) {\n          return value.message || value.name || String(value);\n        }\n        return value == null ? "" : String(value);\n      }\n      function isRegexLike(value) {\n        if (value == null) {\n          return false;\n        }\n        if (value instanceof RegExp) {\n          return true;\n        }\n        return Object.prototype.toString.call(value) === "[object RegExp]";\n      }\n      function index(text, needle, start = 0) {\n        const haystack = [...toStringValue(text)];\n        const find = [...toStringValue(needle)];\n        const offset = Math.max(0, Math.trunc(Number(start ?? 0)));\n        if (find.length === 0) {\n          return Math.min(offset, haystack.length);\n        }\n        for (let i = offset; i <= haystack.length - find.length; i++) {\n          let matched = true;\n          for (let j = 0; j < find.length; j++) {\n            if (haystack[i + j] !== find[j]) {\n              matched = false;\n              break;\n            }\n          }\n          if (matched) {\n            return i;\n          }\n        }\n        return -1;\n      }\n      function rindex(text, needle, start = null) {\n        const haystack = [...toStringValue(text)];\n        const find = [...toStringValue(needle)];\n        if (start == null) {\n          start = haystack.length - find.length;\n        } else {\n          start = Math.trunc(Number(start));\n        }\n        if (find.length === 0) {\n          return Math.min(Math.max(0, start), haystack.length);\n        }\n        start = Math.min(Math.max(0, start), haystack.length - find.length);\n        for (let i = start; i >= 0; i--) {\n          let matched = true;\n          for (let j = 0; j < find.length; j++) {\n            if (haystack[i + j] !== find[j]) {\n              matched = false;\n              break;\n            }\n          }\n          if (matched) {\n            return i;\n          }\n        }\n        return -1;\n      }\n      function contains(text, needle) {\n        return index(text, needle) >= 0;\n      }\n      function integerValue(value, label) {\n        const number = Number(value ?? 0);\n        if (!Number.isInteger(number)) {\n          throw new Error(`${label} expects an integer`);\n        }\n        return number;\n      }\n      function chr(codepoint) {\n        if (arguments.length !== 1) {\n          throw new Error("chr() expects one argument");\n        }\n        const value = integerValue(codepoint, "chr()");\n        if (value < 0 || value > 1114111) {\n          throw new Error("chr() expects a Unicode code point in 0..0x10FFFF");\n        }\n        if (value >= 55296 && value <= 57343) {\n          throw new Error("chr() rejects surrogate code points");\n        }\n        return String.fromCodePoint(value);\n      }\n      function ord(text, index2 = 0) {\n        if (arguments.length < 1 || arguments.length > 2) {\n          throw new Error("ord() expects one or two arguments");\n        }\n        const chars = [...toStringValue(text)];\n        const offset = integerValue(index2, "ord()");\n        if (offset < 0 || offset >= chars.length) {\n          throw new Error("ord() index out of range");\n        }\n        return chars[offset].codePointAt(0);\n      }\n      function substr(text, offset, length = null) {\n        const chars = [...toStringValue(text)];\n        const from = Number(offset ?? 0);\n        if (length == null) {\n          return chars.slice(from).join("");\n        }\n        return chars.slice(from, from + Number(length)).join("");\n      }\n      function pattern_to_regexp(pattern, caseInsensitive = false) {\n        return new RegExp(String(pattern ?? ""), caseInsensitive ? "i" : "");\n      }\n      var REGEXP_META_CHARS = /* @__PURE__ */ new Set([\n        "\\\\",\n        "/",\n        "^",\n        "$",\n        ".",\n        "|",\n        "?",\n        "*",\n        "+",\n        "(",\n        ")",\n        "[",\n        "]",\n        "{",\n        "}",\n        \'"\',\n        "\'"\n      ]);\n      function quotemeta(text) {\n        return [...toStringValue(text)].map((ch) => REGEXP_META_CHARS.has(ch) ? `\\\\${ch}` : ch).join("");\n      }\n      function normalizePattern(pattern, flags = "") {\n        if (isRegexLike(pattern)) {\n          const mergedFlags = [...pattern.flags || "", ...flags || ""];\n          const uniqFlags = [...new Set(mergedFlags)].join("");\n          return new RegExp(pattern.source, uniqFlags);\n        }\n        return new RegExp(String(pattern ?? ""), flags);\n      }\n      function search(text, pattern, flags = "") {\n        const match = toStringValue(text).match(normalizePattern(pattern, flags));\n        return match ? match[0] : null;\n      }\n      function matches(text, pattern, flags = "") {\n        return normalizePattern(pattern, flags).test(toStringValue(text));\n      }\n      function replace(text, pattern, replacement, flags = "") {\n        return toStringValue(text).replace(normalizePattern(pattern, flags), toStringValue(replacement));\n      }\n      function sprint(format, ...args) {\n        let idx = 0;\n        return toStringValue(format).replace(/%([0-9]+)?(?:\\.([0-9]+))?([sdfc])/gu, (_token, width, precision, kind) => {\n          const value = args[idx++];\n          let out = "";\n          if (kind === "d") {\n            out = String(Math.trunc(Number(value ?? 0)));\n          } else if (kind === "f") {\n            const num = Number(value ?? 0);\n            out = precision != null ? num.toFixed(Number(precision)) : String(num);\n          } else if (kind === "c") {\n            out = String.fromCharCode(Number(value ?? 0));\n          } else {\n            out = toStringValue(value);\n          }\n          if (width != null) {\n            const target = Number(width);\n            if (out.length < target) {\n              out = `${" ".repeat(target - out.length)}${out}`;\n            }\n          }\n          return out;\n        });\n      }\n      function join(separator, values) {\n        const sep = toStringValue(separator);\n        if (Array.isArray(values)) {\n          return values.map((value) => toStringValue(value)).join(sep);\n        }\n        if (values == null) {\n          return "";\n        }\n        if (typeof values.to_Iterator === "function") {\n          const out = [];\n          for (const value of values.to_Iterator()) {\n            out.push(toStringValue(value));\n          }\n          return out.join(sep);\n        }\n        if (typeof values.to_Array === "function") {\n          return join(sep, values.to_Array());\n        }\n        if (typeof values[Symbol.iterator] === "function") {\n          return Array.from(values, (value) => toStringValue(value)).join(sep);\n        }\n        return toStringValue(values);\n      }\n      function split(text, pattern) {\n        return toStringValue(text).split(pattern);\n      }\n      function starts_with(text, prefix) {\n        return toStringValue(text).startsWith(toStringValue(prefix));\n      }\n      function ends_with(text, suffix) {\n        return toStringValue(text).endsWith(toStringValue(suffix));\n      }\n      function trim(text) {\n        return toStringValue(text).trim();\n      }\n      function pad(text, width, ch = " ", side = "right") {\n        const src = toStringValue(text);\n        const padChar = toStringValue(ch || " ");\n        const target = Number(width ?? 0);\n        if (src.length >= target) {\n          return src;\n        }\n        const fill = padChar.repeat(target - src.length);\n        return side === "left" ? `${fill}${src}` : `${src}${fill}`;\n      }\n      function chomp(text) {\n        return toStringValue(text).replace(/\\r?\\n$/u, "");\n      }\n      function words(text) {\n        return toStringValue(text).replace(/([a-z0-9])([A-Z])/gu, "$1 $2").replace(/[_\\-]+/gu, " ").trim().split(/\\s+/u).filter(Boolean);\n      }\n      function title(text) {\n        return words(text).map((w) => `${w[0].toUpperCase()}${w.slice(1).toLowerCase()}`).join(" ");\n      }\n      function snake(text) {\n        return words(text).map((w) => w.toLowerCase()).join("_");\n      }\n      function kebab(text) {\n        return words(text).map((w) => w.toLowerCase()).join("-");\n      }\n      function camel(text) {\n        const ws = words(text).map((w) => w.toLowerCase());\n        return ws.map((w, i) => i === 0 ? w : `${w[0].toUpperCase()}${w.slice(1)}`).join("");\n      }\n      function to_binary(value) {\n        if (typeof value !== "string" && !(value instanceof String)) {\n          const type = value == null ? "Null" : value && value.bytes instanceof Uint8Array ? "BinaryString" : typeof value;\n          throw new Error(`TypeException: to_binary expects String, got ${type}`);\n        }\n        return new BinaryString2(new TextEncoder().encode(String(value)));\n      }\n      function to_string(value) {\n        if (!(value && value.bytes instanceof Uint8Array)) {\n          throw new Error("TypeException: to_string expects BinaryString");\n        }\n        return new TextDecoder("utf-8", { fatal: true }).decode(value.bytes);\n      }\n      module2.exports = {\n        camel,\n        chomp,\n        chr,\n        contains,\n        ends_with,\n        index,\n        join,\n        kebab,\n        matches,\n        ord,\n        pad,\n        pattern_to_regexp,\n        quotemeta,\n        rindex,\n        replace,\n        search,\n        snake,\n        split,\n        starts_with,\n        sprint,\n        substr,\n        title,\n        to_binary,\n        to_string,\n        trim\n      };\n    }\n  });\n\n  // modules/std/string/base64.js\n  var require_base64 = __commonJS({\n    "modules/std/string/base64.js"(exports2, module2) {\n      "use strict";\n      var { BinaryString: BinaryString2 } = require_runtime_helpers();\n      var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";\n      var DECODE = (() => {\n        const out = /* @__PURE__ */ Object.create(null);\n        for (let i = 0; i < ALPHABET.length; i++) {\n          out[ALPHABET[i]] = i;\n        }\n        return out;\n      })();\n      function typeName2(value) {\n        if (value == null) {\n          return "Null";\n        }\n        if (typeof value === "string") {\n          return "String";\n        }\n        if (value.bytes instanceof Uint8Array) {\n          return "BinaryString";\n        }\n        return value.constructor && value.constructor.name ? value.constructor.name : typeof value;\n      }\n      function encodeBytes(bytes) {\n        let out = "";\n        for (let i = 0; i < bytes.length; i += 3) {\n          const b0 = bytes[i];\n          const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;\n          const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;\n          out += ALPHABET[b0 >> 2];\n          out += ALPHABET[(b0 & 3) << 4 | b1 >> 4];\n          out += i + 1 < bytes.length ? ALPHABET[(b1 & 15) << 2 | b2 >> 6] : "=";\n          out += i + 2 < bytes.length ? ALPHABET[b2 & 63] : "=";\n        }\n        return out;\n      }\n      function decodeText(value) {\n        const clean = String(value).replace(/\\s+/gu, "");\n        if (clean.length % 4 !== 0) {\n          throw new Error("Exception: invalid Base64 length");\n        }\n        let padding = 0;\n        if (clean.endsWith("==")) {\n          padding = 2;\n        } else if (clean.endsWith("=")) {\n          padding = 1;\n        }\n        const bytes = [];\n        for (let i = 0; i < clean.length; i += 4) {\n          const chunk = clean.slice(i, i + 4);\n          const values = [];\n          for (let j = 0; j < 4; j++) {\n            const ch = chunk[j];\n            if (ch === "=") {\n              values.push(0);\n              continue;\n            }\n            if (DECODE[ch] == null) {\n              throw new Error(`Exception: invalid Base64 character \'${ch}\'`);\n            }\n            values.push(DECODE[ch]);\n          }\n          const triple = values[0] << 18 | values[1] << 12 | values[2] << 6 | values[3];\n          bytes.push(triple >> 16 & 255);\n          if (chunk[2] !== "=") {\n            bytes.push(triple >> 8 & 255);\n          }\n          if (chunk[3] !== "=") {\n            bytes.push(triple & 255);\n          }\n        }\n        const firstPadding = clean.indexOf("=");\n        if (firstPadding >= 0 && firstPadding !== clean.length - padding) {\n          throw new Error("Exception: invalid Base64 padding");\n        }\n        return new Uint8Array(bytes);\n      }\n      function encode(value) {\n        if (!(value && value.bytes instanceof Uint8Array)) {\n          throw new Error(`TypeException: encode expects BinaryString, got ${typeName2(value)}`);\n        }\n        return encodeBytes(value.bytes);\n      }\n      function decode(value) {\n        if (typeof value !== "string") {\n          throw new Error(`TypeException: decode expects String, got ${typeName2(value)}`);\n        }\n        return new BinaryString2(decodeText(value));\n      }\n      function encode_urlsafe(value) {\n        return encode(value).replace(/\\+/gu, "-").replace(/\\//gu, "_").replace(/=+$/gu, "");\n      }\n      function decode_urlsafe(value) {\n        if (typeof value !== "string") {\n          throw new Error(`TypeException: decode expects String, got ${typeName2(value)}`);\n        }\n        let normalized = value.replace(/-/gu, "+").replace(/_/gu, "/");\n        const mod = normalized.length % 4;\n        if (mod !== 0) {\n          normalized += "=".repeat(4 - mod);\n        }\n        return decode(normalized);\n      }\n      module2.exports = {\n        decode,\n        decode_urlsafe,\n        encode,\n        encode_urlsafe\n      };\n    }\n  });\n\n  // modules/std/string/encode.js\n  var require_encode = __commonJS({\n    "modules/std/string/encode.js"(exports2, module2) {\n      "use strict";\n      var { BinaryString: BinaryString2 } = require_runtime_helpers();\n      function typeName2(value) {\n        if (value == null) {\n          return "Null";\n        }\n        if (typeof value === "string" || value instanceof String) {\n          return "String";\n        }\n        if (value.bytes instanceof Uint8Array) {\n          return "BinaryString";\n        }\n        return value.constructor && value.constructor.name ? value.constructor.name : typeof value;\n      }\n      function canonicalEncoding(name2) {\n        const upper = String(name2 == null ? "UTF-8" : name2).toUpperCase().replace(/\\s+/g, "");\n        if (upper === "UTF-8" || upper === "UTF8") {\n          return "utf8";\n        }\n        if (upper === "UTF-16" || upper === "UTF16" || upper === "UTF-16BE") {\n          return "utf16";\n        }\n        if (upper === "UTF-32" || upper === "UTF32" || upper === "UTF-32BE") {\n          return "utf32";\n        }\n        if (upper === "ISO-8859-1" || upper === "ISO8859-1" || upper === "LATIN-1" || upper === "LATIN1" || upper === "LATIN") {\n          return "latin1";\n        }\n        return null;\n      }\n      function codePoints(text) {\n        return Array.from(text, (ch) => ch.codePointAt(0));\n      }\n      function encode(value, encoding) {\n        if (typeName2(value) !== "String") {\n          throw new Error(`TypeException: encode expects String, got ${typeName2(value)}`);\n        }\n        const text = String(value);\n        const codec = canonicalEncoding(encoding);\n        if (codec === "utf8") {\n          return new BinaryString2(new TextEncoder().encode(text));\n        }\n        if (codec === "utf16") {\n          const out = [];\n          for (let i = 0; i < text.length; i++) {\n            const unit = text.charCodeAt(i);\n            out.push(unit >> 8 & 255, unit & 255);\n          }\n          return new BinaryString2(out);\n        }\n        if (codec === "utf32") {\n          const out = [];\n          for (const point of codePoints(text)) {\n            out.push(\n              point >>> 24 & 255,\n              point >>> 16 & 255,\n              point >>> 8 & 255,\n              point & 255\n            );\n          }\n          return new BinaryString2(out);\n        }\n        if (codec === "latin1") {\n          const out = [];\n          for (const point of codePoints(text)) {\n            if (point > 255) {\n              const hex = point.toString(16).toUpperCase().padStart(4, "0");\n              throw new Error(`Exception: Character U+${hex} cannot be encoded as ISO-8859-1`);\n            }\n            out.push(point);\n          }\n          return new BinaryString2(out);\n        }\n        throw new Error(`Exception: Unsupported encoding: ${encoding}`);\n      }\n      function decode(value, encoding) {\n        if (typeName2(value) !== "BinaryString") {\n          throw new Error(`TypeException: decode expects BinaryString, got ${typeName2(value)}`);\n        }\n        let bytes = value.bytes;\n        const codec = canonicalEncoding(encoding);\n        if (codec === "utf8") {\n          try {\n            return new TextDecoder("utf-8", { fatal: true }).decode(bytes);\n          } catch (_err) {\n            throw new Error("Exception: Invalid UTF-8 in BinaryString");\n          }\n        }\n        if (codec === "utf16") {\n          let bigEndian = true;\n          if (bytes.length >= 2 && bytes[0] === 254 && bytes[1] === 255) {\n            bytes = bytes.subarray(2);\n          } else if (bytes.length >= 2 && bytes[0] === 255 && bytes[1] === 254) {\n            bigEndian = false;\n            bytes = bytes.subarray(2);\n          }\n          if (bytes.length % 2 !== 0) {\n            throw new Error("Exception: UTF-16 input length must be a multiple of 2 bytes");\n          }\n          const units = [];\n          for (let i = 0; i < bytes.length; i += 2) {\n            units.push(bigEndian ? bytes[i] << 8 | bytes[i + 1] : bytes[i + 1] << 8 | bytes[i]);\n          }\n          let out = "";\n          for (let i = 0; i < units.length; i++) {\n            const unit = units[i];\n            if (unit >= 55296 && unit <= 56319) {\n              const next = units[i + 1];\n              if (next == null || next < 56320 || next > 57343) {\n                throw new Error("Exception: Invalid UTF-16 in BinaryString");\n              }\n              out += String.fromCharCode(unit, next);\n              i++;\n              continue;\n            }\n            if (unit >= 56320 && unit <= 57343) {\n              throw new Error("Exception: Invalid UTF-16 in BinaryString");\n            }\n            out += String.fromCharCode(unit);\n          }\n          return out;\n        }\n        if (codec === "utf32") {\n          let bigEndian = true;\n          if (bytes.length >= 4 && bytes[0] === 0 && bytes[1] === 0 && bytes[2] === 254 && bytes[3] === 255) {\n            bytes = bytes.subarray(4);\n          } else if (bytes.length >= 4 && bytes[0] === 255 && bytes[1] === 254 && bytes[2] === 0 && bytes[3] === 0) {\n            bigEndian = false;\n            bytes = bytes.subarray(4);\n          }\n          if (bytes.length % 4 !== 0) {\n            throw new Error("Exception: UTF-32 input length must be a multiple of 4 bytes");\n          }\n          let out = "";\n          for (let i = 0; i < bytes.length; i += 4) {\n            const point = bigEndian ? bytes[i] * 16777216 + (bytes[i + 1] << 16) + (bytes[i + 2] << 8) + bytes[i + 3] : bytes[i + 3] * 16777216 + (bytes[i + 2] << 16) + (bytes[i + 1] << 8) + bytes[i];\n            if (point > 1114111 || point >= 55296 && point <= 57343) {\n              throw new Error("Exception: Invalid UTF-32 in BinaryString");\n            }\n            out += String.fromCodePoint(point);\n          }\n          return out;\n        }\n        if (codec === "latin1") {\n          let out = "";\n          for (const byte of bytes) {\n            out += String.fromCharCode(byte);\n          }\n          return out;\n        }\n        throw new Error(`Exception: Unsupported encoding: ${encoding}`);\n      }\n      module2.exports = {\n        encode,\n        decode,\n        ENCODING_UTF8: "UTF-8",\n        ENCODING_UTF16: "UTF-16",\n        ENCODING_UTF32: "UTF-32",\n        ENCODING_LATIN: "ISO-8859-1"\n      };\n    }\n  });\n\n  // modules/std/time.js\n  var require_time = __commonJS({\n    "modules/std/time.js"(exports2, module2) {\n      "use strict";\n      var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];\n      var MONTH_BY_NAME = /* @__PURE__ */ new Map([\n        ["jan", 1],\n        ["january", 1],\n        ["feb", 2],\n        ["february", 2],\n        ["mar", 3],\n        ["march", 3],\n        ["apr", 4],\n        ["april", 4],\n        ["may", 5],\n        ["jun", 6],\n        ["june", 6],\n        ["jul", 7],\n        ["july", 7],\n        ["aug", 8],\n        ["august", 8],\n        ["sep", 9],\n        ["sept", 9],\n        ["september", 9],\n        ["oct", 10],\n        ["october", 10],\n        ["nov", 11],\n        ["november", 11],\n        ["dec", 12],\n        ["december", 12]\n      ]);\n      var DAY_ABBR = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];\n      var WEEKDAY_BY_NAME = /* @__PURE__ */ new Set([\n        "sun",\n        "sunday",\n        "mon",\n        "monday",\n        "tue",\n        "tues",\n        "tuesday",\n        "wed",\n        "weds",\n        "wednesday",\n        "thu",\n        "thur",\n        "thurs",\n        "thursday",\n        "fri",\n        "friday",\n        "sat",\n        "saturday"\n      ]);\n      function defineType(object, name2) {\n        Object.defineProperty(object, "__zuzu_type_name", {\n          value: name2,\n          enumerable: false,\n          configurable: true\n        });\n      }\n      function zoneName(zone) {\n        if (zone instanceof TimeZone) {\n          return zone.name();\n        }\n        if (zone == null || String(zone) === "") {\n          return "UTC";\n        }\n        const text = String(zone);\n        if (/^z$/iu.test(text) || /^gmt$/iu.test(text)) {\n          return "UTC";\n        }\n        if (/^([+-]\\d\\d):?(\\d\\d)$/u.test(text)) {\n          return text.replace(/^([+-]\\d\\d):?(\\d\\d)$/u, "$1:$2");\n        }\n        return text;\n      }\n      function isFixedOffset(zone) {\n        return /^([+-]\\d\\d):(\\d\\d)$/u.test(zoneName(zone));\n      }\n      function offsetSeconds(zone) {\n        const m = zoneName(zone).match(/^([+-])(\\d\\d):(\\d\\d)$/u);\n        if (!m) {\n          return null;\n        }\n        const seconds = Number(m[2]) * 3600 + Number(m[3]) * 60;\n        return m[1] === "-" ? -seconds : seconds;\n      }\n      function pad(value, width = 2, fill = "0") {\n        return String(value).padStart(width, fill);\n      }\n      function stripTrailingPeriod(text) {\n        return String(text).replace(/\\.+$/u, "").toLowerCase();\n      }\n      function weekdayIndex(parts) {\n        const date = new Date(\n          parts.year,\n          parts.month - 1,\n          parts.day\n        );\n        return (date.getDay() + 6) % 7 + 1;\n      }\n      function weekParts(parts) {\n        const date = new Date(\n          parts.year,\n          parts.month - 1,\n          parts.day\n        );\n        const weekDay = date.getDay() || 7;\n        const shifted = new Date(date);\n        shifted.setDate(date.getDate() + 4 - weekDay);\n        const weekYear = shifted.getFullYear();\n        const yearStart = new Date(weekYear, 0, 1);\n        return {\n          year: weekYear,\n          week: Math.ceil((shifted - yearStart) / 864e5 / 7 + 1)\n        };\n      }\n      function dayOfMonthForDisplay(day) {\n        return String(day).padStart(2, " ");\n      }\n      function dayOfYear(parts) {\n        const start = new Date(parts.year, 0, 1);\n        const now = new Date(parts.year, parts.month - 1, parts.day);\n        return (now - start) / 864e5;\n      }\n      function julianDay(parts) {\n        let year = parts.year;\n        let month = parts.month;\n        const day = parts.day;\n        if (month <= 2) {\n          year -= 1;\n          month += 12;\n        }\n        const a = Math.floor((14 - month) / 12);\n        const y = year + 4800 - a;\n        const m = month + 12 * a - 3;\n        const jd = day + Math.floor((153 * m + 2) / 5) + 365 * y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) - 32045;\n        const fraction = (parts.hour * 3600 + parts.minute * 60 + parts.second) / 86400;\n        return jd + fraction - 0.5;\n      }\n      function isLeapYear(year) {\n        if (year % 4 !== 0) return false;\n        if (year % 100 !== 0) return true;\n        return year % 400 === 0;\n      }\n      function daysInMonth(year, month) {\n        if ([1, 3, 5, 7, 8, 10, 12].includes(month)) return 31;\n        if ([4, 6, 9, 11].includes(month)) return 30;\n        if (month === 2) return isLeapYear(year) ? 29 : 28;\n        return 0;\n      }\n      function normaliseParts(parts) {\n        if (parts.hour === 24) {\n          parts.hour = 0;\n        }\n        return parts;\n      }\n      function partsForEpoch(epoch, zone) {\n        const name2 = zoneName(zone);\n        if (isFixedOffset(name2)) {\n          const d = new Date((epoch + offsetSeconds(name2)) * 1e3);\n          return {\n            year: d.getUTCFullYear(),\n            month: d.getUTCMonth() + 1,\n            day: d.getUTCDate(),\n            hour: d.getUTCHours(),\n            minute: d.getUTCMinutes(),\n            second: d.getUTCSeconds(),\n            offset: offsetSeconds(name2)\n          };\n        }\n        const formatter = new Intl.DateTimeFormat("en-GB-u-ca-gregory", {\n          timeZone: name2 === "local" ? void 0 : name2,\n          year: "numeric",\n          month: "2-digit",\n          day: "2-digit",\n          hour: "2-digit",\n          minute: "2-digit",\n          second: "2-digit",\n          hourCycle: "h23"\n        });\n        const out = {};\n        for (const part of formatter.formatToParts(new Date(epoch * 1e3))) {\n          if (part.type === "year") out.year = Number(part.value);\n          if (part.type === "month") out.month = Number(part.value);\n          if (part.type === "day") out.day = Number(part.value);\n          if (part.type === "hour") out.hour = Number(part.value);\n          if (part.type === "minute") out.minute = Number(part.value);\n          if (part.type === "second") out.second = Number(part.value);\n        }\n        return normaliseParts(out);\n      }\n      function offsetForEpoch(epoch, zone) {\n        if (isFixedOffset(zone)) {\n          return offsetSeconds(zone);\n        }\n        const parts = partsForEpoch(epoch, zone);\n        const naive = Date.UTC(\n          parts.year,\n          parts.month - 1,\n          parts.day,\n          parts.hour,\n          parts.minute,\n          parts.second\n        ) / 1e3;\n        return naive - Math.floor(epoch);\n      }\n      function sameWallEpoch(wall, zone) {\n        const name2 = zoneName(zone);\n        let current = { ...wall };\n        for (let shift = 0; shift <= 180; shift++) {\n          if (shift > 0) {\n            const shifted = new Date(Date.UTC(\n              wall.year,\n              wall.month - 1,\n              wall.day,\n              wall.hour,\n              wall.minute + shift,\n              wall.second\n            ));\n            current = {\n              year: shifted.getUTCFullYear(),\n              month: shifted.getUTCMonth() + 1,\n              day: shifted.getUTCDate(),\n              hour: shifted.getUTCHours(),\n              minute: shifted.getUTCMinutes(),\n              second: shifted.getUTCSeconds()\n            };\n          }\n          const naive = Date.UTC(\n            current.year,\n            current.month - 1,\n            current.day,\n            current.hour,\n            current.minute,\n            current.second\n          ) / 1e3;\n          const offsets = /* @__PURE__ */ new Set([\n            offsetForEpoch(naive - 172800, name2),\n            offsetForEpoch(naive - 86400, name2),\n            offsetForEpoch(naive - 3600, name2),\n            offsetForEpoch(naive, name2),\n            offsetForEpoch(naive + 3600, name2),\n            offsetForEpoch(naive + 86400, name2),\n            offsetForEpoch(naive + 172800, name2)\n          ]);\n          const candidates = [];\n          for (const offset of offsets) {\n            const candidate = naive - offset;\n            const check = partsForEpoch(candidate, name2);\n            if (check.year === current.year && check.month === current.month && check.day === current.day && check.hour === current.hour && check.minute === current.minute && check.second === current.second) {\n              candidates.push(candidate);\n            }\n          }\n          if (candidates.length) {\n            return Math.min(...candidates) + (wall.fraction || 0);\n          }\n        }\n        return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) / 1e3;\n      }\n      function addMonthsToWall(parts, months) {\n        const total = parts.year * 12 + (parts.month - 1) + Number(months);\n        const year = Math.floor(total / 12);\n        const month = (total % 12 + 12) % 12 + 1;\n        const last = new Date(Date.UTC(year, month, 0)).getUTCDate();\n        return { ...parts, year, month, day: Math.min(parts.day, last) };\n      }\n      function formatOffset(seconds, colon = true) {\n        const sign = seconds < 0 ? "-" : "+";\n        const abs = Math.abs(seconds);\n        const text = `${sign}${pad(Math.floor(abs / 3600))}${pad(Math.floor(abs % 3600 / 60))}`;\n        return colon ? `${text.slice(0, 3)}:${text.slice(3)}` : text;\n      }\n      function parseOffset(text) {\n        if (text == null || /^(?:z|utc|gmt)$/iu.test(text)) {\n          return 0;\n        }\n        if (/^ut$/iu.test(text)) {\n          return 0;\n        }\n        const m = String(text).match(/^([+-])(\\d\\d):?(\\d\\d)$/u);\n        if (!m) {\n          return null;\n        }\n        const hours = Number(m[2]);\n        const minutes = Number(m[3]);\n        if (hours > 23 || minutes > 59) {\n          return null;\n        }\n        const value = hours * 3600 + minutes * 60;\n        return m[1] === "-" ? -value : value;\n      }\n      function parseRfc5322Zone(text) {\n        const offset = parseOffset(text);\n        if (offset != null) {\n          return offset;\n        }\n        const key = String(text).toUpperCase();\n        const legacy = {\n          EST: -5 * 3600,\n          EDT: -4 * 3600,\n          CST: -6 * 3600,\n          CDT: -5 * 3600,\n          MST: -7 * 3600,\n          MDT: -6 * 3600,\n          PST: -8 * 3600,\n          PDT: -7 * 3600\n        };\n        if (Object.prototype.hasOwnProperty.call(legacy, key)) {\n          return legacy[key];\n        }\n        if (/^[A-Z]$/u.test(key) && key !== "J") {\n          const pos = "ABCDEFGHIKLMNOPQRSTUVWXYZ".indexOf(key);\n          if (pos >= 0) {\n            return pos < 12 ? (pos + 1) * 3600 : -(pos - 11) * 3600;\n          }\n        }\n        return null;\n      }\n      var TimeZone = class _TimeZone {\n        constructor(name2 = "UTC") {\n          defineType(this, "TimeZone");\n          this._name = zoneName(name2);\n        }\n        static utc() {\n          return new _TimeZone("UTC");\n        }\n        static local() {\n          return new _TimeZone("local");\n        }\n        static named(name2) {\n          return new _TimeZone(name2);\n        }\n        static offset(seconds) {\n          return new _TimeZone(formatOffset(Number(seconds), true));\n        }\n        name() {\n          return zoneName(this._name);\n        }\n        to_String() {\n          return this.name();\n        }\n      };\n      var Duration = class _Duration {\n        constructor(seconds = 0, options = {}) {\n          defineType(this, "Duration");\n          this._years = Number(options.years || 0);\n          this._months = Number(options.months || 0);\n          this._weeks = Number(options.weeks || 0);\n          this._days = Number(options.days || 0);\n          this._hours = Number(options.hours || 0);\n          this._minutes = Number(options.minutes || 0);\n          this._seconds = Number(options.seconds == null ? seconds : options.seconds);\n        }\n        static seconds(n) {\n          return new _Duration(n);\n        }\n        static minutes(n) {\n          return new _Duration(0, { minutes: n });\n        }\n        static hours(n) {\n          return new _Duration(0, { hours: n });\n        }\n        static days(n) {\n          return new _Duration(0, { days: n });\n        }\n        static weeks(n) {\n          return new _Duration(0, { weeks: n });\n        }\n        static months(n) {\n          return new _Duration(0, { months: n });\n        }\n        static years(n) {\n          return new _Duration(0, { years: n });\n        }\n        years() {\n          return this._years;\n        }\n        months() {\n          return this._months;\n        }\n        weeks() {\n          return this._weeks;\n        }\n        days() {\n          return this._days;\n        }\n        hours() {\n          return this._hours;\n        }\n        minutes() {\n          return this._minutes;\n        }\n        seconds() {\n          return this._seconds;\n        }\n      };\n      var TimeFormat = class _TimeFormat {\n        constructor(pattern = "", options = {}) {\n          defineType(this, "TimeFormat");\n          this._kind = options.kind || "strftime";\n          this._pattern = pattern == null ? "" : String(pattern);\n          this._timezone = options.timezone == null ? null : zoneName(options.timezone);\n        }\n        static iso8601() {\n          return new _TimeFormat("", { kind: "iso8601" });\n        }\n        static rfc3339() {\n          return new _TimeFormat("", { kind: "rfc3339" });\n        }\n        static rfc5322() {\n          return new _TimeFormat("", { kind: "rfc5322" });\n        }\n        static strftime(pattern, options = {}) {\n          return new _TimeFormat(pattern, { kind: "strftime", timezone: options.timezone });\n        }\n        format(time) {\n          return time.format(this);\n        }\n        parse(text, options = {}) {\n          const parsed = parseTimeText(String(text), this._timezone || options.timezone, true);\n          return new Time2(parsed.epoch, { timezone: this._timezone || options.timezone || parsed.zone });\n        }\n      };\n      function parseTimeText(text, defaultZone, requireZone) {\n        let m = text.match(/^(\\d{4})-(\\d\\d)-(\\d\\d)(?:[Tt ](\\d\\d):(\\d\\d)(?::(\\d\\d)(?:\\.\\d+)?)?)?(?:\\s*(Z|[+-]\\d\\d:?\\d\\d))?$/u);\n        if (m) {\n          if (requireZone && !m[7] && defaultZone == null) {\n            throw new Error("Time.parse() requires a timezone");\n          }\n          const offset = m[7] ? parseOffset(m[7]) : null;\n          if (m[7] && offset == null) {\n            throw new Error("invalid time zone");\n          }\n          const zone = m[7] ? formatOffset(offset, true) : zoneName(defaultZone);\n          const year = Number(m[1]);\n          const month = Number(m[2]);\n          const day = Number(m[3]);\n          const hour = Number(m[4] || 0);\n          const minute = Number(m[5] || 0);\n          const second = Number(m[6] || 0);\n          if (hour > 23 || minute > 59 || second > 59) {\n            throw new Error("invalid time");\n          }\n          if (day < 1 || day > daysInMonth(year, month)) {\n            throw new Error("invalid date");\n          }\n          return {\n            epoch: sameWallEpoch({\n              year,\n              month,\n              day,\n              hour,\n              minute,\n              second\n            }, zone),\n            zone\n          };\n        }\n        m = text.match(/^(?:([A-Za-z.]+),\\s*)?(\\d{1,2})\\s+([A-Za-z.]+)\\s+(\\d{2}|\\d{4})\\s+(\\d{1,2}):(\\d\\d)(?::(\\d\\d))?\\s+([+-]\\d\\d:?\\d\\d|[A-Za-z]{1,5})$/iu);\n        if (m) {\n          if (m[1] && !WEEKDAY_BY_NAME.has(stripTrailingPeriod(m[1]))) {\n            throw new Error("invalid weekday");\n          }\n          const month = MONTH_BY_NAME.get(stripTrailingPeriod(m[3]));\n          if (!month) throw new Error("invalid month");\n          let year = Number(m[4]);\n          if (String(m[4]).length === 2) {\n            year += year >= 50 ? 1900 : 2e3;\n          }\n          if (year < 1) {\n            throw new Error("invalid year");\n          }\n          const day = Number(m[2]);\n          const hour = Number(m[5]);\n          const minute = Number(m[6]);\n          const second = Number(m[7] || 0);\n          if (hour > 23 || minute > 59 || second > 59) {\n            throw new Error("invalid time");\n          }\n          if (day < 1 || day > daysInMonth(year, month)) {\n            throw new Error("invalid date");\n          }\n          const offset = parseRfc5322Zone(m[8]);\n          if (offset == null) {\n            throw new Error("invalid time zone");\n          }\n          const zone = formatOffset(offset, true);\n          return {\n            epoch: sameWallEpoch({\n              year,\n              month,\n              day,\n              hour,\n              minute,\n              second\n            }, zone),\n            zone\n          };\n        }\n        throw new Error("Error parsing time");\n      }\n      var Time2 = class _Time {\n        constructor(epoch = null, options = {}) {\n          defineType(this, "Time");\n          this._epoch = epoch == null ? Math.floor(Date.now() / 1e3) : Number(epoch);\n          this._timezone = zoneName(options.timezone || "UTC");\n        }\n        static parse(text, options = {}) {\n          const parsed = parseTimeText(String(text), options.timezone, true);\n          return new _Time(parsed.epoch, { timezone: options.timezone || parsed.zone });\n        }\n        _clone(nextEpoch, zone = this._timezone) {\n          return new _Time(nextEpoch, { timezone: zone });\n        }\n        _parts() {\n          return partsForEpoch(this._epoch, this._timezone);\n        }\n        epoch() {\n          return this._epoch;\n        }\n        timezone() {\n          return new TimeZone(this._timezone);\n        }\n        with_timezone(zone) {\n          return this._clone(this._epoch, zoneName(zone));\n        }\n        reinterpret_timezone(zone) {\n          return this._clone(sameWallEpoch(this._parts(), zone), zoneName(zone));\n        }\n        as_utc() {\n          return this.with_timezone("UTC");\n        }\n        as_local() {\n          return this.with_timezone("local");\n        }\n        sec() {\n          return this._parts().second;\n        }\n        min() {\n          return this._parts().minute;\n        }\n        hour() {\n          return this._parts().hour;\n        }\n        day_of_month() {\n          return this._parts().day;\n        }\n        mon() {\n          return this._parts().month;\n        }\n        month() {\n          return this.mon();\n        }\n        year() {\n          return this._parts().year;\n        }\n        yy() {\n          return pad(this._parts().year % 100, 2);\n        }\n        day_of_week() {\n          return weekdayIndex(this._parts());\n        }\n        day() {\n          return DAY_ABBR[this.day_of_week() - 1];\n        }\n        day_of_year() {\n          return dayOfYear(this._parts());\n        }\n        month_last_day() {\n          return daysInMonth(this._parts().year, this._parts().month);\n        }\n        hms(separator = ":") {\n          const p = this._parts();\n          return `${pad(p.hour)}${String(separator)}${pad(p.minute)}${String(separator)}${pad(p.second)}`;\n        }\n        ymd(separator = "-") {\n          const p = this._parts();\n          const sep = String(separator);\n          return `${pad(p.year, 4)}${sep}${pad(p.month)}${sep}${pad(p.day)}`;\n        }\n        mdy(separator = "-") {\n          const p = this._parts();\n          const sep = String(separator);\n          return `${pad(p.month)}${sep}${pad(p.day)}${sep}${pad(p.year, 4)}`;\n        }\n        dmy(separator = "-") {\n          const p = this._parts();\n          const sep = String(separator);\n          return `${pad(p.day)}${sep}${pad(p.month)}${sep}${pad(p.year, 4)}`;\n        }\n        cdate() {\n          const p = this._parts();\n          return `${DAY_ABBR[weekdayIndex(p) - 1]} ${MONTHS[p.month - 1]} ${dayOfMonthForDisplay(p.day)} ${pad(p.hour)}:${pad(p.minute)}:${pad(p.second)} ${p.year}`;\n        }\n        tzoffset() {\n          return offsetForEpoch(this._epoch, this._timezone);\n        }\n        is_leap_year() {\n          return isLeapYear(this._parts().year);\n        }\n        week() {\n          return weekParts(this._parts()).week;\n        }\n        week_year() {\n          return weekParts(this._parts()).year;\n        }\n        julian_day() {\n          return julianDay(this._parts());\n        }\n        add_seconds(n) {\n          return this._clone(this._epoch + Number(n));\n        }\n        add_minutes(n) {\n          return this.add_seconds(Number(n) * 60);\n        }\n        add_hours(n) {\n          return this.add_seconds(Number(n) * 3600);\n        }\n        _calendarAdd(delta) {\n          let parts = this._parts();\n          if (delta.years) parts = addMonthsToWall(parts, Number(delta.years) * 12);\n          if (delta.months) parts = addMonthsToWall(parts, delta.months);\n          const dayDelta = Number(delta.days || 0) + Number(delta.weeks || 0) * 7;\n          if (dayDelta) {\n            const d = new Date(Date.UTC(\n              parts.year,\n              parts.month - 1,\n              parts.day + dayDelta,\n              parts.hour,\n              parts.minute,\n              parts.second\n            ));\n            parts = {\n              year: d.getUTCFullYear(),\n              month: d.getUTCMonth() + 1,\n              day: d.getUTCDate(),\n              hour: d.getUTCHours(),\n              minute: d.getUTCMinutes(),\n              second: d.getUTCSeconds()\n            };\n          }\n          return this._clone(sameWallEpoch(parts, this._timezone));\n        }\n        add_days(n) {\n          return this._calendarAdd({ days: n });\n        }\n        add_weeks(n) {\n          return this._calendarAdd({ weeks: n });\n        }\n        add_months(n) {\n          return this._calendarAdd({ months: n });\n        }\n        add_years(n) {\n          return this._calendarAdd({ years: n });\n        }\n        subtract_seconds(n) {\n          return this.add_seconds(-Number(n));\n        }\n        subtract_minutes(n) {\n          return this.add_minutes(-Number(n));\n        }\n        subtract_hours(n) {\n          return this.add_hours(-Number(n));\n        }\n        subtract_days(n) {\n          return this.add_days(-Number(n));\n        }\n        subtract_weeks(n) {\n          return this.add_weeks(-Number(n));\n        }\n        subtract_months(n) {\n          return this.add_months(-Number(n));\n        }\n        subtract_years(n) {\n          return this.add_years(-Number(n));\n        }\n        add(duration) {\n          return this.add_seconds(\n            Number(duration.seconds()) + Number(duration.minutes()) * 60 + Number(duration.hours()) * 3600\n          )._calendarAdd({\n            days: duration.days(),\n            weeks: duration.weeks(),\n            months: duration.months(),\n            years: duration.years()\n          });\n        }\n        subtract(duration) {\n          return this.add(new Duration(-duration.seconds(), {\n            minutes: -duration.minutes(),\n            hours: -duration.hours(),\n            days: -duration.days(),\n            weeks: -duration.weeks(),\n            months: -duration.months(),\n            years: -duration.years()\n          }));\n        }\n        elapsed_seconds_until(other) {\n          return other.epoch() - this._epoch;\n        }\n        compare(other) {\n          return this._epoch < other.epoch() ? -1 : this._epoch > other.epoch() ? 1 : 0;\n        }\n        is_before(other) {\n          return this._epoch < other.epoch();\n        }\n        is_after(other) {\n          return this._epoch > other.epoch();\n        }\n        datetime() {\n          return this.strftime("%Y-%m-%dT%H:%M:%S");\n        }\n        to_String() {\n          return this.datetime();\n        }\n        to_iso8601() {\n          return this.to_rfc3339();\n        }\n        to_rfc3339() {\n          const p = this._parts();\n          return `${pad(p.year, 4)}-${pad(p.month)}-${pad(p.day)}T${pad(p.hour)}:${pad(p.minute)}:${pad(p.second)}${formatOffset(offsetForEpoch(this._epoch, this._timezone), true)}`;\n        }\n        to_rfc5322(options = {}) {\n          const p = this._parts();\n          const weekday = DAY_ABBR[weekdayIndex(p) - 1];\n          const core = `${pad(p.day)} ${MONTHS[p.month - 1]} ${pad(p.year, 4)} ${pad(p.hour)}:${pad(p.minute)}:${pad(p.second)} ${formatOffset(offsetForEpoch(this._epoch, this._timezone), false)}`;\n          return options.include_weekday === false ? core : `${weekday}, ${core}`;\n        }\n        format(timeFormat) {\n          const time = timeFormat._timezone == null ? this : this.with_timezone(timeFormat._timezone);\n          if (timeFormat._kind === "iso8601" || timeFormat._kind === "rfc3339") return time.to_rfc3339();\n          if (timeFormat._kind === "rfc5322") return time.to_rfc5322();\n          return time.strftime(timeFormat._pattern);\n        }\n        strftime(fmt) {\n          const p = this._parts();\n          const offset = offsetForEpoch(this._epoch, this._timezone);\n          const parts = {\n            Y: pad(p.year, 4),\n            m: pad(p.month),\n            d: pad(p.day),\n            H: pad(p.hour),\n            M: pad(p.minute),\n            S: pad(p.second),\n            z: formatOffset(offset, false),\n            Z: this._timezone,\n            "%": "%"\n          };\n          return String(fmt).replace(/%([%YmdHMSzZ])/g, (_match, key) => parts[key]);\n        }\n      };\n      var TimeParser = class {\n        constructor(_fmt = "%Y-%m-%d") {\n          this._format = String(_fmt);\n        }\n        parse(text) {\n          const m = String(text).match(/(?:[A-Za-z]+\\.?\\s+)?([0-9]{1,2})(?:st|nd|rd|th)\\s+([A-Za-z]{3}),\\s+([0-9]{4})/u);\n          if (!m) {\n            try {\n              return new Time2(parseTimeText(String(text), "UTC", false).epoch, { timezone: "UTC" });\n            } catch (_err) {\n              throw new Error("Exception: unable to parse time string");\n            }\n          }\n          const day = Number(m[1]);\n          const mon = MONTH_BY_NAME.get(m[2].toLowerCase());\n          const year = Number(m[3]);\n          if (!mon) {\n            throw new Error("Exception: unable to parse month");\n          }\n          return new Time2(sameWallEpoch({\n            year,\n            month: mon,\n            day,\n            hour: 0,\n            minute: 0,\n            second: 0\n          }, "UTC"), { timezone: "UTC" });\n        }\n      };\n      module2.exports = {\n        Time: Time2,\n        TimeZone,\n        Duration,\n        TimeFormat,\n        TimeParser\n      };\n    }\n  });\n\n  // modules/std/marshal/cbor.js\n  var require_cbor = __commonJS({\n    "modules/std/marshal/cbor.js"(exports2, module2) {\n      "use strict";\n      var { BinaryString: BinaryString2, ZuzuBinary } = require_runtime_helpers();\n      var MAX_SAFE_INTEGER = 9007199254740991;\n      var SELF_DESCRIBED_TAG = 55799;\n      var PUSH_BYTES_CHUNK = 16384;\n      var CborTextString = class {\n        constructor(value) {\n          this.value = String(value ?? "");\n        }\n      };\n      var CborByteString = class {\n        constructor(value) {\n          this.value = toUint8Array(value);\n        }\n      };\n      var CborTagged = class {\n        constructor(tagNumberValue, value) {\n          this.tagNumber = Number(tagNumberValue);\n          this.value = value;\n        }\n      };\n      function textString(value) {\n        return new CborTextString(value);\n      }\n      function byteString(value) {\n        return new CborByteString(value);\n      }\n      function tag(tagNumberValue, value) {\n        return new CborTagged(tagNumberValue, value);\n      }\n      function isTextString(value) {\n        return value instanceof CborTextString;\n      }\n      function isByteString(value) {\n        return value instanceof CborByteString;\n      }\n      function isTagged(value) {\n        return value instanceof CborTagged;\n      }\n      function textValue(value) {\n        if (!isTextString(value)) {\n          throw new Error("Not a CBOR text string");\n        }\n        return value.value;\n      }\n      function bytesValue(value) {\n        if (!isByteString(value)) {\n          throw new Error("Not a CBOR byte string");\n        }\n        return new Uint8Array(value.value);\n      }\n      function tagNumber(value) {\n        if (!isTagged(value)) {\n          throw new Error("Not a CBOR tag");\n        }\n        return value.tagNumber;\n      }\n      function tagValue(value) {\n        if (!isTagged(value)) {\n          throw new Error("Not a CBOR tag");\n        }\n        return value.value;\n      }\n      function encodeOne(item) {\n        const out = [];\n        encodeItem(item, out);\n        return new BinaryString2(Uint8Array.from(out));\n      }\n      function decodeOne(input) {\n        const bytes = toUint8Array(input);\n        const decoded = decodeItem(bytes, 0, true);\n        if (decoded.offset !== bytes.length) {\n          throw cborError("trailing bytes after item");\n        }\n        return decoded.value;\n      }\n      function validateProfile(input) {\n        const bytes = toUint8Array(input);\n        const offset = scanItem(bytes, 0, true);\n        if (offset !== bytes.length) {\n          throw cborError("trailing bytes after item");\n        }\n        return true;\n      }\n      function encodeItem(item, out) {\n        if (item == null) {\n          out.push(246);\n          return;\n        }\n        if (item === false) {\n          out.push(244);\n          return;\n        }\n        if (item === true) {\n          out.push(245);\n          return;\n        }\n        if (typeof item === "number") {\n          encodeNumber(item, out);\n          return;\n        }\n        if (typeof item === "string" || item instanceof CborTextString) {\n          const text = item instanceof CborTextString ? item.value : item;\n          const bytes = new TextEncoder().encode(text);\n          encodeUnsigned(3, bytes.length, out);\n          pushBytes(out, bytes);\n          return;\n        }\n        if (item instanceof CborByteString) {\n          encodeUnsigned(2, item.value.length, out);\n          pushBytes(out, item.value);\n          return;\n        }\n        if (item instanceof CborTagged) {\n          if (item.tagNumber !== SELF_DESCRIBED_TAG) {\n            throw cborError(`unsupported tag ${item.tagNumber}`);\n          }\n          encodeUnsigned(6, item.tagNumber, out);\n          encodeItem(item.value, out);\n          return;\n        }\n        if (item instanceof Uint8Array || item instanceof ZuzuBinary) {\n          const bytes = toUint8Array(item);\n          encodeUnsigned(2, bytes.length, out);\n          pushBytes(out, bytes);\n          return;\n        }\n        if (Array.isArray(item)) {\n          encodeUnsigned(4, item.length, out);\n          for (const value of item) {\n            encodeItem(value, out);\n          }\n          return;\n        }\n        if (item instanceof Map) {\n          encodeUnsigned(5, item.size, out);\n          for (const [key, value] of item.entries()) {\n            encodeItem(key, out);\n            encodeItem(value, out);\n          }\n          return;\n        }\n        if (typeof item === "object") {\n          const entries = Object.entries(item);\n          encodeUnsigned(5, entries.length, out);\n          for (const [key, value] of entries) {\n            encodeItem(new CborTextString(key), out);\n            encodeItem(value, out);\n          }\n          return;\n        }\n        throw cborError(`unsupported value type ${typeof item}`);\n      }\n      function encodeNumber(value, out) {\n        if (!Number.isFinite(value)) {\n          throw cborError(Number.isNaN(value) ? "NaN is invalid" : "infinite float is invalid");\n        }\n        if (!Object.is(value, -0) && Number.isInteger(value) && Math.abs(value) <= MAX_SAFE_INTEGER) {\n          if (value >= 0) {\n            encodeUnsigned(0, value, out);\n          } else {\n            encodeUnsigned(1, -1 - value, out);\n          }\n          return;\n        }\n        out.push(251);\n        const buffer = new ArrayBuffer(8);\n        new DataView(buffer).setFloat64(0, value, false);\n        pushBytes(out, new Uint8Array(buffer));\n      }\n      function encodeUnsigned(major, value, out) {\n        if (!Number.isSafeInteger(value) || value < 0) {\n          throw cborError("integer is outside supported range");\n        }\n        const prefix = major << 5;\n        if (value <= 23) {\n          out.push(prefix | value);\n        } else if (value <= 255) {\n          out.push(prefix | 24, value);\n        } else if (value <= 65535) {\n          out.push(prefix | 25, value >> 8, value & 255);\n        } else if (value <= 4294967295) {\n          out.push(\n            prefix | 26,\n            value >>> 24 & 255,\n            value >>> 16 & 255,\n            value >>> 8 & 255,\n            value & 255\n          );\n        } else {\n          out.push(prefix | 27);\n          const high = Math.floor(value / 4294967296);\n          const low = value >>> 0;\n          out.push(\n            high >>> 24 & 255,\n            high >>> 16 & 255,\n            high >>> 8 & 255,\n            high & 255,\n            low >>> 24 & 255,\n            low >>> 16 & 255,\n            low >>> 8 & 255,\n            low & 255\n          );\n        }\n      }\n      function decodeItem(bytes, offset, topLevel) {\n        requireAvailable(bytes, offset, 1, "initial byte");\n        const initial = bytes[offset];\n        const major = initial >> 5;\n        const ai = initial & 31;\n        offset++;\n        if (ai === 31) {\n          throw cborError("indefinite-length item");\n        }\n        if (ai >= 28 && ai <= 30) {\n          throw cborError("reserved additional information");\n        }\n        if (major === 7) {\n          return decodeSimpleOrFloat(bytes, offset, ai);\n        }\n        const argument = readArgument(bytes, offset, ai);\n        const value = argument.value;\n        offset = argument.offset;\n        switch (major) {\n          case 0:\n            assertUnsignedNumberRange(value);\n            return { value, offset };\n          case 1:\n            assertNegativeNumberRange(value);\n            return { value: -1 - value, offset };\n          case 2:\n            requireAvailable(bytes, offset, value, "byte string payload");\n            return {\n              value: new CborByteString(bytes.subarray(offset, offset + value)),\n              offset: offset + value\n            };\n          case 3: {\n            requireAvailable(bytes, offset, value, "text string payload");\n            const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(offset, offset + value));\n            return { value: new CborTextString(text), offset: offset + value };\n          }\n          case 4: {\n            const values = [];\n            for (let i = 0; i < value; i++) {\n              const item = decodeItem(bytes, offset, false);\n              values.push(item.value);\n              offset = item.offset;\n            }\n            return { value: values, offset };\n          }\n          case 5: {\n            const map = /* @__PURE__ */ new Map();\n            for (let i = 0; i < value; i++) {\n              const key = decodeItem(bytes, offset, false);\n              const mapValue = decodeItem(bytes, key.offset, false);\n              map.set(key.value, mapValue.value);\n              offset = mapValue.offset;\n            }\n            return { value: map, offset };\n          }\n          case 6: {\n            if (!topLevel || value !== SELF_DESCRIBED_TAG) {\n              throw cborError(`unsupported tag ${value}`);\n            }\n            const inner = decodeItem(bytes, offset, false);\n            return {\n              value: new CborTagged(value, inner.value),\n              offset: inner.offset\n            };\n          }\n          default:\n            throw cborError("unsupported major type");\n        }\n      }\n      function scanItem(bytes, offset, topLevel) {\n        return decodeItem(bytes, offset, topLevel).offset;\n      }\n      function decodeSimpleOrFloat(bytes, offset, ai) {\n        if (ai === 20) {\n          return { value: false, offset };\n        }\n        if (ai === 21) {\n          return { value: true, offset };\n        }\n        if (ai === 22) {\n          return { value: null, offset };\n        }\n        if (ai === 25) {\n          throw cborError("half-precision float is invalid");\n        }\n        if (ai === 26) {\n          throw cborError("single-precision float is invalid");\n        }\n        if (ai === 27) {\n          requireAvailable(bytes, offset, 8, "binary64 float");\n          const value = new DataView(\n            bytes.buffer,\n            bytes.byteOffset + offset,\n            8\n          ).getFloat64(0, false);\n          if (Number.isNaN(value)) {\n            throw cborError("NaN is invalid");\n          }\n          if (!Number.isFinite(value)) {\n            throw cborError("infinite float is invalid");\n          }\n          return { value, offset: offset + 8 };\n        }\n        throw cborError("unsupported simple value");\n      }\n      function readArgument(bytes, offset, ai) {\n        if (ai <= 23) {\n          return { value: ai, offset };\n        }\n        if (ai === 24) {\n          requireAvailable(bytes, offset, 1, "uint8 argument");\n          const value = bytes[offset];\n          assertShortestArgument(value, 24);\n          return { value, offset: offset + 1 };\n        }\n        if (ai === 25) {\n          requireAvailable(bytes, offset, 2, "uint16 argument");\n          const value = bytes[offset] << 8 | bytes[offset + 1];\n          assertShortestArgument(value, 256);\n          return { value, offset: offset + 2 };\n        }\n        if (ai === 26) {\n          requireAvailable(bytes, offset, 4, "uint32 argument");\n          const value = bytes[offset] * 16777216 + (bytes[offset + 1] << 16) + (bytes[offset + 2] << 8) + bytes[offset + 3];\n          assertShortestArgument(value, 65536);\n          return { value, offset: offset + 4 };\n        }\n        if (ai === 27) {\n          requireAvailable(bytes, offset, 8, "uint64 argument");\n          const high = bytes[offset] * 16777216 + (bytes[offset + 1] << 16) + (bytes[offset + 2] << 8) + bytes[offset + 3];\n          const low = bytes[offset + 4] * 16777216 + (bytes[offset + 5] << 16) + (bytes[offset + 6] << 8) + bytes[offset + 7];\n          const value = high * 4294967296 + low;\n          assertShortestArgument(value, 4294967296);\n          return { value, offset: offset + 8 };\n        }\n        throw cborError("unsupported additional information");\n      }\n      function assertShortestArgument(value, minimum) {\n        if (value < minimum) {\n          throw cborError("non-shortest integer encoding");\n        }\n      }\n      function assertUnsignedNumberRange(value) {\n        if (value > MAX_SAFE_INTEGER) {\n          throw cborError("integer is outside Zuzu Number range");\n        }\n      }\n      function assertNegativeNumberRange(value) {\n        if (value >= MAX_SAFE_INTEGER) {\n          throw cborError("integer is outside Zuzu Number range");\n        }\n      }\n      function requireAvailable(bytes, offset, length, context) {\n        if (offset + length > bytes.length) {\n          throw cborError(`incomplete ${context}`);\n        }\n      }\n      function pushBytes(out, bytes) {\n        for (let offset = 0; offset < bytes.length; offset += PUSH_BYTES_CHUNK) {\n          out.push(...bytes.subarray(offset, offset + PUSH_BYTES_CHUNK));\n        }\n      }\n      function toUint8Array(value) {\n        if (value instanceof ZuzuBinary) {\n          return new Uint8Array(value.bytes);\n        }\n        if (value instanceof Uint8Array) {\n          return new Uint8Array(value);\n        }\n        if (Array.isArray(value)) {\n          return Uint8Array.from(value.map((item) => Number(item) & 255));\n        }\n        if (value && value.buffer instanceof ArrayBuffer) {\n          return new Uint8Array(value.buffer, value.byteOffset || 0, value.byteLength);\n        }\n        throw new Error("TypeException: CBOR adapter expects BinaryString or Uint8Array bytes");\n      }\n      function cborError(message) {\n        return new Error(`CBOR profile error: ${message}`);\n      }\n      module2.exports = {\n        CborTextString,\n        CborByteString,\n        CborTagged,\n        SELF_DESCRIBED_TAG,\n        byteString,\n        bytesValue,\n        decodeOne,\n        encodeOne,\n        isByteString,\n        isTagged,\n        isTextString,\n        tag,\n        tagNumber,\n        tagValue,\n        textString,\n        textValue,\n        validateProfile\n      };\n    }\n  });\n\n  // lib/gui/dom-renderer.js\n  var require_dom_renderer = __commonJS({\n    "lib/gui/dom-renderer.js"(exports2, module2) {\n      "use strict";\n      function installSafeDefineProperties() {\n        if (Object.__zuzu_safe_define_properties) {\n          return;\n        }\n        const nativeDefineProperty = Object.defineProperty;\n        const nativeDefineProperties = Object.defineProperties;\n        function safeDescriptor(descriptor) {\n          if (!descriptor || typeof descriptor !== "object") {\n            return descriptor;\n          }\n          const safe = /* @__PURE__ */ Object.create(null);\n          for (const key of [\n            "value",\n            "get",\n            "set",\n            "writable",\n            "enumerable",\n            "configurable"\n          ]) {\n            if (Object.prototype.hasOwnProperty.call(descriptor, key)) {\n              safe[key] = descriptor[key];\n            }\n          }\n          return safe;\n        }\n        Object.defineProperty = function zuzuSafeDefineProperty(obj, prop, descriptor) {\n          return nativeDefineProperty(obj, prop, safeDescriptor(descriptor));\n        };\n        Object.defineProperties = function zuzuSafeDefineProperties(obj, descriptors) {\n          const safe = /* @__PURE__ */ Object.create(null);\n          for (const key of Object.keys(descriptors || {})) {\n            safe[key] = safeDescriptor(descriptors[key]);\n          }\n          return nativeDefineProperties(obj, safe);\n        };\n        nativeDefineProperty(Object, "__zuzu_safe_define_properties", {\n          value: true,\n          enumerable: false,\n          configurable: false\n        });\n      }\n      var activeState = null;\n      function rendererState() {\n        if (!activeState) {\n          throw new Error("Zuzu GUI DOM renderer is not active");\n        }\n        return activeState;\n      }\n      function rendererDocument() {\n        const state = rendererState();\n        return state.document || document;\n      }\n      function itemLabel(item) {\n        if (item == null) {\n          return "";\n        }\n        if (typeof item === "string" || typeof item === "number") {\n          return String(item);\n        }\n        return String(item.label ?? item.value ?? "");\n      }\n      function itemValue(item) {\n        if (item == null) {\n          return "";\n        }\n        if (typeof item === "string" || typeof item === "number") {\n          return String(item);\n        }\n        return item.value ?? itemLabel(item);\n      }\n      function itemChildren(item) {\n        return Array.isArray(item && item.children) ? item.children : [];\n      }\n      function pathKey(path) {\n        return Array.isArray(path) ? path.map(Number).join(",") : "";\n      }\n      function sendWidgetEvent(type, node, extra = {}) {\n        const state = node.__zuzuRendererState || rendererState();\n        if (state.sendEvent) {\n          state.sendEvent({\n            windowId: state.windowId,\n            type,\n            widgetGuid: node.dataset.guid || null,\n            ...extra\n          });\n          return;\n        }\n        if (!window.zuzuGui) {\n          return;\n        }\n        window.zuzuGui.sendEvent({\n          windowId: state.windowId,\n          type,\n          widgetGuid: node.dataset.guid || null,\n          ...extra\n        });\n      }\n      function sendThrottledWidgetEvent(type, node, extraFactory) {\n        if (node.__zuzuPendingEvent) {\n          node.__zuzuPendingEvent.extraFactory = extraFactory;\n          return;\n        }\n        node.__zuzuPendingEvent = { extraFactory };\n        setTimeout(() => {\n          const pending = node.__zuzuPendingEvent;\n          node.__zuzuPendingEvent = null;\n          sendWidgetEvent(type, node, pending.extraFactory());\n        }, 50);\n      }\n      function applyCommonProps(element, snapshot) {\n        const props = snapshot.props || {};\n        element.dataset.guid = snapshot.guid || "";\n        element.hidden = props.visible === false;\n        element.className = "";\n        if (snapshot.classes && snapshot.classes.length > 0) {\n          element.classList.add(...snapshot.classes);\n        }\n        if (snapshot.id) {\n          element.id = snapshot.id;\n        } else {\n          element.removeAttribute("id");\n        }\n        if (props.disabled) {\n          element.setAttribute("aria-disabled", "true");\n          if ("disabled" in element) {\n            element.disabled = true;\n          }\n        } else {\n          element.removeAttribute("aria-disabled");\n          if ("disabled" in element) {\n            element.disabled = false;\n          }\n        }\n        for (const [key, cssName] of [\n          ["width", "width"],\n          ["height", "height"],\n          ["minwidth", "minWidth"],\n          ["minheight", "minHeight"],\n          ["maxwidth", "maxWidth"],\n          ["maxheight", "maxHeight"]\n        ]) {\n          if (props[key] != null && props[key] !== "") {\n            element.style[cssName] = `${Number(props[key]) || 0}px`;\n          } else {\n            element.style[cssName] = "";\n          }\n        }\n      }\n      function applyBoxStyle(element, snapshot) {\n        const props = snapshot.props || {};\n        element.classList.add(snapshot.type === "HBox" ? "zuzu-hbox" : "zuzu-vbox");\n        element.style.display = "flex";\n        element.style.flexDirection = snapshot.type === "HBox" ? "row" : "column";\n        if (props.gap != null) {\n          element.style.gap = `${Number(props.gap) || 0}px`;\n        }\n        if (props.padding != null) {\n          element.style.padding = `${Number(props.padding) || 0}px`;\n        }\n      }\n      function applySpecificProps(element, snapshot) {\n        const type = snapshot.type || "Widget";\n        const props = snapshot.props || {};\n        if (type === "Window") {\n          return;\n        }\n        if (type === "Frame") {\n          let legend = element.querySelector(":scope > legend");\n          if (!legend) {\n            legend = rendererDocument().createElement("legend");\n            element.prepend(legend);\n          }\n          legend.textContent = props.label || "";\n          element.classList.toggle("zuzu-collapsed", props.collapsed === true);\n          return;\n        }\n        if (type === "VBox" || type === "HBox") {\n          applyBoxStyle(element, snapshot);\n          return;\n        }\n        if (type === "Label") {\n          element.textContent = props.text || "";\n          if (props.for_id) {\n            element.htmlFor = props.for_id;\n          }\n          return;\n        }\n        if (type === "Text") {\n          element.textContent = props.text || props.value || "";\n          element.style.whiteSpace = props.wrap === false ? "pre" : "pre-wrap";\n          return;\n        }\n        if (type === "RichText") {\n          element.innerHTML = props.value || "";\n          return;\n        }\n        if (type === "Image") {\n          element.src = props.src || "";\n          element.alt = props.alt || "";\n          element.style.objectFit = props.fit === "stretch" ? "fill" : props.fit || "contain";\n          return;\n        }\n        if (type === "Input") {\n          setInputValue(element, props.value || "");\n          element.placeholder = props.placeholder || "";\n          element.readOnly = props.readonly === true;\n          element.required = props.required === true;\n          if ("type" in element) {\n            element.type = props.password ? "password" : "text";\n          }\n          return;\n        }\n        if (type === "DatePicker") {\n          setInputValue(element, props.value || "");\n          element.placeholder = "YYYY-MM-DD";\n          element.pattern = "\\\\d{4}-\\\\d{2}-\\\\d{2}";\n          element.dataset.min = props.min || "";\n          element.dataset.max = props.max || "";\n          return;\n        }\n        if (type === "Checkbox" || type === "Radio") {\n          const input = element.querySelector("input");\n          const label = element.querySelector("span");\n          input.checked = props.checked === true;\n          input.indeterminate = props.indeterminate === true;\n          input.value = props.value || "";\n          input.name = props.name || props.group || "";\n          label.textContent = props.label || "";\n          return;\n        }\n        if (type === "RadioGroup") {\n          const radios = element.querySelectorAll(\':scope input[type="radio"]\');\n          for (const radio of radios) {\n            radio.name = snapshot.guid || "";\n          }\n          return;\n        }\n        if (type === "Select") {\n          renderSelectOptions(element, props);\n          element.value = props.value == null ? "" : String(props.value);\n          element.multiple = props.multiple === true;\n          return;\n        }\n        if (type === "Separator") {\n          element.classList.toggle("zuzu-vertical-separator", props.orientation === "vertical");\n          return;\n        }\n        if (type === "Slider") {\n          setInputValue(element, props.value ?? 0);\n          element.min = props.min ?? 0;\n          element.max = props.max ?? 100;\n          element.step = props.step ?? 1;\n          element.disabled = props.disabled === true || props.readonly === true;\n          return;\n        }\n        if (type === "Progress") {\n          element.value = Number(props.value ?? 0);\n          element.max = Number(props.max ?? 100);\n          element.classList.toggle("zuzu-indeterminate", props.indeterminate === true);\n          element.title = props.show_text ? `${element.value} / ${element.max}` : "";\n          return;\n        }\n        if (type === "Tabs") {\n          element.dataset.selected = props.selected || "";\n          for (const child of Array.from(element.children)) {\n            if (child.__zuzuGuiType === "Tab") {\n              child.open = child.dataset.value === element.dataset.selected;\n            }\n          }\n          return;\n        }\n        if (type === "Tab") {\n          element.open = props.selected === true;\n          element.dataset.value = props.value || "";\n          element.querySelector("summary").textContent = props.title || props.value || "";\n          return;\n        }\n        if (type === "ListView") {\n          renderListView(element, props);\n          return;\n        }\n        if (type === "TreeView") {\n          renderTreeView(element, props);\n          return;\n        }\n        if (type === "Menu") {\n          let label = element.__zuzuMenuLabel;\n          if (!label) {\n            label = rendererDocument().createElement("span");\n            label.className = "zuzu-menu-label";\n            label.__zuzuRendererState = rendererState();\n            element.__zuzuMenuLabel = label;\n            element.insertBefore(label, element.children[0] || null);\n          }\n          label.textContent = props.text || "";\n          return;\n        }\n        if (type === "Button" || type === "MenuItem") {\n          element.textContent = props.text || "";\n        }\n      }\n      function setInputValue(element, value) {\n        const text = String(value ?? "");\n        if (element.value === text) {\n          return;\n        }\n        const focused = rendererDocument().activeElement === element;\n        const selectionStart = focused ? element.selectionStart : null;\n        const selectionEnd = focused ? element.selectionEnd : null;\n        element.value = text;\n        if (focused && typeof element.setSelectionRange === "function" && selectionStart != null && selectionEnd != null) {\n          const start = Math.min(selectionStart, text.length);\n          const end = Math.min(selectionEnd, text.length);\n          element.setSelectionRange(start, end);\n        }\n      }\n      function createElement(snapshot) {\n        const type = snapshot.type || "Widget";\n        let element;\n        if (type === "Window") {\n          element = rendererDocument().createElement("main");\n        } else if (type === "Frame") {\n          element = rendererDocument().createElement("fieldset");\n        } else if (type === "VBox" || type === "HBox") {\n          element = rendererDocument().createElement("div");\n        } else if (type === "Label") {\n          element = rendererDocument().createElement("label");\n        } else if (type === "Text" || type === "RichText") {\n          element = rendererDocument().createElement("div");\n          element.addEventListener("click", () => {\n            sendWidgetEvent("click", element);\n          });\n        } else if (type === "Image") {\n          element = rendererDocument().createElement("img");\n          element.addEventListener("click", () => {\n            sendWidgetEvent("click", element);\n          });\n        } else if (type === "Input") {\n          element = snapshot.props && snapshot.props.multiline ? rendererDocument().createElement("textarea") : rendererDocument().createElement("input");\n          element.addEventListener("input", () => {\n            sendWidgetEvent("input", element, { value: element.value });\n          });\n          element.addEventListener("change", () => {\n            sendWidgetEvent("change", element, { value: element.value });\n          });\n        } else if (type === "DatePicker") {\n          element = rendererDocument().createElement("input");\n          element.type = "text";\n          element.inputMode = "numeric";\n          element.autocomplete = "off";\n          element.addEventListener("input", () => {\n            sendWidgetEvent("input", element, { value: element.value });\n          });\n          element.addEventListener("change", () => {\n            sendWidgetEvent("change", element, { value: element.value });\n          });\n        } else if (type === "Checkbox" || type === "Radio") {\n          element = rendererDocument().createElement("label");\n          element.className = "zuzu-check-control";\n          const input = rendererDocument().createElement("input");\n          input.type = type === "Radio" ? "radio" : "checkbox";\n          const label = rendererDocument().createElement("span");\n          element.append(input, label);\n          input.addEventListener("change", () => {\n            const eventTarget = type === "Radio" && element.dataset.parentGuid ? element.dataset.parentGuid : element.dataset.guid;\n            sendWidgetEvent("change", element, {\n              widgetGuid: eventTarget,\n              checked: input.checked,\n              value: input.value\n            });\n          });\n        } else if (type === "Select") {\n          element = rendererDocument().createElement("select");\n          element.addEventListener("change", () => {\n            sendWidgetEvent("change", element, { value: element.value });\n          });\n        } else if (type === "Button" || type === "MenuItem") {\n          element = rendererDocument().createElement("button");\n          element.type = "button";\n          element.addEventListener("click", () => {\n            sendWidgetEvent("click", element);\n          });\n        } else if (type === "Menu") {\n          element = rendererDocument().createElement("nav");\n        } else if (type === "Separator") {\n          element = rendererDocument().createElement("hr");\n        } else if (type === "Slider") {\n          element = rendererDocument().createElement("input");\n          element.type = "range";\n          element.addEventListener("input", () => {\n            sendThrottledWidgetEvent("input", element, () => ({\n              value: Number(element.value)\n            }));\n          });\n          element.addEventListener("change", () => {\n            sendWidgetEvent("change", element, { value: Number(element.value) });\n          });\n        } else if (type === "Progress") {\n          element = rendererDocument().createElement("progress");\n        } else if (type === "Tabs") {\n          element = rendererDocument().createElement("div");\n          element.className = "zuzu-tabs";\n        } else if (type === "Tab") {\n          element = rendererDocument().createElement("details");\n          const summary = rendererDocument().createElement("summary");\n          element.appendChild(summary);\n          summary.addEventListener("click", (event) => {\n            event.preventDefault();\n            const parent = element.parentNode;\n            if (parent) {\n              for (const child of Array.from(parent.children)) {\n                if (child.__zuzuGuiType === "Tab") {\n                  child.open = child === element;\n                }\n              }\n            }\n            element.open = true;\n            sendWidgetEvent("select", element, {\n              widgetGuid: element.dataset.parentGuid || element.dataset.guid,\n              selected: element.dataset.value || "",\n              value: element.dataset.value || ""\n            });\n          });\n        } else if (type === "ListView" || type === "TreeView") {\n          element = rendererDocument().createElement("div");\n          element.tabIndex = 0;\n        } else {\n          element = rendererDocument().createElement("div");\n        }\n        element.__zuzuRendererState = rendererState();\n        element.__zuzuGuiType = type;\n        element.__zuzuGuiSubType = type === "Input" && snapshot.props && snapshot.props.multiline ? "multiline" : "";\n        return element;\n      }\n      function renderNode(snapshot) {\n        const element = createElement(snapshot);\n        applyCommonProps(element, snapshot);\n        applySpecificProps(element, snapshot);\n        rendererState().nodes.set(snapshot.guid, element);\n        for (const child of snapshot.children || []) {\n          if (snapshot.type === "Window" && child.type === "Menu" && !rendererState().renderMenus) {\n            continue;\n          }\n          const childElement = renderNode(child);\n          childElement.dataset.parentGuid = snapshot.guid || "";\n          if (snapshot.type === "RadioGroup" && child.type === "Radio") {\n            const radio = childElement.querySelector(\'input[type="radio"]\');\n            if (radio) {\n              radio.name = snapshot.guid || "";\n            }\n          }\n          element.appendChild(childElement);\n        }\n        return element;\n      }\n      function renderSelectOptions(element, props) {\n        element.replaceChildren();\n        for (const item of props.options || []) {\n          const option = rendererDocument().createElement("option");\n          option.textContent = itemLabel(item);\n          option.value = String(itemValue(item));\n          option.disabled = item && item.disabled === true;\n          element.appendChild(option);\n        }\n      }\n      function renderListView(element, props) {\n        element.classList.add("zuzu-listview");\n        element.replaceChildren();\n        const list = rendererDocument().createElement("ul");\n        const selected = props.selected_index == null ? null : Number(props.selected_index);\n        (props.items || []).forEach((item, index) => {\n          const row = rendererDocument().createElement("li");\n          row.textContent = itemLabel(item);\n          row.dataset.index = String(index);\n          row.classList.toggle("selected", index === selected);\n          row.addEventListener("click", () => {\n            markListSelected(element, index);\n            sendWidgetEvent("select", element, { selected_index: index });\n          });\n          row.addEventListener("dblclick", () => {\n            markListSelected(element, index);\n            sendWidgetEvent("activate", element, { selected_index: index });\n          });\n          list.appendChild(row);\n        });\n        element.appendChild(list);\n      }\n      function markListSelected(element, index) {\n        for (const row of element.querySelectorAll("li")) {\n          row.classList.toggle("selected", Number(row.dataset.index) === Number(index));\n        }\n      }\n      function renderTreeView(element, props) {\n        element.classList.add("zuzu-treeview");\n        element.replaceChildren();\n        const selected = pathKey(props.selected_path || []);\n        const expanded = new Set((props.expanded_paths || []).map(pathKey));\n        element.appendChild(renderTreeItems(props.items || [], [], selected, expanded, element));\n      }\n      function renderTreeItems(items, prefix, selected, expanded, owner) {\n        const list = rendererDocument().createElement("ul");\n        items.forEach((item, index) => {\n          const path = [...prefix, index];\n          const key = pathKey(path);\n          const children = itemChildren(item);\n          const row = rendererDocument().createElement("li");\n          if (children.length > 0) {\n            const details = rendererDocument().createElement("details");\n            details.open = expanded.has(key);\n            const summary = rendererDocument().createElement("summary");\n            summary.textContent = itemLabel(item);\n            summary.dataset.path = key;\n            summary.classList.toggle("selected", key === selected);\n            summary.addEventListener("click", () => {\n              markTreeSelected(owner, key);\n              sendWidgetEvent("select", owner, { selected_path: path });\n            });\n            summary.addEventListener("dblclick", () => {\n              markTreeSelected(owner, key);\n              sendWidgetEvent("activate", owner, { selected_path: path });\n            });\n            details.addEventListener("toggle", () => {\n              sendWidgetEvent(details.open ? "expand" : "collapse", owner, {\n                selected_path: path\n              });\n            });\n            details.append(summary, renderTreeItems(children, path, selected, expanded, owner));\n            row.appendChild(details);\n          } else {\n            const button = rendererDocument().createElement("button");\n            button.type = "button";\n            button.textContent = itemLabel(item);\n            button.dataset.path = key;\n            button.classList.toggle("selected", key === selected);\n            button.addEventListener("click", () => {\n              markTreeSelected(owner, key);\n              sendWidgetEvent("select", owner, { selected_path: path });\n            });\n            button.addEventListener("dblclick", () => {\n              markTreeSelected(owner, key);\n              sendWidgetEvent("activate", owner, { selected_path: path });\n            });\n            row.appendChild(button);\n          }\n          list.appendChild(row);\n        });\n        return list;\n      }\n      function markTreeSelected(element, key) {\n        for (const node of element.querySelectorAll("[data-path]")) {\n          node.classList.toggle("selected", node.dataset.path === key);\n        }\n      }\n      function replaceNode(snapshot) {\n        const old = rendererState().nodes.get(snapshot.guid);\n        if (!old) {\n          return;\n        }\n        const parent = old.parentNode;\n        const next = renderNode(snapshot);\n        forgetNode(old);\n        parent.replaceChild(next, old);\n      }\n      function forgetNode(node) {\n        const guid = node && node.dataset ? node.dataset.guid : null;\n        if (guid) {\n          rendererState().nodes.delete(guid);\n        }\n        for (const child of Array.from(node.children || [])) {\n          forgetNode(child);\n        }\n      }\n      function updateNode(snapshot) {\n        const element = rendererState().nodes.get(snapshot.guid);\n        if (!element) {\n          return;\n        }\n        if (element.__zuzuGuiType !== (snapshot.type || "Widget")) {\n          replaceNode(snapshot);\n          return;\n        }\n        if (element.__zuzuGuiType === "Input" && element.__zuzuGuiSubType !== (snapshot.props && snapshot.props.multiline ? "multiline" : "")) {\n          replaceNode(snapshot);\n          return;\n        }\n        applyCommonProps(element, snapshot);\n        applySpecificProps(element, snapshot);\n      }\n      function createZuzuGuiDomRenderer(options = {}) {\n        installSafeDefineProperties();\n        const doc = options.document || options.root && options.root.ownerDocument || document;\n        const root = options.root || doc.getElementById(options.rootId || "app");\n        if (!root) {\n          throw new Error("Zuzu GUI DOM renderer requires a root element");\n        }\n        const state = {\n          document: doc,\n          windowId: null,\n          nodes: /* @__PURE__ */ new Map(),\n          root,\n          sendEvent: typeof options.sendEvent === "function" ? options.sendEvent : null,\n          renderMenus: options.renderMenus === true\n        };\n        function withState(fn2) {\n          const previous = activeState;\n          activeState = state;\n          try {\n            return fn2();\n          } finally {\n            activeState = previous;\n          }\n        }\n        return {\n          render(payload = {}) {\n            return withState(() => {\n              state.windowId = payload.windowId;\n              state.nodes.clear();\n              root.replaceChildren(renderNode(payload.snapshot));\n            });\n          },\n          create(payload = {}) {\n            return withState(() => {\n              if (payload.snapshot && payload.snapshot.type === "Menu" && !state.renderMenus) {\n                return;\n              }\n              const parent = state.nodes.get(payload.parentGuid);\n              if (!parent) {\n                return;\n              }\n              const node = renderNode(payload.snapshot);\n              const index = Number.isInteger(payload.index) ? payload.index : null;\n              if (index == null || index >= parent.children.length) {\n                parent.appendChild(node);\n              } else {\n                parent.insertBefore(node, parent.children[index]);\n              }\n            });\n          },\n          update(payload = {}) {\n            return withState(() => {\n              if (!payload.snapshot) {\n                return;\n              }\n              if ((payload.snapshot.type === "Menu" || payload.snapshot.type === "MenuItem") && !state.renderMenus) {\n                return;\n              }\n              updateNode(payload.snapshot);\n            });\n          },\n          destroy(payload = {}) {\n            return withState(() => {\n              const node = state.nodes.get(payload.widgetGuid);\n              if (node && node.parentNode) {\n                node.parentNode.removeChild(node);\n              }\n              if (node) {\n                forgetNode(node);\n              }\n            });\n          },\n          nodeForGuid(guid) {\n            return state.nodes.get(guid) || null;\n          }\n        };\n      }\n      if (typeof module2 !== "undefined" && module2.exports) {\n        module2.exports = {\n          createZuzuGuiDomRenderer\n        };\n      }\n      if (typeof window !== "undefined") {\n        window.ZuzuGuiDomRenderer = {\n          createZuzuGuiDomRenderer\n        };\n      }\n    }\n  });\n\n  // lib/browser-gui-renderer.js\n  var require_browser_gui_renderer = __commonJS({\n    "lib/browser-gui-renderer.js"(exports2, module2) {\n      "use strict";\n      var {\n        createZuzuGuiDomRenderer\n      } = require_dom_renderer();\n      var DEFAULT_ROOT_ID = "zuzu-browser-gui";\n      var STYLE_ID = "zuzu-browser-gui-style";\n      function createBrowserGuiRenderer(options = {}) {\n        return createZuzuGuiDomRenderer({\n          document: options.document,\n          root: options.root,\n          rootId: options.rootId,\n          renderMenus: options.renderMenus,\n          sendEvent: options.sendEvent\n        });\n      }\n      function browserDocument(options) {\n        if (options.document) {\n          return options.document;\n        }\n        if (typeof document !== "undefined") {\n          return document;\n        }\n        throw new Error("Zuzu browser GUI requires a DOM document");\n      }\n      function resolveRoot(doc, options) {\n        if (options.root) {\n          return options.root;\n        }\n        const rootId = options.rootId || DEFAULT_ROOT_ID;\n        let root = doc.getElementById ? doc.getElementById(rootId) : null;\n        if (root) {\n          return root;\n        }\n        root = doc.createElement("div");\n        root.id = rootId;\n        root.className = "zuzu-browser-gui-root";\n        const parent = doc.body || doc.documentElement;\n        if (!parent) {\n          throw new Error("Zuzu browser GUI requires document.body");\n        }\n        parent.appendChild(root);\n        return root;\n      }\n      function installStyles(doc) {\n        if (!doc.createElement || !doc.head) {\n          return;\n        }\n        if (doc.getElementById && doc.getElementById(STYLE_ID)) {\n          return;\n        }\n        const style = doc.createElement("style");\n        style.id = STYLE_ID;\n        style.textContent = [\n          ".zuzu-browser-gui-root{position:fixed;inset:0;pointer-events:none;",\n          "z-index:2147480000;font:13px/1.4 system-ui,sans-serif;color:#202124;}",\n          ".zuzu-browser-window{position:absolute;display:flex;flex-direction:column;",\n          "min-width:220px;min-height:120px;background:#fff;border:1px solid #8c939f;",\n          "box-shadow:0 12px 36px rgba(0,0,0,.22);pointer-events:auto;}",\n          ".zuzu-browser-window-titlebar{display:flex;align-items:center;gap:8px;",\n          "height:32px;padding:0 6px 0 10px;background:#e9edf3;border-bottom:1px solid #c8ced8;",\n          "user-select:none;cursor:default;}",\n          ".zuzu-browser-window-title{flex:1;overflow:hidden;text-overflow:ellipsis;",\n          "white-space:nowrap;font-weight:600;}",\n          ".zuzu-browser-window-close{width:24px;height:24px;border:0;background:transparent;",\n          "font:16px/1 system-ui,sans-serif;cursor:pointer;}",\n          ".zuzu-browser-window-close:hover{background:#d8dde6;}",\n          ".zuzu-browser-window-content{flex:1;min-height:0;overflow:auto;padding:12px;}",\n          ".zuzu-browser-window-content>main{display:flex;flex-direction:column;gap:8px;}",\n          ".zuzu-browser-window nav{display:flex;gap:4px;padding:4px 8px;",\n          "border-bottom:1px solid #d7dbe2;background:#f7f8fa;}",\n          ".zuzu-browser-window .zuzu-menu-label{padding:4px 8px;font-weight:600;}",\n          ".zuzu-browser-window nav button{border:1px solid transparent;background:transparent;",\n          "padding:4px 8px;cursor:pointer;}",\n          ".zuzu-browser-window nav button:hover{border-color:#c4c9d2;background:#fff;}"\n        ].join("");\n        doc.head.appendChild(style);\n      }\n      function snapshotTitle(snapshot) {\n        const props = snapshot && snapshot.props ? snapshot.props : {};\n        return String(props.title || "Zuzu Window");\n      }\n      function snapshotDimension(snapshot, name2, fallback) {\n        const props = snapshot && snapshot.props ? snapshot.props : {};\n        const value = Number(props[name2]);\n        return Number.isFinite(value) && value > 0 ? value : fallback;\n      }\n      var WINDOW_FRAME_PROPS = /* @__PURE__ */ new Set([\n        "height",\n        "maxheight",\n        "maxwidth",\n        "minheight",\n        "minwidth",\n        "width"\n      ]);\n      function contentSnapshot(snapshot) {\n        if (!snapshot || snapshot.type !== "Window" || !snapshot.props) {\n          return snapshot;\n        }\n        const props = { ...snapshot.props };\n        for (const key of WINDOW_FRAME_PROPS) {\n          delete props[key];\n        }\n        return {\n          ...snapshot,\n          props\n        };\n      }\n      function optionValue(options, key, fallback = null) {\n        if (options && typeof options.get === "function") {\n          return options.get(key, fallback);\n        }\n        if (options && Object.prototype.hasOwnProperty.call(options, key)) {\n          return options[key];\n        }\n        return fallback;\n      }\n      function optionString2(options, key, fallback = "") {\n        const value = optionValue(options, key, fallback);\n        return value == null ? value : String(value);\n      }\n      function browserDialogHost(doc, options) {\n        if (options.dialogs && typeof options.dialogs === "object") {\n          return options.dialogs;\n        }\n        if (options.window && typeof options.window === "object") {\n          return options.window;\n        }\n        if (doc.defaultView && typeof doc.defaultView === "object") {\n          return doc.defaultView;\n        }\n        if (typeof window !== "undefined" && window) {\n          return window;\n        }\n        if (typeof globalThis !== "undefined" && globalThis) {\n          return globalThis;\n        }\n        return {};\n      }\n      function removeNode(node) {\n        if (node && node.parentNode) {\n          node.parentNode.removeChild(node);\n        }\n      }\n      function createBrowserGuiBridge(options = {}) {\n        const doc = browserDocument(options);\n        const root = resolveRoot(doc, options);\n        installStyles(doc);\n        let nextWindowId = 1;\n        let nextZIndex = Number(options.baseZIndex || 100);\n        const windows = /* @__PURE__ */ new Map();\n        const dialogs = browserDialogHost(doc, options);\n        function focusWindow(id) {\n          const win = windows.get(Number(id));\n          if (!win) {\n            return;\n          }\n          win.frame.style.zIndex = String(nextZIndex++);\n          if (typeof win.frame.focus === "function") {\n            win.frame.focus();\n          }\n        }\n        function closeNativeWindow(id, notifyClosed = true) {\n          const win = windows.get(Number(id));\n          if (!win) {\n            return;\n          }\n          windows.delete(Number(id));\n          removeNode(win.frame);\n          if (notifyClosed && typeof win.options.onClosed === "function") {\n            win.options.onClosed();\n          }\n        }\n        function requestClose(id) {\n          const win = windows.get(Number(id));\n          if (!win) {\n            return;\n          }\n          let cancelled = false;\n          if (typeof win.options.onCloseRequest === "function") {\n            cancelled = win.options.onCloseRequest() === true;\n          }\n          if (cancelled) {\n            return;\n          }\n          closeNativeWindow(id);\n        }\n        function createFrame(id, snapshot) {\n          const width = snapshotDimension(snapshot, "width", 480);\n          const height = snapshotDimension(snapshot, "height", 320);\n          const title = snapshotTitle(snapshot);\n          const frame = doc.createElement("div");\n          frame.className = "zuzu-browser-window";\n          frame.dataset.windowId = String(id);\n          frame.setAttribute("role", "dialog");\n          frame.setAttribute("aria-label", title);\n          frame.tabIndex = -1;\n          frame.style.width = `${width}px`;\n          frame.style.height = `${height}px`;\n          frame.style.left = `${24 + (id - 1) % 8 * 28}px`;\n          frame.style.top = `${24 + (id - 1) % 8 * 24}px`;\n          frame.addEventListener("mousedown", () => focusWindow(id));\n          const titlebar = doc.createElement("div");\n          titlebar.className = "zuzu-browser-window-titlebar";\n          const titleText = doc.createElement("span");\n          titleText.className = "zuzu-browser-window-title";\n          titleText.textContent = title;\n          const close = doc.createElement("button");\n          close.className = "zuzu-browser-window-close";\n          close.type = "button";\n          close.setAttribute("aria-label", `Close ${title}`);\n          close.textContent = "x";\n          close.addEventListener("click", () => requestClose(id));\n          titlebar.append(titleText, close);\n          const content = doc.createElement("div");\n          content.className = "zuzu-browser-window-content";\n          frame.append(titlebar, content);\n          return {\n            frame,\n            content,\n            titleText\n          };\n        }\n        return {\n          windows,\n          openWindow(snapshot, bridgeOptions = {}) {\n            const id = nextWindowId++;\n            const frameParts = createFrame(id, snapshot);\n            const renderer = createBrowserGuiRenderer({\n              document: doc,\n              root: frameParts.content,\n              renderMenus: true,\n              sendEvent(payload) {\n                if (typeof bridgeOptions.onEvent === "function") {\n                  bridgeOptions.onEvent(payload);\n                }\n              }\n            });\n            windows.set(id, {\n              id,\n              snapshot,\n              options: bridgeOptions,\n              renderer,\n              ...frameParts\n            });\n            root.appendChild(frameParts.frame);\n            renderer.render({\n              windowId: id,\n              snapshot: contentSnapshot(snapshot)\n            });\n            focusWindow(id);\n            return id;\n          },\n          closeWindow(id) {\n            closeNativeWindow(id);\n          },\n          createWidget(id, parentGuid, snapshot, index) {\n            const win = windows.get(Number(id));\n            if (win) {\n              win.renderer.create({\n                parentGuid,\n                snapshot,\n                index\n              });\n            }\n          },\n          updateWidget(id, snapshot) {\n            const win = windows.get(Number(id));\n            if (!win) {\n              return;\n            }\n            if (snapshot && snapshot.type === "Window") {\n              win.snapshot = snapshot;\n              const title = snapshotTitle(snapshot);\n              win.titleText.textContent = title;\n              win.frame.setAttribute("aria-label", title);\n              win.frame.style.width = `${snapshotDimension(snapshot, "width", 480)}px`;\n              win.frame.style.height = `${snapshotDimension(snapshot, "height", 320)}px`;\n              return;\n            }\n            win.renderer.update({\n              snapshot\n            });\n          },\n          destroyWidget(id, widgetGuid) {\n            const win = windows.get(Number(id));\n            if (win) {\n              win.renderer.destroy({\n                widgetGuid\n              });\n            }\n          },\n          alert(message, optionsForDialog = {}) {\n            if (typeof dialogs.alert === "function") {\n              dialogs.alert(String(message ?? ""));\n            }\n            return true;\n          },\n          confirm(message, optionsForDialog = {}) {\n            if (typeof dialogs.confirm === "function") {\n              return dialogs.confirm(String(message ?? "")) ? true : false;\n            }\n            return optionValue(optionsForDialog, "default", false) ? true : false;\n          },\n          prompt(message, optionsForDialog = {}) {\n            const defaultValue = optionString2(\n              optionsForDialog,\n              "value",\n              optionString2(optionsForDialog, "default", "")\n            );\n            if (typeof dialogs.prompt === "function") {\n              return dialogs.prompt(String(message ?? ""), defaultValue);\n            }\n            return defaultValue;\n          },\n          colourPicker(optionsForDialog = {}) {\n            const defaultValue = optionString2(\n              optionsForDialog,\n              "value",\n              "#000000"\n            );\n            if (typeof dialogs.colourPicker === "function") {\n              return dialogs.colourPicker(defaultValue, optionsForDialog);\n            }\n            if (typeof dialogs.colorPicker === "function") {\n              return dialogs.colorPicker(defaultValue, optionsForDialog);\n            }\n            if (typeof dialogs.prompt === "function") {\n              const answer = dialogs.prompt(\n                optionString2(optionsForDialog, "label", "Colour:"),\n                defaultValue\n              );\n              return answer == null ? defaultValue : answer;\n            }\n            return defaultValue;\n          },\n          fileOpen() {\n            throw new Error(\n              "GUI_DIALOGUE_UNSUPPORTED: file dialogues are unsupported in JS/Browser"\n            );\n          },\n          fileSave() {\n            throw new Error(\n              "GUI_DIALOGUE_UNSUPPORTED: file dialogues are unsupported in JS/Browser"\n            );\n          },\n          directoryOpen() {\n            throw new Error(\n              "GUI_DIALOGUE_UNSUPPORTED: directory dialogues are unsupported in JS/Browser"\n            );\n          },\n          directorySave() {\n            throw new Error(\n              "GUI_DIALOGUE_UNSUPPORTED: directory dialogues are unsupported in JS/Browser"\n            );\n          },\n          focusWindow\n        };\n      }\n      module2.exports = {\n        createBrowserGuiBridge,\n        createBrowserGuiRenderer\n      };\n    }\n  });\n\n  // lib/host/browser-host.js\n  var require_browser_host = __commonJS({\n    "lib/host/browser-host.js"(exports2, module2) {\n      "use strict";\n      function _splitPath(value) {\n        return String(value ?? "").split(/[\\\\/]+/u).filter(Boolean);\n      }\n      function _normalizePath(value) {\n        const isAbs = String(value ?? "").startsWith("/");\n        const stack = [];\n        for (const part of _splitPath(value)) {\n          if (part === ".") {\n            continue;\n          }\n          if (part === "..") {\n            if (stack.length > 0) {\n              stack.pop();\n            }\n            continue;\n          }\n          stack.push(part);\n        }\n        if (isAbs) {\n          return `/${stack.join("/")}`;\n        }\n        return stack.join("/") || ".";\n      }\n      function _resolvePath(...parts) {\n        const raw = parts.map((item) => String(item ?? "")).join("/");\n        const seeded = raw.startsWith("/") ? raw : `/${raw}`;\n        return _normalizePath(seeded);\n      }\n      function _dirname(value) {\n        const normalized = _normalizePath(value);\n        if (normalized === "/" || normalized === ".") {\n          return "/";\n        }\n        const parts = _splitPath(normalized);\n        parts.pop();\n        return parts.length > 0 ? `/${parts.join("/")}` : "/";\n      }\n      function _sourceUrlComment(runOptions = {}) {\n        const filename = runOptions.filename == null ? "/<browser>.zzs" : String(runOptions.filename);\n        return `\n//# sourceURL=${filename.replace(/[\\r\\n]/gu, "_")}`;\n      }\n      var browserModuleUrls = /* @__PURE__ */ new Map();\n      function _normalizeModuleName(value) {\n        const name2 = String(value ?? "").trim().replace(/\\\\/gu, "/");\n        if (name2 === "" || name2.startsWith("/") || name2.endsWith("/") || /(^|\\/)\\.\\.?(\\/|$)/u.test(name2)) {\n          throw new Error(`Invalid browser module name: ${value}`);\n        }\n        return name2.replace(/\\.zzm$/u, "");\n      }\n      function _moduleNameFromPath(filename) {\n        const path = _resolvePath(filename);\n        if (!path.startsWith("/modules/") || !path.endsWith(".zzm")) {\n          return null;\n        }\n        return path.slice("/modules/".length, -".zzm".length);\n      }\n      function addBrowserModule(moduleName, url) {\n        const logicalName = _normalizeModuleName(moduleName);\n        const moduleUrl = String(url ?? "").trim();\n        if (moduleUrl === "") {\n          throw new Error(`Invalid URL for browser module \'${logicalName}\'`);\n        }\n        browserModuleUrls.set(logicalName, moduleUrl);\n        return logicalName;\n      }\n      function hasBrowserModules() {\n        return browserModuleUrls.size > 0;\n      }\n      function _browserEval(source, context, runOptions = {}) {\n        context.globalThis = context;\n        const sourceUrl = _sourceUrlComment(runOptions);\n        try {\n          const expr = Function(\n            "__zuzu_context",\n            `with ( __zuzu_context ) { return ( ${source} ); }${sourceUrl}`\n          );\n          return expr(context);\n        } catch (_exprError) {\n          const script = Function(\n            "__zuzu_context",\n            `with ( __zuzu_context ) { ${source}\n }${sourceUrl}`\n          );\n          return script(context);\n        }\n      }\n      function _defaultGuiBridge(options) {\n        if (Object.prototype.hasOwnProperty.call(options, "guiBridge")) {\n          return options.guiBridge;\n        }\n        const doc = options.document || (typeof document !== "undefined" ? document : null);\n        if (!doc || typeof doc.createElement !== "function") {\n          return null;\n        }\n        let bridge = null;\n        function getBridge() {\n          if (bridge) {\n            return bridge;\n          }\n          const {\n            createBrowserGuiBridge\n          } = require_browser_gui_renderer();\n          bridge = createBrowserGuiBridge({\n            document: doc,\n            root: options.guiRoot,\n            rootId: options.guiRootId,\n            baseZIndex: options.guiBaseZIndex,\n            dialogs: options.guiDialogs,\n            window: options.window\n          });\n          return bridge;\n        }\n        return {\n          get windows() {\n            return getBridge().windows;\n          },\n          openWindow(...args) {\n            return getBridge().openWindow(...args);\n          },\n          closeWindow(...args) {\n            return getBridge().closeWindow(...args);\n          },\n          createWidget(...args) {\n            return getBridge().createWidget(...args);\n          },\n          updateWidget(...args) {\n            return getBridge().updateWidget(...args);\n          },\n          destroyWidget(...args) {\n            return getBridge().destroyWidget(...args);\n          },\n          focusWindow(...args) {\n            return getBridge().focusWindow(...args);\n          },\n          alert(...args) {\n            return getBridge().alert(...args);\n          },\n          confirm(...args) {\n            return getBridge().confirm(...args);\n          },\n          prompt(...args) {\n            return getBridge().prompt(...args);\n          },\n          colourPicker(...args) {\n            return getBridge().colourPicker(...args);\n          },\n          fileOpen(...args) {\n            return getBridge().fileOpen(...args);\n          },\n          fileSave(...args) {\n            return getBridge().fileSave(...args);\n          },\n          directoryOpen(...args) {\n            return getBridge().directoryOpen(...args);\n          },\n          directorySave(...args) {\n            return getBridge().directorySave(...args);\n          }\n        };\n      }\n      function createBrowserHost(options = {}) {\n        const repoRoot = options.repoRoot || "/";\n        const includePaths = Array.isArray(options.includePaths) ? options.includePaths.map((item) => _resolvePath(item)) : [];\n        const virtualFiles = new Map(Object.entries(options.virtualFiles || {}).map(([filename, source]) => [_resolvePath(filename), String(source)]));\n        const jsModules = new Map(Object.entries(options.jsModules || {}).map(([filename, loaded]) => [_resolvePath(filename), loaded]));\n        const fetchedFiles = /* @__PURE__ */ new Map();\n        const fetchingFiles = /* @__PURE__ */ new Map();\n        const optionModuleUrls = new Map(\n          Object.entries(options.remoteModules || {}).map(([name2, url]) => [_normalizeModuleName(name2), String(url)])\n        );\n        const fetchText = typeof options.fetch === "function" ? options.fetch : typeof fetch === "function" ? fetch : null;\n        const fetchModule = typeof options.fetchModule === "function" ? options.fetchModule : null;\n        const runInContext = typeof options.evaluate === "function" ? options.evaluate : _browserEval;\n        const capabilities2 = /* @__PURE__ */ new Set([\n          "console",\n          "time",\n          "module_load",\n          "module_fetch",\n          "file_availability",\n          "http",\n          "js",\n          "gui"\n        ]);\n        const workerSource = options.workerSource || typeof globalThis !== "undefined" && globalThis.__ZUZU_BROWSER_WORKER_SOURCE__ || null;\n        const workerUrl = options.workerUrl || typeof globalThis !== "undefined" && globalThis.__ZUZU_BROWSER_WORKER_URL__ || null;\n        const workerFactory = typeof options.workerFactory === "function" ? options.workerFactory : typeof globalThis !== "undefined" && typeof globalThis.__ZUZU_BROWSER_WORKER_FACTORY__ === "function" ? globalThis.__ZUZU_BROWSER_WORKER_FACTORY__ : null;\n        if (workerSource || workerUrl || workerFactory) {\n          capabilities2.add("worker");\n        }\n        const gui = _defaultGuiBridge(options);\n        function browserModuleUrlForPath(filename) {\n          const logicalName = _moduleNameFromPath(filename);\n          if (!logicalName) {\n            return null;\n          }\n          if (optionModuleUrls.has(logicalName)) {\n            return optionModuleUrls.get(logicalName);\n          }\n          return browserModuleUrls.get(logicalName) || null;\n        }\n        function hasAsyncModules() {\n          return optionModuleUrls.size > 0 || browserModuleUrls.size > 0;\n        }\n        async function fetchBrowserModule(key, url) {\n          if (fetchedFiles.has(key)) {\n            return fetchedFiles.get(key);\n          }\n          if (fetchingFiles.has(key)) {\n            return fetchingFiles.get(key);\n          }\n          if (!fetchText) {\n            throw new Error(`Exception: Browser host cannot fetch module \'${key}\'`);\n          }\n          const pending = Promise.resolve(fetchText(url)).then(async (response) => {\n            if (typeof response === "string") {\n              return response;\n            }\n            if (response && response.ok === false) {\n              throw new Error(\n                `Exception: Fetch failed for browser module \'${key}\' (${response.status})`\n              );\n            }\n            if (!response || typeof response.text !== "function") {\n              throw new Error(\n                `Exception: Fetch did not return text for browser module \'${key}\'`\n              );\n            }\n            return response.text();\n          }).then((source) => {\n            const text = String(source);\n            fetchedFiles.set(key, text);\n            fetchingFiles.delete(key);\n            return text;\n          }, (err) => {\n            fetchingFiles.delete(key);\n            throw err;\n          });\n          fetchingFiles.set(key, pending);\n          return pending;\n        }\n        return {\n          name: "browser",\n          repoRoot,\n          includePaths,\n          capabilities: capabilities2,\n          gui,\n          workerSource,\n          workerUrl,\n          workerFactory,\n          cwd() {\n            return "/";\n          },\n          resolve(...parts) {\n            return _resolvePath(...parts);\n          },\n          dirname(value) {\n            return _dirname(value);\n          },\n          join(...parts) {\n            return _normalizePath(parts.map((item) => String(item ?? "")).join("/"));\n          },\n          readFileText(filename) {\n            const key = _resolvePath(filename);\n            if (virtualFiles.has(key)) {\n              return virtualFiles.get(key);\n            }\n            if (fetchedFiles.has(key)) {\n              return fetchedFiles.get(key);\n            }\n            if (fetchModule) {\n              const fetched = fetchModule(key);\n              if (typeof fetched === "string") {\n                fetchedFiles.set(key, fetched);\n                return fetched;\n              }\n            }\n            if (browserModuleUrlForPath(key)) {\n              throw new Error(`Exception: Browser module \'${filename}\' requires asynchronous loading`);\n            }\n            throw new Error(`Exception: Browser host cannot read file \'${filename}\'`);\n          },\n          async readFileTextAsync(filename) {\n            const key = _resolvePath(filename);\n            if (virtualFiles.has(key)) {\n              return virtualFiles.get(key);\n            }\n            if (fetchedFiles.has(key)) {\n              return fetchedFiles.get(key);\n            }\n            const browserModuleUrl = browserModuleUrlForPath(key);\n            if (browserModuleUrl) {\n              return fetchBrowserModule(key, browserModuleUrl);\n            }\n            return this.readFileText(key);\n          },\n          fileExists(filename) {\n            const key = _resolvePath(filename);\n            if (virtualFiles.has(key) || jsModules.has(key) || fetchedFiles.has(key)) {\n              return true;\n            }\n            if (browserModuleUrlForPath(key)) {\n              return true;\n            }\n            if (fetchModule) {\n              const fetched = fetchModule(key);\n              if (typeof fetched === "string") {\n                fetchedFiles.set(key, fetched);\n                return true;\n              }\n            }\n            return false;\n          },\n          runInContext(source, context, runOptions = {}) {\n            return runInContext(source, context, runOptions);\n          },\n          consoleLog(value) {\n            if (typeof options.consoleLog === "function") {\n              options.consoleLog(value);\n              return;\n            }\n            if (typeof console !== "undefined" && typeof console.log === "function") {\n              console.log(value);\n            }\n          },\n          now() {\n            return Date.now();\n          },\n          getEnv(_name) {\n            return null;\n          },\n          loadJsModule(filename) {\n            const key = _resolvePath(filename);\n            if (!jsModules.has(key)) {\n              throw new Error(`Exception: Browser host has no JS module for \'${filename}\'`);\n            }\n            return jsModules.get(key);\n          },\n          hasAsyncModules\n        };\n      }\n      module2.exports = {\n        addBrowserModule,\n        createBrowserHost,\n        hasBrowserModules\n      };\n    }\n  });\n\n  // lib/transpiler-utils.js\n  var require_transpiler_utils = __commonJS({\n    "lib/transpiler-utils.js"(exports2, module2) {\n      "use strict";\n      function isEscaped(text, idx) {\n        let k = idx - 1;\n        let backslashes = 0;\n        while (k >= 0 && text[k] === "\\\\") {\n          backslashes++;\n          k--;\n        }\n        return backslashes % 2 === 1;\n      }\n      function findMatching(source, start, openChar, closeChar) {\n        let depth = 0;\n        let quote = null;\n        for (let i = start; i < source.length; i++) {\n          const ch = source[i];\n          if (quote) {\n            if (ch === quote && !isEscaped(source, i)) {\n              quote = null;\n            }\n            continue;\n          }\n          if (ch === \'"\' || ch === "\'" || ch === "`") {\n            quote = ch;\n            continue;\n          }\n          if (ch === openChar) {\n            depth++;\n          } else if (ch === closeChar) {\n            depth--;\n            if (depth === 0) {\n              return i;\n            }\n          }\n        }\n        return -1;\n      }\n      function splitCaseValues(text) {\n        return text.split(",").map((v) => v.trim()).filter((v) => v.length > 0);\n      }\n      function stripPod(source) {\n        const lines = source.split(/\\r?\\n/);\n        const out = [];\n        let inPod = false;\n        for (const line of lines) {\n          if (/^=cut\\b/.test(line)) {\n            inPod = false;\n            continue;\n          }\n          if (/^=\\w+/.test(line)) {\n            inPod = true;\n            continue;\n          }\n          if (inPod) {\n            continue;\n          }\n          out.push(line);\n        }\n        return out.join("\\n");\n      }\n      function stripPodPreservingLines(source) {\n        const lines = source.split(/\\r?\\n/);\n        const out = [];\n        let inPod = false;\n        for (const line of lines) {\n          if (/^=cut\\b/.test(line)) {\n            inPod = false;\n            out.push("");\n            continue;\n          }\n          if (/^=\\w+/.test(line)) {\n            inPod = true;\n            out.push("");\n            continue;\n          }\n          out.push(inPod ? "" : line);\n        }\n        return out.join("\\n");\n      }\n      module2.exports = {\n        isEscaped,\n        findMatching,\n        splitCaseValues,\n        stripPod,\n        stripPodPreservingLines\n      };\n    }\n  });\n\n  // lib/transpiler-new/errors.js\n  var require_errors = __commonJS({\n    "lib/transpiler-new/errors.js"(exports2, module2) {\n      "use strict";\n      var TranspilerSyntaxError = class extends Error {\n        constructor(message, token = null) {\n          const suffix = token && token.line != null && token.column != null ? ` at ${token.line}:${token.column}` : "";\n          super(`${message}${suffix}`);\n          this.name = "TranspilerSyntaxError";\n          this.token = token;\n        }\n      };\n      var UnsupportedSyntaxError = class extends Error {\n        constructor(message, token = null) {\n          const suffix = token && token.line != null && token.column != null ? ` at ${token.line}:${token.column}` : "";\n          super(`${message}${suffix}`);\n          this.name = "UnsupportedSyntaxError";\n          this.token = token;\n        }\n      };\n      module2.exports = {\n        TranspilerSyntaxError,\n        UnsupportedSyntaxError\n      };\n    }\n  });\n\n  // lib/transpiler-new/lexer.js\n  var require_lexer = __commonJS({\n    "lib/transpiler-new/lexer.js"(exports2, module2) {\n      "use strict";\n      var { stripPod } = require_transpiler_utils();\n      var {\n        TranspilerSyntaxError,\n        UnsupportedSyntaxError\n      } = require_errors();\n      var UTF8_ENCODER = new TextEncoder();\n      var KEYWORDS = /* @__PURE__ */ new Set([\n        "from",\n        "import",\n        "as",\n        "let",\n        "const",\n        "function",\n        "async",\n        "await",\n        "spawn",\n        "return",\n        "if",\n        "else",\n        "true",\n        "false",\n        "null",\n        "and",\n        "or",\n        "xor",\n        "nand",\n        "nor",\n        "xnor",\n        "onlyif",\n        "butnot",\n        "not",\n        // TODO: Remove stale legacy JS-only words that are not current\n        // ZuzuScript keywords: contains, difference, elsif, export, foreach,\n        // given, isa, my, not_in, our, package, sub, then, use, when.\n        "not_in",\n        "eq",\n        "ne",\n        "gt",\n        "ge",\n        "lt",\n        "le",\n        "cmp",\n        "eqi",\n        "nei",\n        "gti",\n        "gei",\n        "lti",\n        "lei",\n        "cmpi",\n        "mod",\n        "abs",\n        "sqrt",\n        "floor",\n        "ceil",\n        "round",\n        "int",\n        "length",\n        "uc",\n        "lc",\n        "say",\n        "class",\n        "trait",\n        "try",\n        "catch",\n        "switch",\n        "case",\n        "default",\n        "for",\n        "while",\n        "do",\n        "fn",\n        "next",\n        "continue",\n        "last",\n        "unless",\n        "export",\n        "die",\n        "new",\n        "method",\n        "static",\n        "extends",\n        "with",\n        "but",\n        "super",\n        "does",\n        "my",\n        "our",\n        "use",\n        "package",\n        "given",\n        "when",\n        "then",\n        "elsif",\n        "foreach",\n        "in",\n        "isa",\n        "can",\n        "does",\n        "typeof",\n        "debug",\n        "warn",\n        "assert",\n        "throw",\n        "sub",\n        "union",\n        "divides",\n        "intersection",\n        "difference",\n        "subsetof",\n        "supersetof",\n        "equivalentof",\n        "contains"\n      ]);\n      var SIMPLE_PUNCTUATION = /* @__PURE__ */ new Set(["(", ")", "{", "}", "[", "]", ",", ";", "."]);\n      var VALUE_PRESERVING_LOGICAL_OPERATORS = /* @__PURE__ */ new Set([\n        "and",\n        "\\u22C0",\n        "or",\n        "\\u22C1",\n        "xor",\n        "\\u22BB",\n        "xnor",\n        "\\u2194",\n        "nand",\n        "\\u22BC",\n        "nor",\n        "\\u22BD",\n        "onlyif",\n        "\\u22A8",\n        "butnot",\n        "\\u22AD"\n      ]);\n      function maybeValuePreservingOperator(value, peek, advance) {\n        if (VALUE_PRESERVING_LOGICAL_OPERATORS.has(value) && peek() === "?") {\n          advance();\n          return `${value}?`;\n        }\n        return value;\n      }\n      function decodeSimpleEscape(esc) {\n        switch (esc) {\n          case "n":\n            return "\\n";\n          case "r":\n            return "\\r";\n          case "t":\n            return "	";\n          case \'"\':\n          case "\'":\n          case "`":\n          case "/":\n          case "$":\n          case "\\\\":\n            return esc;\n          default:\n            return null;\n        }\n      }\n      function decodeUnicodeEscape(digits) {\n        if (!/^[0-9A-Fa-f]{4}$/u.test(digits)) {\n          return null;\n        }\n        const code = Number.parseInt(digits, 16);\n        if (code >= 55296 && code <= 57343) {\n          return null;\n        }\n        return String.fromCodePoint(code);\n      }\n      function decodeHexEscape(digits) {\n        if (!/^[0-9A-Fa-f]{2}$/u.test(digits)) {\n          return null;\n        }\n        return String.fromCharCode(Number.parseInt(digits, 16));\n      }\n      function isDigit(ch) {\n        return ch >= "0" && ch <= "9";\n      }\n      function isUnicodeLetter(ch) {\n        return ch.toLowerCase() !== ch.toUpperCase();\n      }\n      function isIdentifierStart(ch) {\n        return ch === "_" || ch === "$" || isUnicodeLetter(ch);\n      }\n      function isIdentifierPart(ch) {\n        return isIdentifierStart(ch) || isDigit(ch);\n      }\n      function appendUtf8ByteChars(out, ch) {\n        for (const byte of UTF8_ENCODER.encode(ch)) {\n          out.value += String.fromCharCode(byte);\n        }\n      }\n      function makeToken(type, value, start, end, source) {\n        return {\n          type,\n          value,\n          start: start.offset,\n          end: end.offset,\n          line: start.line,\n          column: start.column,\n          endLine: end.line,\n          endColumn: end.column,\n          raw: source.slice(start.offset, end.offset)\n        };\n      }\n      function readTemplateLiteral(text, start, state) {\n        const parts = [];\n        let offset = state.offset;\n        let line = state.line;\n        let column = state.column;\n        const delimiter = text.slice(start.offset, start.offset + 3) === "```" ? "```" : "`";\n        function peek(n = 0) {\n          return text[offset + n] || "";\n        }\n        function advance() {\n          const ch = text[offset] || "";\n          offset++;\n          if (ch === "\\n") {\n            line++;\n            column = 1;\n          } else {\n            column++;\n          }\n          return ch;\n        }\n        function cursor() {\n          return { offset, line, column };\n        }\n        function skipQuoted() {\n          const quote = advance();\n          while (offset < text.length) {\n            const ch = advance();\n            if (ch === "\\\\") {\n              advance();\n              continue;\n            }\n            if (ch === quote) {\n              return;\n            }\n          }\n          throw new TranspilerSyntaxError("Unterminated quoted section in template literal");\n        }\n        function skipLineComment() {\n          advance();\n          advance();\n          while (offset < text.length && peek() !== "\\n") {\n            advance();\n          }\n        }\n        function skipBlockComment() {\n          advance();\n          advance();\n          while (offset < text.length) {\n            if (peek() === "*" && peek(1) === "/") {\n              advance();\n              advance();\n              return;\n            }\n            advance();\n          }\n          throw new TranspilerSyntaxError("Unterminated block comment in template literal");\n        }\n        let textPart = "";\n        for (let i = 0; i < delimiter.length; i++) {\n          advance();\n        }\n        while (offset < text.length) {\n          const ch = peek();\n          if (delimiter === "```" ? text.slice(offset, offset + 3) === "```" : ch === "`") {\n            if (textPart.length > 0) {\n              parts.push({\n                type: "text",\n                value: textPart\n              });\n            }\n            for (let i = 0; i < delimiter.length; i++) {\n              advance();\n            }\n            return {\n              parts,\n              end: cursor()\n            };\n          }\n          if (delimiter !== "```" && ch === "\\\\") {\n            advance();\n            const escStart = cursor();\n            const esc = advance();\n            if (esc === "x") {\n              const digits = advance() + advance();\n              const decoded2 = decodeHexEscape(digits);\n              if (decoded2 == null) {\n                throw new TranspilerSyntaxError(\n                  "Invalid hex escape sequence",\n                  makeToken("escape", `x${digits}`, escStart, cursor(), text)\n                );\n              }\n              textPart += decoded2;\n              continue;\n            }\n            if (esc === "u") {\n              const digits = advance() + advance() + advance() + advance();\n              const decoded2 = decodeUnicodeEscape(digits);\n              if (decoded2 == null) {\n                throw new TranspilerSyntaxError(\n                  "Invalid unicode escape sequence",\n                  makeToken("escape", `u${digits}`, escStart, cursor(), text)\n                );\n              }\n              textPart += decoded2;\n              continue;\n            }\n            const decoded = decodeSimpleEscape(esc);\n            if (decoded == null) {\n              throw new TranspilerSyntaxError(\n                `Unsupported escape sequence \\\\${esc}`,\n                makeToken("escape", esc, escStart, cursor(), text)\n              );\n            }\n            textPart += decoded;\n            continue;\n          }\n          if (delimiter !== "```" && ch === "\\n") {\n            throw new TranspilerSyntaxError("Unterminated template literal", makeToken("template", "", start, cursor(), text));\n          }\n          if (ch === "$" && peek(1) === "{") {\n            if (textPart.length > 0) {\n              parts.push({\n                type: "text",\n                value: textPart\n              });\n              textPart = "";\n            }\n            advance();\n            advance();\n            const exprStart = offset;\n            let depth = 1;\n            while (offset < text.length) {\n              if (peek() === \'"\' || peek() === "\'" || peek() === "`") {\n                skipQuoted();\n                continue;\n              }\n              if (peek() === "/" && peek(1) === "/") {\n                skipLineComment();\n                continue;\n              }\n              if (peek() === "/" && peek(1) === "*") {\n                skipBlockComment();\n                continue;\n              }\n              const cur = advance();\n              if (cur === "{") {\n                depth++;\n              } else if (cur === "}") {\n                depth--;\n                if (depth === 0) {\n                  parts.push({\n                    type: "expr",\n                    value: text.slice(exprStart, offset - 1)\n                  });\n                  break;\n                }\n              }\n            }\n            if (depth !== 0) {\n              throw new TranspilerSyntaxError("Unterminated template interpolation");\n            }\n            continue;\n          }\n          textPart += advance();\n        }\n        throw new TranspilerSyntaxError("Unterminated template literal", makeToken("template", "", start, cursor(), text));\n      }\n      function tokenize(source) {\n        const text = stripPod(String(source ?? ""));\n        const tokens = [];\n        let lastToken = null;\n        let offset = 0;\n        let line = 1;\n        let column = 1;\n        function cursor() {\n          return { offset, line, column };\n        }\n        function peek(n = 0) {\n          return text[offset + n] || "";\n        }\n        function advance() {\n          const ch = text[offset] || "";\n          offset++;\n          if (ch === "\\n") {\n            line++;\n            column = 1;\n          } else {\n            column++;\n          }\n          return ch;\n        }\n        function addToken(type, value, start, end2) {\n          const token = makeToken(type, value, start, end2, text);\n          tokens.push(token);\n          lastToken = token;\n        }\n        function canStartRegex() {\n          if (!lastToken) {\n            return true;\n          }\n          if (lastToken.type === "punctuation" && ["(", "[", "{", ",", ";"].includes(lastToken.value)) {\n            return true;\n          }\n          if (lastToken.type === "operator") {\n            return true;\n          }\n          if (lastToken.type === "keyword" && [\n            "return",\n            "case",\n            "if",\n            "while",\n            "throw",\n            "and",\n            "and?",\n            "or",\n            "or?",\n            "xor",\n            "xor?",\n            "xnor",\n            "xnor?",\n            "nand",\n            "nand?",\n            "nor",\n            "nor?",\n            "onlyif",\n            "onlyif?",\n            "butnot",\n            "butnot?",\n            "not"\n          ].includes(lastToken.value)) {\n            return true;\n          }\n          return false;\n        }\n        function readInterpolationSource() {\n          advance();\n          advance();\n          const exprStart = offset;\n          let depth = 1;\n          while (offset < text.length) {\n            if (peek() === \'"\' || peek() === "\'" || peek() === "`") {\n              const quote = advance();\n              while (offset < text.length) {\n                const ch = advance();\n                if (ch === "\\\\") {\n                  advance();\n                  continue;\n                }\n                if (ch === quote) {\n                  break;\n                }\n              }\n              continue;\n            }\n            if (peek() === "/" && peek(1) === "/") {\n              advance();\n              advance();\n              while (offset < text.length && peek() !== "\\n") {\n                advance();\n              }\n              continue;\n            }\n            if (peek() === "/" && peek(1) === "*") {\n              advance();\n              advance();\n              while (offset < text.length) {\n                if (peek() === "*" && peek(1) === "/") {\n                  advance();\n                  advance();\n                  break;\n                }\n                advance();\n              }\n              continue;\n            }\n            const cur = advance();\n            if (cur === "{") {\n              depth++;\n            } else if (cur === "}") {\n              depth--;\n              if (depth === 0) {\n                return text.slice(exprStart, offset - 1);\n              }\n            }\n          }\n          throw new TranspilerSyntaxError("Unterminated template interpolation");\n        }\n        while (offset < text.length) {\n          const ch = peek();\n          if (offset === 0 && ch === "#" && peek(1) === "!") {\n            advance();\n            advance();\n            while (offset < text.length && peek() !== "\\n") {\n              advance();\n            }\n            continue;\n          }\n          if (ch === " " || ch === "	" || ch === "\\r" || ch === "\\n") {\n            advance();\n            continue;\n          }\n          if (ch === "/" && peek(1) === "/") {\n            while (offset < text.length && peek() !== "\\n") {\n              advance();\n            }\n            continue;\n          }\n          if (ch === "/" && peek(1) === "*") {\n            advance();\n            advance();\n            while (offset < text.length && !(peek() === "*" && peek(1) === "/")) {\n              advance();\n            }\n            if (offset >= text.length) {\n              throw new TranspilerSyntaxError("Unterminated block comment");\n            }\n            advance();\n            advance();\n            continue;\n          }\n          const start = cursor();\n          if (ch === "/" && peek(1) !== "/" && peek(1) !== "*" && canStartRegex()) {\n            let pattern = "";\n            let textPart = "";\n            const parts = [];\n            let inClass = false;\n            let sawInterpolation = false;\n            advance();\n            while (offset < text.length) {\n              const cur = peek();\n              if (cur === "\\\\") {\n                const backslash = advance();\n                const escaped = advance();\n                pattern += backslash + escaped;\n                textPart += backslash + escaped;\n                continue;\n              }\n              if (cur === "[") {\n                inClass = true;\n              } else if (cur === "]") {\n                inClass = false;\n              }\n              if (cur === "$" && peek(1) === "{") {\n                if (textPart.length > 0) {\n                  parts.push({\n                    type: "text",\n                    value: textPart\n                  });\n                  textPart = "";\n                }\n                const expr = readInterpolationSource();\n                parts.push({\n                  type: "expr",\n                  value: expr\n                });\n                sawInterpolation = true;\n                pattern += `\\${${expr}}`;\n                continue;\n              }\n              if (cur === "/" && !inClass) {\n                break;\n              }\n              if (cur === "\\n") {\n                throw new TranspilerSyntaxError("Unterminated regexp literal");\n              }\n              const value = advance();\n              pattern += value;\n              textPart += value;\n            }\n            if (peek() !== "/") {\n              throw new TranspilerSyntaxError("Unterminated regexp literal");\n            }\n            advance();\n            let flags = "";\n            while (/[a-z]/i.test(peek())) {\n              flags += advance();\n            }\n            if (sawInterpolation && textPart.length > 0) {\n              parts.push({\n                type: "text",\n                value: textPart\n              });\n            }\n            addToken("regexp", { pattern, parts, flags }, start, cursor());\n            continue;\n          }\n          if (ch === \'"\') {\n            if (peek(1) === \'"\' && peek(2) === \'"\') {\n              let value2 = "";\n              advance();\n              advance();\n              advance();\n              while (offset < text.length) {\n                if (peek() === \'"\' && peek(1) === \'"\' && peek(2) === \'"\') {\n                  advance();\n                  advance();\n                  advance();\n                  addToken("string", value2, start, cursor());\n                  value2 = null;\n                  break;\n                }\n                value2 += advance();\n              }\n              if (value2 !== null) {\n                throw new TranspilerSyntaxError("Unterminated triple-quoted string literal");\n              }\n              continue;\n            }\n            let value = "";\n            advance();\n            while (offset < text.length && peek() !== \'"\') {\n              if (peek() === "\\\\") {\n                const escStart = cursor();\n                advance();\n                const esc = advance();\n                if (esc === "x") {\n                  const digits = advance() + advance();\n                  const decoded = decodeHexEscape(digits);\n                  if (decoded == null) {\n                    throw new TranspilerSyntaxError(\n                      "Invalid hex escape sequence",\n                      makeToken("escape", `x${digits}`, escStart, cursor(), text)\n                    );\n                  }\n                  value += decoded;\n                } else if (esc === "u") {\n                  const digits = advance() + advance() + advance() + advance();\n                  const decoded = decodeUnicodeEscape(digits);\n                  if (decoded == null) {\n                    throw new TranspilerSyntaxError(\n                      "Invalid unicode escape sequence",\n                      makeToken("escape", `u${digits}`, escStart, cursor(), text)\n                    );\n                  }\n                  value += decoded;\n                } else {\n                  const decoded = decodeSimpleEscape(esc);\n                  if (decoded == null) {\n                    throw new TranspilerSyntaxError(\n                      `Unsupported escape sequence \\\\${esc}`,\n                      makeToken("escape", esc, escStart, cursor(), text)\n                    );\n                  }\n                  value += decoded;\n                }\n                continue;\n              }\n              if (peek() === "\\n") {\n                throw new TranspilerSyntaxError("Unterminated string literal");\n              }\n              value += advance();\n            }\n            if (peek() !== \'"\') {\n              throw new TranspilerSyntaxError("Unterminated string literal");\n            }\n            advance();\n            addToken("string", value, start, cursor());\n            continue;\n          }\n          if (ch === "\'") {\n            if (peek(1) === "\'" && peek(2) === "\'") {\n              const out = { value: "" };\n              advance();\n              advance();\n              advance();\n              while (offset < text.length) {\n                if (peek() === "\'" && peek(1) === "\'" && peek(2) === "\'") {\n                  advance();\n                  advance();\n                  advance();\n                  addToken("binary_string", out.value, start, cursor());\n                  out.value = null;\n                  break;\n                }\n                appendUtf8ByteChars(out, advance());\n              }\n              if (out.value !== null) {\n                throw new TranspilerSyntaxError("Unterminated triple-quoted binary string literal");\n              }\n              continue;\n            }\n            let value = "";\n            advance();\n            while (offset < text.length && peek() !== "\'") {\n              if (peek() === "\\\\") {\n                const escStart = cursor();\n                advance();\n                const esc = advance();\n                if (esc === "u") {\n                  throw new TranspilerSyntaxError(\n                    "Unicode escapes are not supported in binary strings",\n                    makeToken("escape", esc, escStart, cursor(), text)\n                  );\n                }\n                if (esc === "x") {\n                  const digits = advance() + advance();\n                  const decoded2 = decodeHexEscape(digits);\n                  if (decoded2 == null) {\n                    throw new TranspilerSyntaxError(\n                      "Invalid hex escape sequence",\n                      makeToken("escape", `x${digits}`, escStart, cursor(), text)\n                    );\n                  }\n                  value += decoded2;\n                  continue;\n                }\n                const decoded = decodeSimpleEscape(esc);\n                if (decoded == null) {\n                  throw new TranspilerSyntaxError(\n                    `Unsupported escape sequence \\\\${esc}`,\n                    makeToken("escape", esc, escStart, cursor(), text)\n                  );\n                }\n                value += decoded;\n                continue;\n              }\n              if (peek() === "\\n") {\n                throw new TranspilerSyntaxError("Unterminated binary string literal");\n              }\n              const out = { value: "" };\n              appendUtf8ByteChars(out, advance());\n              value += out.value;\n            }\n            if (peek() !== "\'") {\n              throw new TranspilerSyntaxError("Unterminated binary string literal");\n            }\n            advance();\n            addToken("binary_string", value, start, cursor());\n            continue;\n          }\n          if (ch === "`") {\n            const template = readTemplateLiteral(text, start, cursor());\n            offset = template.end.offset;\n            line = template.end.line;\n            column = template.end.column;\n            addToken("template", template.parts, start, template.end);\n            continue;\n          }\n          const twoChar = ch + peek(1);\n          const threeChar = twoChar + peek(2);\n          if (twoChar === "^^") {\n            advance();\n            advance();\n            addToken("identifier", "^^", start, cursor());\n            continue;\n          }\n          if (["...", "<<<", ">>>", "**=", "?:=", "<=>"].includes(threeChar)) {\n            advance();\n            advance();\n            advance();\n            addToken("operator", threeChar, start, cursor());\n            continue;\n          }\n          if (["{{", "<<", ">>", ":=", "==", "!=", "<=", ">=", "+=", "-=", "*=", "/=", "%=", "_=", "++", "--", "->", "?:", "**", "@@", "@?", "~=", "|>", "<|", "\\u2282\\u2283", "\\xD7=", "\\xF7="].includes(twoChar)) {\n            advance();\n            advance();\n            addToken("operator", twoChar, start, cursor());\n            continue;\n          }\n          if (ch === "_" && !isIdentifierPart(peek(1))) {\n            advance();\n            addToken("operator", "_", start, cursor());\n            continue;\n          }\n          if (isDigit(ch)) {\n            const radixDigitOk = ch === "0" ? peek(1) === "x" ? (c) => /[0-9a-fA-F]/.test(c || "") : peek(1) === "b" ? (c) => c === "0" || c === "1" : peek(1) === "o" ? (c) => /[0-7]/.test(c || "") : null : null;\n            if (radixDigitOk && radixDigitOk(peek(2))) {\n              const radix = peek(1) === "x" ? 16 : peek(1) === "b" ? 2 : 8;\n              advance();\n              advance();\n              let digits = "";\n              while (radixDigitOk(peek())) {\n                digits += advance();\n              }\n              addToken("number", String(parseInt(digits, radix)), start, cursor());\n              continue;\n            }\n            let value = "";\n            while (isDigit(peek())) {\n              value += advance();\n            }\n            if (peek() === "." && isDigit(peek(1))) {\n              value += advance();\n              while (isDigit(peek())) {\n                value += advance();\n              }\n            }\n            if (peek() === "E" && (isDigit(peek(1)) || (peek(1) === "+" || peek(1) === "-") && isDigit(peek(2)))) {\n              value += advance();\n              if (peek() === "+" || peek() === "-") {\n                value += advance();\n              }\n              while (isDigit(peek())) {\n                value += advance();\n              }\n            }\n            addToken("number", value, start, cursor());\n            continue;\n          }\n          if (ch === "\\u22A4" || ch === "\\u22A5") {\n            advance();\n            addToken("keyword", ch === "\\u22A4" ? "true" : "false", start, cursor());\n            continue;\n          }\n          if (isIdentifierStart(ch)) {\n            let value = "";\n            while (isIdentifierPart(peek())) {\n              value += advance();\n            }\n            if (KEYWORDS.has(value)) {\n              value = maybeValuePreservingOperator(value, peek, advance);\n              addToken("keyword", value, start, cursor());\n            } else {\n              addToken("identifier", value, start, cursor());\n            }\n            continue;\n          }\n          if (SIMPLE_PUNCTUATION.has(ch)) {\n            advance();\n            addToken("punctuation", ch, start, cursor());\n            continue;\n          }\n          if (["+", "-", "*", "/", "%", "<", ">", "=", "_", "?", ":", "~", "!", "\\\\", "&", "|", "^", "@", "\\xD7", "\\xF7", "\\xAC", "\\u22C0", "\\u22C1", "\\u22BB", "\\u22BC", "\\u22BD", "\\u2194", "\\u22A8", "\\u22AD"].includes(ch)) {\n            advance();\n            const value = maybeValuePreservingOperator(ch, peek, advance);\n            addToken("operator", value, start, cursor());\n            continue;\n          }\n          if (["\\u2261", "\\u2262", "\\u2260", "\\u2264", "\\u2265", "\\u2192", "\\u221A", "\\u230A", "\\u230B", "\\u2308", "\\u2309", "\\u2208", "\\u2209", "\\u22C3", "\\u22C2", "\\u2216", "\\u2282", "\\u2283", "\\xAB", "\\xBB", "\\u2276", "\\u2277", "\\u25B7", "\\u25C1", "\\u2223", "\\u2224"].includes(ch)) {\n            advance();\n            addToken("operator", ch, start, cursor());\n            continue;\n          }\n          throw new UnsupportedSyntaxError(\n            `Unsupported character ${JSON.stringify(ch)}`,\n            makeToken("unsupported", ch, start, start, text)\n          );\n        }\n        const end = cursor();\n        tokens.push(makeToken("eof", "", end, end, text));\n        return tokens;\n      }\n      module2.exports = {\n        tokenize\n      };\n    }\n  });\n\n  // lib/transpiler-new/ast.js\n  var require_ast = __commonJS({\n    "lib/transpiler-new/ast.js"(exports2, module2) {\n      "use strict";\n      function withLoc(node, start, end) {\n        return {\n          ...node,\n          loc: {\n            start: start ? {\n              offset: start.start,\n              line: start.line,\n              column: start.column\n            } : null,\n            end: end ? {\n              offset: end.end,\n              line: end.endLine,\n              column: end.endColumn\n            } : null\n          }\n        };\n      }\n      module2.exports = {\n        withLoc\n      };\n    }\n  });\n\n  // lib/transpiler-new/parser.js\n  var require_parser = __commonJS({\n    "lib/transpiler-new/parser.js"(exports2, module2) {\n      "use strict";\n      var { withLoc } = require_ast();\n      var { tokenize } = require_lexer();\n      var {\n        TranspilerSyntaxError,\n        UnsupportedSyntaxError\n      } = require_errors();\n      function parse(tokens, options = {}) {\n        const pendingSetClosers = [];\n        let index = 0;\n        let asyncContextDepth = 1;\n        function startLocFromToken(token) {\n          return {\n            start: token.start,\n            line: token.line,\n            column: token.column\n          };\n        }\n        function startLocFromNode(node) {\n          return {\n            start: node.loc.start.offset,\n            line: node.loc.start.line,\n            column: node.loc.start.column\n          };\n        }\n        function endLocFromToken(token) {\n          return {\n            end: token.end,\n            endLine: token.endLine,\n            endColumn: token.endColumn\n          };\n        }\n        function endLocFromNode(node) {\n          return {\n            end: node.loc.end.offset,\n            endLine: node.loc.end.line,\n            endColumn: node.loc.end.column\n          };\n        }\n        function current() {\n          return tokens[index];\n        }\n        function peekToken(n = 1) {\n          return tokens[index + n] || tokens[tokens.length - 1];\n        }\n        function previous() {\n          return tokens[index - 1];\n        }\n        function canTerminateSimpleStatement() {\n          const token = current();\n          if (token.type === "punctuation" && token.value === "}") {\n            return true;\n          }\n          if (token.type === "eof") {\n            return true;\n          }\n          return false;\n        }\n        function consumeStatementTerminator(message) {\n          if (match("punctuation", ";")) {\n            return;\n          }\n          if (canTerminateSimpleStatement()) {\n            return;\n          }\n          throw new TranspilerSyntaxError(message || "Expected statement terminator", current());\n        }\n        function atEnd() {\n          return current().type === "eof";\n        }\n        function match(type, value = null) {\n          const token = current();\n          if (token.type !== type) {\n            return false;\n          }\n          if (value != null && token.value !== value) {\n            return false;\n          }\n          index++;\n          return true;\n        }\n        function expect(type, value = null, message = null) {\n          const token = current();\n          if (match(type, value)) {\n            return previous();\n          }\n          throw new TranspilerSyntaxError(\n            message || `Expected ${value != null ? `${type} ${value}` : type}`,\n            token\n          );\n        }\n        function expectIdentifier(message = "Expected identifier") {\n          const token = current();\n          if (token.type === "identifier" || token.type === "keyword") {\n            if (token.value === "^^") {\n              throw new TranspilerSyntaxError("\'^^\' is reserved for the chain placeholder", token);\n            }\n            index++;\n            return token;\n          }\n          throw new TranspilerSyntaxError(message, token);\n        }\n        function parseProgram() {\n          const body = [];\n          const start = current();\n          while (!atEnd()) {\n            body.push(parseStatement());\n          }\n          return withLoc({\n            type: "Program",\n            body\n          }, start, previous() || start);\n        }\n        function matchPairListClose() {\n          if (current().type === "punctuation" && current().value === "}" && peekToken().type === "punctuation" && peekToken().value === "}") {\n            index += 2;\n            return true;\n          }\n          return false;\n        }\n        function parseExpressionRoot() {\n          const expr = parseExpression();\n          if (!atEnd()) {\n            throw new TranspilerSyntaxError("Unexpected token after expression", current());\n          }\n          return expr;\n        }\n        function parseStatement() {\n          const token = current();\n          if (token.type === "punctuation" && token.value === ";") {\n            index++;\n            return withLoc({ type: "EmptyStatement" }, token, token);\n          }\n          if (token.type === "keyword") {\n            switch (token.value) {\n              case "from":\n                return parseImportDeclaration();\n              case "let":\n              case "const":\n                return parseVariableDeclaration();\n              case "function":\n                return parseFunctionDeclaration();\n              case "async":\n                if (peekToken().type === "keyword" && peekToken().value === "function") {\n                  return parseFunctionDeclaration();\n                }\n                if (peekToken().type === "keyword" && peekToken().value === "fn") {\n                  const start = expect("keyword", "async");\n                  return parseFunctionDeclarationLikeFn(true, start);\n                }\n                break;\n              case "return":\n                return parseReturnStatement();\n              case "if":\n                return parseIfStatement();\n              case "for":\n                return parseForStatement();\n              case "while":\n                return parseWhileStatement();\n              case "switch":\n                return parseSwitchStatement();\n              case "next":\n              case "continue":\n                return parseLoopControlStatement("ContinueStatement");\n              case "last":\n                return parseLoopControlStatement("BreakStatement");\n              case "throw":\n                return parseThrowStatement();\n              case "die":\n                return parseDieStatement();\n              case "warn":\n                return parseWarnStatement();\n              case "assert":\n                return parseAssertStatement();\n              case "debug":\n                return parseDebugStatement();\n              case "say":\n                return parseSayStatement();\n              case "try":\n                return parseTryStatement();\n              case "class":\n                return parseClassDeclaration();\n              case "trait":\n                return parseTraitDeclaration();\n              case "export":\n                return parseExportDeclaration();\n              case "catch":\n              case "unless":\n                throw new UnsupportedSyntaxError(\n                  `Keyword ${token.value} is not supported by zuzu-js transpilation yet`,\n                  token\n                );\n              case "fn":\n                return parseFunctionDeclarationLikeFn();\n              default:\n                break;\n            }\n          }\n          if (token.type === "punctuation" && token.value === "{") {\n            return parseBlockStatement();\n          }\n          return parseExpressionStatement();\n        }\n        function parseExportDeclaration() {\n          const start = expect("keyword", "export");\n          const token = current();\n          const allowed = /* @__PURE__ */ new Set(["let", "const", "function", "async", "fn", "class", "trait"]);\n          if (token.type !== "keyword" || !allowed.has(token.value)) {\n            throw new TranspilerSyntaxError("Expected declaration after export", token);\n          }\n          const declaration = parseStatement();\n          declaration.exported = true;\n          declaration.loc.start = {\n            offset: start.start,\n            line: start.line,\n            column: start.column\n          };\n          return declaration;\n        }\n        function parseImportDeclaration() {\n          const start = expect("keyword", "from");\n          const moduleParts = [];\n          while (!(current().type === "keyword" && (current().value === "import" || current().value === "try"))) {\n            if (current().type === "identifier" || current().type === "keyword" || current().type === "operator" && current().value === "/" || current().type === "operator" && current().value === "." || current().type === "punctuation" && current().value === ".") {\n              moduleParts.push(current().value);\n              index++;\n              continue;\n            }\n            if (current().type === "string") {\n              moduleParts.push(current().value);\n              index++;\n              break;\n            }\n            throw new TranspilerSyntaxError("Invalid module path in import", current());\n          }\n          const tryMode = match("keyword", "try");\n          expect("keyword", "import");\n          let importAll = false;\n          const specifiers = [];\n          if (match("operator", "*")) {\n            if (tryMode) {\n              throw new TranspilerSyntaxError(\n                "Wildcard import \'*\' cannot be combined with try import",\n                previous()\n              );\n            }\n            importAll = true;\n          } else {\n            do {\n              const imported = expectIdentifier();\n              let local = imported;\n              if (match("keyword", "as")) {\n                local = expectIdentifier("Expected alias name after as");\n              }\n              specifiers.push({\n                type: "ImportSpecifier",\n                imported: imported.value,\n                local: local.value\n              });\n            } while (match("punctuation", ","));\n          }\n          let condition = null;\n          if (current().type === "keyword" && ["if", "unless"].includes(current().value)) {\n            const keyword = current();\n            if (importAll) {\n              throw new TranspilerSyntaxError(\n                "Wildcard import \'*\' cannot be combined with postfix if/unless",\n                keyword\n              );\n            }\n            index++;\n            condition = {\n              type: "PostfixCondition",\n              keyword: keyword.value,\n              test: parseExpression()\n            };\n          }\n          consumeStatementTerminator("Expected ; after import declaration");\n          return withLoc({\n            type: "ImportDeclaration",\n            source: moduleParts.join(""),\n            tryMode,\n            importAll,\n            specifiers,\n            condition\n          }, start, previous());\n        }\n        function parseVariableDeclaration() {\n          const start = expect("keyword");\n          if (current().type === "punctuation" && current().value === "{") {\n            return parseVariableUnpackDeclaration(start);\n          }\n          const declaration = parseVariableDeclarationParts(start);\n          consumeStatementTerminator("Expected ; after variable declaration");\n          return withLoc({\n            type: "VariableDeclaration",\n            ...declaration\n          }, start, previous());\n        }\n        function parseVariableDeclarationParts(start) {\n          let declaredType = null;\n          let id = expectIdentifier();\n          if (current().type === "identifier" && ![":=", "=", ";", ",", ")"].includes(current().value)) {\n            declaredType = id.value;\n            id = expectIdentifier("Expected variable name after type");\n          }\n          let isWeakStorage = parseOptionalWeakModifier("declaration");\n          let init = null;\n          if (match("operator", ":=") || match("operator", "=")) {\n            init = parseExpression();\n            isWeakStorage = parseOptionalWeakModifier("declaration") || isWeakStorage;\n          }\n          return {\n            kind: start.value,\n            declaredType,\n            id: withLoc({\n              type: "Identifier",\n              name: id.value\n            }, id, id),\n            init,\n            isWeakStorage\n          };\n        }\n        function parseVariableUnpackDeclaration(start) {\n          const pattern = parseDeclarationBindingPattern();\n          expect("operator", ":=", "Expected \':=\' after declaration binding pattern");\n          const init = parseExpression();\n          consumeStatementTerminator("Expected ; after variable unpack declaration");\n          return withLoc({\n            type: "VariableUnpackDeclaration",\n            kind: start.value,\n            pattern,\n            init\n          }, start, previous());\n        }\n        function parseDeclarationBindingPattern() {\n          const start = expect("punctuation", "{", "Expected \'{\' in declaration binding pattern");\n          const entries = [];\n          if (!match("punctuation", "}")) {\n            while (true) {\n              if (match("punctuation", ",")) {\n                continue;\n              }\n              if (match("punctuation", "}")) {\n                break;\n              }\n              entries.push(parseDeclarationBindingEntry());\n              if (match("punctuation", "}")) {\n                break;\n              }\n              match("punctuation", ",");\n            }\n          }\n          return withLoc({\n            type: "KeyedBindingPattern",\n            entries\n          }, start, previous());\n        }\n        function parseDeclarationBindingEntry() {\n          const start = current();\n          const binding = parseDeclarationBindingKeyAndName();\n          let defaultValue = null;\n          if (match("operator", ":=")) {\n            defaultValue = parseExpression();\n          }\n          const isWeakStorage = parseOptionalWeakModifier("declaration");\n          return withLoc({\n            type: "DeclarationBindingEntry",\n            key: binding.key,\n            declaredType: binding.declaredType,\n            name: binding.name,\n            defaultValue,\n            isWeakStorage\n          }, start, previous() || start);\n        }\n        function parseDeclarationBindingKeyAndName() {\n          if (current().type === "identifier") {\n            const first = current();\n            index++;\n            if (match("operator", ":")) {\n              const typed = parseTypedBindingName();\n              return {\n                key: bindingIdentifierKey(first),\n                declaredType: typed.declaredType,\n                name: typed.name\n              };\n            }\n            if (current().type === "identifier" || current().type === "keyword") {\n              const name2 = expectIdentifier("Expected unpacked binding name after type");\n              return {\n                key: bindingIdentifierKey(name2),\n                declaredType: first.value,\n                name: name2.value\n              };\n            }\n            return {\n              key: bindingIdentifierKey(first),\n              declaredType: null,\n              name: first.value\n            };\n          }\n          if (current().type === "keyword" || current().type === "string") {\n            const key = parseDeclarationBindingKey();\n            expect("operator", ":", "Expected \':\' after declaration binding key");\n            const typed = parseTypedBindingName();\n            return {\n              key,\n              declaredType: typed.declaredType,\n              name: typed.name\n            };\n          }\n          if (current().type === "template" || current().type === "punctuation" && current().value === "(") {\n            const key = parseDeclarationBindingKey();\n            expect("operator", ":", "Expected \':\' after declaration binding key");\n            const typed = parseTypedBindingName();\n            return {\n              key,\n              declaredType: typed.declaredType,\n              name: typed.name\n            };\n          }\n          throw new TranspilerSyntaxError("Expected unpacked binding in declaration", current());\n        }\n        function parseTypedBindingName() {\n          let declaredType = null;\n          let name2 = expectIdentifier("Expected unpacked binding name");\n          if (current().type === "identifier") {\n            declaredType = name2.value;\n            name2 = expectIdentifier("Expected unpacked binding name after type");\n          }\n          return {\n            declaredType,\n            name: name2.value\n          };\n        }\n        function bindingIdentifierKey(token) {\n          return withLoc({\n            type: "BraceIdentifier",\n            name: token.value\n          }, token, token);\n        }\n        function parseDeclarationBindingKey() {\n          const token = current();\n          if (token.type === "identifier" || token.type === "keyword") {\n            index++;\n            return withLoc({\n              type: "BraceIdentifier",\n              name: token.value\n            }, token, token);\n          }\n          if (token.type === "string") {\n            index++;\n            return withLoc({\n              type: "StringLiteral",\n              value: token.value\n            }, token, token);\n          }\n          if (token.type === "template") {\n            return parsePrimary();\n          }\n          if (match("punctuation", "(")) {\n            const expr = parseExpression();\n            expect("punctuation", ")", "Expected ) after declaration binding key");\n            return expr;\n          }\n          throw new TranspilerSyntaxError("Expected declaration binding key", token);\n        }\n        function parseFunctionDeclaration() {\n          let isAsync = false;\n          let start = current();\n          if (match("keyword", "async")) {\n            isAsync = true;\n            start = previous();\n          }\n          expect("keyword", "function");\n          const id = expectIdentifier();\n          if (match("punctuation", ";")) {\n            return withLoc({\n              type: "FunctionDeclaration",\n              id: {\n                type: "Identifier",\n                name: id.value\n              },\n              params: [],\n              returnType: null,\n              isAsync,\n              isPredeclared: true,\n              body: withLoc({\n                type: "BlockStatement",\n                body: []\n              }, id, id)\n            }, start, previous());\n          }\n          const params = parseParameterList();\n          const returnType = parseOptionalReturnType();\n          const body = parseBlockInAsyncContext(isAsync);\n          return withLoc({\n            type: "FunctionDeclaration",\n            id: {\n              type: "Identifier",\n              name: id.value\n            },\n            params,\n            returnType,\n            isAsync,\n            isPredeclared: false,\n            body\n          }, start, previous());\n        }\n        function parseFunctionDeclarationLikeFn(isAsync = false, startOverride = null) {\n          const start = startOverride || current();\n          expect("keyword", "fn");\n          const id = expectIdentifier();\n          const params = parseParameterList();\n          const returnType = parseOptionalReturnType();\n          const body = parseBlockInAsyncContext(isAsync);\n          return withLoc({\n            type: "FunctionDeclaration",\n            id: {\n              type: "Identifier",\n              name: id.value\n            },\n            params,\n            returnType,\n            isAsync,\n            body\n          }, start, previous());\n        }\n        function parseClassDeclaration() {\n          const start = expect("keyword", "class");\n          const id = expectIdentifier("Expected class name");\n          let base = null;\n          if (match("keyword", "extends")) {\n            const baseId = expectIdentifier("Expected base class name after extends");\n            base = withLoc({\n              type: "Identifier",\n              name: baseId.value\n            }, baseId, baseId);\n          }\n          const traits = parseTraitCompositionList();\n          if (match("punctuation", ";")) {\n            return withLoc({\n              type: "ClassDeclaration",\n              id: withLoc({\n                type: "Identifier",\n                name: id.value\n              }, id, id),\n              base,\n              traits,\n              body: [],\n              shorthand: true\n            }, start, previous());\n          }\n          expect("punctuation", "{", "Expected { to start class body");\n          const body = [];\n          while (!(current().type === "punctuation" && current().value === "}")) {\n            if (atEnd()) {\n              throw new TranspilerSyntaxError("Unterminated class declaration", current());\n            }\n            if (current().type === "punctuation" && current().value === ";") {\n              index++;\n              continue;\n            }\n            body.push(parseClassMember());\n          }\n          expect("punctuation", "}");\n          return withLoc({\n            type: "ClassDeclaration",\n            id: withLoc({\n              type: "Identifier",\n              name: id.value\n            }, id, id),\n            base,\n            traits,\n            body,\n            shorthand: false\n          }, start, previous());\n        }\n        function parseTraitDeclaration() {\n          const start = expect("keyword", "trait");\n          const id = expectIdentifier("Expected trait name");\n          expect("punctuation", "{", "Expected { to start trait body");\n          const body = [];\n          while (!(current().type === "punctuation" && current().value === "}")) {\n            if (atEnd()) {\n              throw new TranspilerSyntaxError("Unterminated trait declaration", current());\n            }\n            if (current().type === "punctuation" && current().value === ";") {\n              index++;\n              continue;\n            }\n            body.push(parseMethodDeclaration({ allowStatic: false }));\n          }\n          expect("punctuation", "}");\n          return withLoc({\n            type: "TraitDeclaration",\n            id: withLoc({\n              type: "Identifier",\n              name: id.value\n            }, id, id),\n            body\n          }, start, previous());\n        }\n        function parseTraitCompositionList() {\n          const traits = [];\n          if (current().type === "keyword" && ["with", "but"].includes(current().value)) {\n            index++;\n            do {\n              const traitId = expectIdentifier("Expected trait name");\n              traits.push(withLoc({\n                type: "Identifier",\n                name: traitId.value\n              }, traitId, traitId));\n            } while (match("punctuation", ","));\n          }\n          return traits;\n        }\n        function parseOptionalWeakModifier(context) {\n          if (current().type !== "keyword" || current().value !== "but") {\n            return false;\n          }\n          index++;\n          const modifier = current();\n          if (!(modifier.type === "identifier" || modifier.type === "keyword") || modifier.value !== "weak") {\n            throw new TranspilerSyntaxError(\n              `Unknown but modifier \'${modifier.value || ""}\' in ${context}; expected \'but weak\'`,\n              modifier\n            );\n          }\n          index++;\n          return true;\n        }\n        function parseClassMember() {\n          if (current().type === "keyword" && ["static", "async"].includes(current().value)) {\n            return parseMethodDeclaration({ allowStatic: true });\n          }\n          if (current().type === "keyword" && current().value === "method") {\n            return parseMethodDeclaration({ allowStatic: true });\n          }\n          if (current().type === "keyword" && ["let", "const"].includes(current().value)) {\n            return parseFieldDeclaration();\n          }\n          if (current().type === "keyword" && current().value === "class") {\n            return parseClassDeclaration();\n          }\n          if (current().type === "keyword" && current().value === "trait") {\n            return parseTraitDeclaration();\n          }\n          throw new UnsupportedSyntaxError("Unsupported class member", current());\n        }\n        function parseMethodDeclaration({ allowStatic = true } = {}) {\n          const start = current();\n          let isStatic = false;\n          let isAsync = false;\n          while (current().type === "keyword" && ["static", "async"].includes(current().value)) {\n            if (current().value === "static") {\n              if (!allowStatic || isStatic) {\n                break;\n              }\n              isStatic = true;\n              index++;\n              continue;\n            }\n            if (isAsync) {\n              break;\n            }\n            isAsync = true;\n            index++;\n          }\n          expect("keyword", "method", "Expected method declaration");\n          const id = expectIdentifier("Expected method name");\n          if (match("punctuation", ";")) {\n            return withLoc({\n              type: "MethodDeclaration",\n              id: withLoc({\n                type: "Identifier",\n                name: id.value\n              }, id, id),\n              params: [],\n              returnType: null,\n              body: withLoc({\n                type: "BlockStatement",\n                body: []\n              }, id, id),\n              static: isStatic,\n              isAsync,\n              isPredeclared: true\n            }, start, previous());\n          }\n          const params = parseParameterList();\n          const returnType = parseOptionalReturnType();\n          const body = parseBlockInAsyncContext(isAsync);\n          return withLoc({\n            type: "MethodDeclaration",\n            id: withLoc({\n              type: "Identifier",\n              name: id.value\n            }, id, id),\n            params,\n            returnType,\n            body,\n            static: isStatic,\n            isAsync,\n            isPredeclared: false\n          }, start, previous());\n        }\n        function parseFieldDeclaration() {\n          const start = expect("keyword");\n          let typeName2 = null;\n          let id = expectIdentifier("Expected field name");\n          if (current().type === "identifier" && current().value !== "with" && !(current().type === "operator" && current().value === ":=") && !(current().type === "punctuation" && [";", "}"].includes(current().value))) {\n            typeName2 = id.value;\n            id = expectIdentifier("Expected field name after type");\n          }\n          const accessors = [];\n          if (match("keyword", "with")) {\n            do {\n              accessors.push(expectIdentifier("Expected accessor name").value);\n            } while (match("punctuation", ","));\n          }\n          let isWeakStorage = parseOptionalWeakModifier("field declaration");\n          let defaultValue = null;\n          if (match("operator", ":=")) {\n            defaultValue = parseExpression();\n            isWeakStorage = parseOptionalWeakModifier("field declaration") || isWeakStorage;\n          }\n          consumeStatementTerminator("Expected ; after field declaration");\n          return withLoc({\n            type: "FieldDeclaration",\n            kind: start.value,\n            typeName: typeName2,\n            id: withLoc({\n              type: "Identifier",\n              name: id.value\n            }, id, id),\n            accessors,\n            defaultValue,\n            isWeakStorage\n          }, start, previous());\n        }\n        function parseParameterList() {\n          expect("punctuation", "(");\n          const params = [];\n          if (!match("punctuation", ")")) {\n            while (true) {\n              if (match("punctuation", ",")) {\n                continue;\n              }\n              params.push(parseParameter());\n              if (match("punctuation", ")")) {\n                break;\n              }\n              if (match("punctuation", ",") && match("punctuation", ")")) {\n                break;\n              }\n            }\n          }\n          return params;\n        }\n        function parseParameter() {\n          const start = current();\n          let rest = false;\n          if (match("operator", "...")) {\n            if (current().type === "identifier" && peekToken().type === "identifier") {\n              const containerType = expectIdentifier("Expected parameter type after ...");\n              const id2 = expectIdentifier("Expected parameter name");\n              return withLoc({\n                type: "SpecialParameter",\n                special: "rest_only",\n                leadName: null,\n                containerType: containerType.value,\n                name: id2.value\n              }, start, previous() || start);\n            }\n            rest = true;\n          }\n          let typeName2 = null;\n          let id = expectIdentifier("Expected parameter name");\n          if (!rest && current().type === "operator" && current().value === "...") {\n            index++;\n            const first = expectIdentifier("Expected parameter type or name after ...");\n            let containerType;\n            let target;\n            if (current().type === "identifier" && !["?", ":=", ",", ")"].includes(current().value)) {\n              containerType = first.value;\n              target = expectIdentifier("Expected parameter name after special variadic type");\n            } else {\n              containerType = "Array";\n              target = first;\n            }\n            return withLoc({\n              type: "SpecialParameter",\n              special: "lead_rest",\n              leadName: id.value,\n              containerType,\n              name: target.value\n            }, start, previous() || start);\n          }\n          if (!rest && current().type === "identifier" && !["?", ":=", ",", ")"].includes(current().value) && peekToken().type !== "identifier") {\n            typeName2 = id.value;\n            id = expectIdentifier("Expected parameter name after type");\n          }\n          let optional = false;\n          let defaultValue = null;\n          if (match("operator", "?")) {\n            optional = true;\n          }\n          if (match("operator", ":=")) {\n            defaultValue = parseExpression();\n          }\n          return withLoc({\n            type: "Parameter",\n            name: id.value,\n            typeName: typeName2,\n            optional,\n            defaultValue,\n            rest\n          }, start, previous() || start);\n        }\n        function parseOptionalReturnType() {\n          if (current().type === "operator" && (current().value === "->" || current().value === "\\u2192")) {\n            index++;\n            return expectIdentifier("Expected return type after ->").value;\n          }\n          return null;\n        }\n        function parseReturnStatement() {\n          const start = expect("keyword", "return");\n          let argument = null;\n          if (!(current().type === "punctuation" && current().value === ";") && !(current().type === "keyword" && ["if", "unless"].includes(current().value))) {\n            argument = parseExpression();\n          }\n          const stmt = withLoc({\n            type: "ReturnStatement",\n            argument\n          }, start, previous() || start);\n          return finishStatement(stmt, "Expected ; after return statement");\n        }\n        function parseIfStatement() {\n          const start = expect("keyword", "if");\n          expect("punctuation", "(");\n          let declaration = null;\n          let test = null;\n          if (current().type === "keyword" && ["let", "const"].includes(current().value)) {\n            declaration = parseInlineVariableDeclaration();\n            test = declaration.id;\n          } else {\n            test = parseExpression();\n          }\n          expect("punctuation", ")", "Expected ) after if condition");\n          const consequent = parseBlockStatement();\n          let alternate = null;\n          if (match("keyword", "else")) {\n            if (current().type === "keyword" && current().value === "if") {\n              alternate = parseIfStatement();\n            } else {\n              alternate = parseBlockStatement();\n            }\n          }\n          return withLoc({\n            type: "IfStatement",\n            declaration,\n            test,\n            consequent,\n            alternate\n          }, start, previous());\n        }\n        function parseForStatement() {\n          const start = expect("keyword", "for");\n          expect("punctuation", "(");\n          let decl = null;\n          let id = null;\n          let iterable;\n          if (current().type === "keyword" && ["let", "const"].includes(current().value)) {\n            decl = expect("keyword");\n            id = expectIdentifier("Expected loop variable");\n            expect("keyword", "in", "Expected in inside for loop");\n            iterable = parseExpression();\n          } else if (current().type === "identifier" && peekToken().type === "keyword" && peekToken().value === "in") {\n            id = expectIdentifier("Expected loop variable");\n            expect("keyword", "in", "Expected in inside for loop");\n            iterable = parseExpression();\n          } else {\n            decl = { value: "const" };\n            id = {\n              value: "^^",\n              start: current().start,\n              end: current().end,\n              line: current().line,\n              column: current().column\n            };\n            iterable = parseExpression();\n          }\n          expect("punctuation", ")", "Expected ) after for loop header");\n          const body = parseBlockStatement();\n          let elseBlock = null;\n          if (match("keyword", "else")) {\n            elseBlock = parseBlockStatement();\n          }\n          return withLoc({\n            type: "ForInStatement",\n            kind: decl ? decl.value : null,\n            left: {\n              type: "Identifier",\n              name: id.value\n            },\n            iterable,\n            body,\n            elseBlock\n          }, start, previous());\n        }\n        function parseWhileStatement() {\n          const start = expect("keyword", "while");\n          expect("punctuation", "(");\n          let declaration = null;\n          let test = null;\n          if (current().type === "keyword" && ["let", "const"].includes(current().value)) {\n            declaration = parseInlineVariableDeclaration();\n            test = declaration.id;\n          } else {\n            test = parseExpression();\n          }\n          expect("punctuation", ")", "Expected ) after while condition");\n          const body = parseBlockStatement();\n          return withLoc({\n            type: "WhileStatement",\n            declaration,\n            test,\n            body\n          }, start, previous());\n        }\n        function parseSwitchStatement() {\n          const start = expect("keyword", "switch");\n          expect("punctuation", "(");\n          const discriminant = parseExpression();\n          let comparator = "==";\n          if (match("operator", ":")) {\n            const token = current();\n            const operator = parseSwitchComparator();\n            if (!operator) {\n              throw new TranspilerSyntaxError("Expected switch comparator after :", token);\n            }\n            comparator = operator;\n          }\n          expect("punctuation", ")", "Expected ) after switch header");\n          expect("punctuation", "{", "Expected { to start switch body");\n          const cases = [];\n          let defaultCase = null;\n          while (!(current().type === "punctuation" && current().value === "}")) {\n            if (atEnd()) {\n              throw new TranspilerSyntaxError("Unterminated switch statement", current());\n            }\n            if (current().type === "keyword" && current().value === "case") {\n              cases.push(parseSwitchCase());\n              continue;\n            }\n            if (current().type === "keyword" && current().value === "default") {\n              if (defaultCase) {\n                throw new TranspilerSyntaxError("Duplicate default clause in switch statement", current());\n              }\n              defaultCase = parseSwitchDefaultCase();\n              continue;\n            }\n            throw new TranspilerSyntaxError("Expected case or default inside switch statement", current());\n          }\n          expect("punctuation", "}");\n          return withLoc({\n            type: "SwitchStatement",\n            discriminant,\n            comparator,\n            cases,\n            defaultCase\n          }, start, previous());\n        }\n        function parseSwitchCase() {\n          const start = expect("keyword", "case");\n          const first = parseSwitchCaseValue();\n          const values = [first.value];\n          const operators = [first.operator];\n          while (match("punctuation", ",")) {\n            const item = parseSwitchCaseValue();\n            values.push(item.value);\n            operators.push(item.operator);\n          }\n          expect("operator", ":", "Expected : after switch case");\n          const consequent = parseSwitchConsequent(start);\n          return withLoc({\n            type: "SwitchCase",\n            values,\n            operators,\n            consequent\n          }, start, endLocFromNode(consequent));\n        }\n        function parseSwitchCaseValue() {\n          const operator = parseSwitchComparator();\n          return {\n            operator,\n            value: parseExpression()\n          };\n        }\n        function parseSwitchComparator() {\n          if (!isSwitchComparatorToken(current())) {\n            return null;\n          }\n          const operator = current().value;\n          index++;\n          return operator;\n        }\n        function isSwitchComparatorToken(token) {\n          if (!token) {\n            return false;\n          }\n          if (token.type === "identifier" && token.value === "instanceof") {\n            return true;\n          }\n          if (token.type !== "operator" && token.type !== "keyword") {\n            return false;\n          }\n          return [\n            ">",\n            "<",\n            ">=",\n            "\\u2264",\n            "<=",\n            "\\u2265",\n            "=",\n            "!=",\n            "\\u2260",\n            "==",\n            "\\u2261",\n            "\\u2262",\n            "<=>",\n            "\\u2276",\n            "\\u2277",\n            "eq",\n            "ne",\n            "gt",\n            "ge",\n            "lt",\n            "le",\n            "cmp",\n            "eqi",\n            "nei",\n            "gti",\n            "gei",\n            "lti",\n            "lei",\n            "cmpi",\n            "in",\n            "\\u2208",\n            "not_in",\n            "\\u2209",\n            "subsetof",\n            "\\u2282",\n            "supersetof",\n            "\\u2283",\n            "equivalentof",\n            "\\u2282\\u2283",\n            "does",\n            "can",\n            "~",\n            "@?",\n            "\\u2223",\n            "divides",\n            "\\u2224"\n          ].includes(token.value);\n        }\n        function parseSwitchDefaultCase() {\n          const start = expect("keyword", "default");\n          expect("operator", ":", "Expected : after default");\n          const consequent = parseSwitchConsequent(start);\n          return withLoc({\n            type: "SwitchCase",\n            values: null,\n            consequent\n          }, start, endLocFromNode(consequent));\n        }\n        function parseSwitchConsequent(startToken) {\n          const body = [];\n          while (true) {\n            if (atEnd()) {\n              throw new TranspilerSyntaxError("Unterminated switch case body", current());\n            }\n            if (current().type === "punctuation" && current().value === "}") {\n              break;\n            }\n            if (current().type === "keyword" && ["case", "default"].includes(current().value)) {\n              break;\n            }\n            body.push(parseStatement());\n          }\n          return withLoc({\n            type: "BlockStatement",\n            body\n          }, startToken, previous() || startToken);\n        }\n        function parseInlineVariableDeclaration() {\n          const start = expect("keyword");\n          const declaration = parseVariableDeclarationParts(start);\n          return withLoc({\n            type: "VariableDeclaration",\n            ...declaration\n          }, start, previous());\n        }\n        function parseLoopControlStatement(type) {\n          const start = expect("keyword");\n          const stmt = withLoc({ type }, start, previous() || start);\n          return finishStatement(stmt, `Expected ; after ${start.value}`);\n        }\n        function parseThrowStatement() {\n          const start = expect("keyword", "throw");\n          const argument = parseExpression();\n          const stmt = withLoc({\n            type: "ThrowStatement",\n            argument\n          }, start, previous());\n          return finishStatement(stmt, "Expected ; after throw statement");\n        }\n        function parseDieStatement() {\n          const start = expect("keyword", "die");\n          const argument = parseExpression();\n          const stmt = withLoc({\n            type: "DieStatement",\n            argument\n          }, start, previous());\n          return finishStatement(stmt, "Expected ; after die statement");\n        }\n        function parseWarnStatement() {\n          const start = expect("keyword", "warn");\n          const argument = parseExpression();\n          const stmt = withLoc({\n            type: "WarnStatement",\n            argument\n          }, start, previous());\n          return finishStatement(stmt, "Expected ; after warn statement");\n        }\n        function parseAssertStatement() {\n          const start = expect("keyword", "assert");\n          const argument = parseExpression();\n          const stmt = withLoc({\n            type: "AssertStatement",\n            argument\n          }, start, previous());\n          return finishStatement(stmt, "Expected ; after assert statement");\n        }\n        function parseDebugStatement() {\n          const start = expect("keyword", "debug");\n          const argumentsList = [];\n          if (!(current().type === "punctuation" && current().value === ";")) {\n            argumentsList.push(parseExpression());\n            while (match("punctuation", ",")) {\n              argumentsList.push(parseExpression());\n            }\n          }\n          const stmt = withLoc({\n            type: "DebugStatement",\n            arguments: argumentsList\n          }, start, previous() || start);\n          return finishStatement(stmt, "Expected ; after debug statement");\n        }\n        function parseSayStatement() {\n          const start = expect("keyword", "say");\n          const args = [];\n          if (!(current().type === "punctuation" && current().value === ";")) {\n            args.push(parseExpression());\n            while (match("punctuation", ",")) {\n              args.push(parseExpression());\n            }\n          }\n          const stmt = withLoc({\n            type: "ExpressionStatement",\n            expression: withLoc({\n              type: "CallExpression",\n              callee: withLoc({\n                type: "Identifier",\n                name: "say"\n              }, start, start),\n              arguments: args\n            }, start, previous() || start)\n          }, start, previous() || start);\n          return finishStatement(stmt, "Expected ; after say statement");\n        }\n        function parseTryStatement() {\n          const parsed = parseTryLike();\n          return withLoc({\n            type: "TryStatement",\n            block: parsed.block,\n            handlers: parsed.handlers\n          }, parsed.start, previous());\n        }\n        function parseTryLike() {\n          const start = expect("keyword", "try");\n          const block = parseBlockStatement();\n          const handlers = [];\n          while (current().type === "keyword" && current().value === "catch") {\n            const catchTok = expect("keyword", "catch");\n            let typeName2 = "Exception";\n            let paramName = "e";\n            if (match("punctuation", "(")) {\n              if (current().type === "identifier") {\n                const first = current();\n                index++;\n                if (current().type === "identifier") {\n                  typeName2 = first.value;\n                  paramName = current().value;\n                  index++;\n                } else {\n                  paramName = first.value;\n                }\n              }\n              expect("punctuation", ")", "Expected ) after catch clause");\n            }\n            const handlerBody = parseBlockStatement();\n            handlers.push(withLoc({\n              type: "CatchClause",\n              typeName: typeName2,\n              paramName,\n              body: handlerBody\n            }, catchTok, previous()));\n          }\n          return {\n            start,\n            block,\n            handlers\n          };\n        }\n        function parseBlockStatement() {\n          const start = expect("punctuation", "{");\n          const body = [];\n          while (!(current().type === "punctuation" && current().value === "}")) {\n            if (atEnd()) {\n              throw new TranspilerSyntaxError("Unterminated block statement", current());\n            }\n            body.push(parseStatement());\n          }\n          expect("punctuation", "}");\n          return withLoc({\n            type: "BlockStatement",\n            body\n          }, start, previous());\n        }\n        function parseBlockInAsyncContext(isAsync) {\n          const previousDepth = asyncContextDepth;\n          asyncContextDepth = isAsync ? previousDepth + 1 : 0;\n          try {\n            return parseBlockStatement();\n          } finally {\n            asyncContextDepth = previousDepth;\n          }\n        }\n        function parseExpressionStatement() {\n          const start = current();\n          const expression = parseExpression();\n          const stmt = withLoc({\n            type: "ExpressionStatement",\n            expression\n          }, start, previous());\n          return finishStatement(stmt, "Expected ; after expression");\n        }\n        function finishStatement(stmt, semicolonMessage) {\n          if (current().type === "keyword" && ["if", "unless"].includes(current().value)) {\n            const keyword = current();\n            index++;\n            let test = parseExpression();\n            if (keyword.value === "unless") {\n              test = withLoc({\n                type: "UnaryExpression",\n                operator: "not",\n                argument: test,\n                prefix: true\n              }, keyword, endLocFromNode(test));\n            }\n            consumeStatementTerminator(semicolonMessage);\n            const consequent = withLoc({\n              type: "BlockStatement",\n              body: [stmt]\n            }, startLocFromNode(stmt), endLocFromNode(stmt));\n            return withLoc({\n              type: "IfStatement",\n              declaration: null,\n              test,\n              consequent,\n              alternate: null\n            }, startLocFromNode(stmt), endLocFromNode(consequent));\n          }\n          if (current().type === "keyword" && current().value === "for") {\n            const keyword = current();\n            index++;\n            const iterable = parseExpression();\n            consumeStatementTerminator(semicolonMessage);\n            const body = withLoc({\n              type: "BlockStatement",\n              body: [stmt]\n            }, startLocFromNode(stmt), endLocFromNode(stmt));\n            return withLoc({\n              type: "ForInStatement",\n              kind: "const",\n              left: {\n                type: "Identifier",\n                name: "^^"\n              },\n              iterable,\n              body,\n              elseBlock: null\n            }, startLocFromNode(stmt), endLocFromNode(iterable) || keyword);\n          }\n          consumeStatementTerminator(semicolonMessage);\n          return stmt;\n        }\n        function parseExpression() {\n          return parseAssignment();\n        }\n        function parseConditional() {\n          return parseConditionalTail(parseLogicalOr());\n        }\n        function parseConditionalTail(expr) {\n          if (match("operator", "?:")) {\n            const alternate = parseConditional();\n            return withLoc({\n              type: "ShortTernaryExpression",\n              test: expr,\n              alternate\n            }, startLocFromNode(expr), endLocFromNode(alternate));\n          }\n          if (match("operator", "?")) {\n            const consequent = parseExpression();\n            expect("operator", ":", "Expected : in ternary expression");\n            const alternate = parseConditional();\n            return withLoc({\n              type: "ConditionalExpression",\n              test: expr,\n              consequent,\n              alternate\n            }, startLocFromNode(expr), endLocFromNode(alternate));\n          }\n          return expr;\n        }\n        function parseAssignment() {\n          const left = parseChain();\n          if (current().type === "operator" && [":=", "+=", "-=", "*=", "/=", "%=", "**=", "_=", "?:=", "\\xD7=", "\\xF7="].includes(current().value)) {\n            const op = current();\n            index++;\n            const right = parseAssignment();\n            const isWeakWrite = parseOptionalWeakModifier("assignment");\n            if (isWeakWrite && op.value !== ":=") {\n              throw new TranspilerSyntaxError(\n                "but weak is only valid on \':=\' assignments",\n                op\n              );\n            }\n            if (isWeakWrite && left && left.type === "BinaryExpression" && left.operator === "@?") {\n              throw new TranspilerSyntaxError(\n                "but weak is not valid on @? path assignments",\n                op\n              );\n            }\n            return withLoc({\n              type: "AssignmentExpression",\n              operator: op.value,\n              left,\n              right,\n              isWeakWrite\n            }, startLocFromNode(left), endLocFromNode(right));\n          }\n          if (current().type === "operator" && current().value === "~=") {\n            const op = current();\n            index++;\n            const pattern = parseChain();\n            if (current().type !== "operator" || !(current().value === "->" || current().value === "\\u2192")) {\n              throw new TranspilerSyntaxError("Expected -> after regex replacement pattern", current());\n            }\n            index++;\n            const replacement = parseAssignment();\n            return withLoc({\n              type: "RegexReplaceExpression",\n              operator: op.value,\n              left,\n              pattern,\n              replacement\n            }, startLocFromNode(left), endLocFromNode(replacement));\n          }\n          return left;\n        }\n        function chainDirection(token) {\n          if (token.type !== "operator") {\n            return null;\n          }\n          if (token.value === "\\u25B7" || token.value === "|>") {\n            return "right";\n          }\n          if (token.value === "\\u25C1" || token.value === "<|") {\n            return "left";\n          }\n          return null;\n        }\n        function parseChain() {\n          let expr = parseConditional();\n          const firstDirection = chainDirection(current());\n          if (!firstDirection) {\n            return expr;\n          }\n          let op = current();\n          index++;\n          const right = firstDirection === "left" ? parseLeftwardChainRhs() : parseConditional();\n          expr = withLoc({\n            type: "BinaryExpression",\n            operator: op.value,\n            left: expr,\n            right\n          }, startLocFromNode(expr), endLocFromNode(right));\n          while (firstDirection === "right") {\n            const nextDirection = chainDirection(current());\n            if (!nextDirection) {\n              break;\n            }\n            if (nextDirection !== firstDirection) {\n              throw new TranspilerSyntaxError("Mixed chain directions require parentheses", current());\n            }\n            op = current();\n            index++;\n            const nextRight = parseConditional();\n            expr = withLoc({\n              type: "BinaryExpression",\n              operator: op.value,\n              left: expr,\n              right: nextRight\n            }, startLocFromNode(expr), endLocFromNode(nextRight));\n          }\n          if (firstDirection === "left" && chainDirection(current())) {\n            throw new TranspilerSyntaxError("Mixed chain directions require parentheses", current());\n          }\n          return expr;\n        }\n        function parseLeftwardChainRhs() {\n          const left = parseConditional();\n          const direction = chainDirection(current());\n          if (!direction) {\n            return left;\n          }\n          if (direction !== "left") {\n            throw new TranspilerSyntaxError("Mixed chain directions require parentheses", current());\n          }\n          const op = current();\n          index++;\n          const right = parseLeftwardChainRhs();\n          return withLoc({\n            type: "BinaryExpression",\n            operator: op.value,\n            left,\n            right\n          }, startLocFromNode(left), endLocFromNode(right));\n        }\n        function parseLogicalOr() {\n          return parseLeftAssociative(\n            parseOnlyif,\n            (token) => token.type === "keyword" && ["or", "or?"].includes(token.value) || token.type === "operator" && ["\\u22C1", "\\u22C1?"].includes(token.value)\n          );\n        }\n        function parseOnlyif() {\n          return parseRightAssociative(\n            parseLogicalXor,\n            (token) => token.type === "keyword" && ["onlyif", "onlyif?"].includes(token.value) || token.type === "operator" && ["\\u22A8", "\\u22A8?"].includes(token.value)\n          );\n        }\n        function parseLogicalXor() {\n          return parseLeftAssociative(\n            parseLogicalAnd,\n            (token) => token.type === "keyword" && ["xor", "xor?", "nor", "nor?", "xnor", "xnor?"].includes(token.value) || token.type === "operator" && ["\\u22BB", "\\u22BB?", "\\u22BD", "\\u22BD?", "\\u2194", "\\u2194?"].includes(token.value)\n          );\n        }\n        function parseLogicalAnd() {\n          return parseLeftAssociative(\n            parseEquality,\n            (token) => token.type === "keyword" && ["and", "and?", "nand", "nand?", "butnot", "butnot?"].includes(token.value) || token.type === "operator" && ["\\u22C0", "\\u22C0?", "\\u22BC", "\\u22BC?", "\\u22AD", "\\u22AD?"].includes(token.value)\n          );\n        }\n        function parseEquality() {\n          return parseLeftAssociative(\n            parseBitwise,\n            (token) => token.type === "operator" && ["==", "!=", "="].includes(token.value) || token.type === "operator" && ["\\u2261", "\\u2262", "\\u2260"].includes(token.value) || token.type === "keyword" && ["eq", "ne", "default"].includes(token.value)\n          );\n        }\n        function parseBitwise() {\n          return parseLeftAssociative(\n            parseShift,\n            (token) => token.type === "operator" && ["&", "|", "^"].includes(token.value)\n          );\n        }\n        function parseShift() {\n          return parseLeftAssociative(\n            parseComparison,\n            (token) => token.type === "operator" && ["<<", ">>", "\\xAB", "\\xBB"].includes(token.value) && token.value !== pendingSetClosers[pendingSetClosers.length - 1]\n          );\n        }\n        function parseComparison() {\n          return parseLeftAssociative(\n            parseRange,\n            (token) => token.type === "operator" && ["<", "<=", ">", ">=", "\\u2264", "\\u2265", "~", "<=>", "@", "@@", "@?", "\\\\", "\\u2208", "\\u2209", "\\u22C3", "\\u22C2", "\\u2216", "\\u2282", "\\u2283", "\\u2282\\u2283", "\\u2276", "\\u2277", "\\u2223", "\\u2224"].includes(token.value) || token.type === "keyword" && ["gt", "ge", "lt", "le", "cmp", "eqi", "nei", "gti", "gei", "lti", "lei", "cmpi", "in", "not_in", "union", "intersection", "difference", "subsetof", "supersetof", "equivalentof", "does", "can", "divides"].includes(token.value) || token.type === "identifier" && token.value === "instanceof"\n          );\n        }\n        function parseRange() {\n          return parseLeftAssociative(\n            parseTerm,\n            (token) => token.type === "operator" && token.value === "..."\n          );\n        }\n        function parseTerm() {\n          return parseLeftAssociative(\n            parseFactor,\n            (token) => token.type === "operator" && ["+", "-", "_"].includes(token.value)\n          );\n        }\n        function parseFactor() {\n          return parseLeftAssociative(\n            parseUnary,\n            (token) => token.type === "operator" && ["*", "/", "%", "**"].includes(token.value) || token.type === "operator" && ["\\xD7", "\\xF7"].includes(token.value) || token.type === "keyword" && token.value === "mod"\n          );\n        }\n        function parseLeftAssociative(nextFn, predicate) {\n          let expr = nextFn();\n          while (predicate(current())) {\n            const op = current();\n            index++;\n            const right = nextFn();\n            expr = withLoc({\n              type: "BinaryExpression",\n              operator: op.value,\n              left: expr,\n              right\n            }, startLocFromNode(expr), endLocFromNode(right));\n          }\n          return expr;\n        }\n        function parseRightAssociative(nextFn, predicate) {\n          const left = nextFn();\n          if (!predicate(current())) {\n            return left;\n          }\n          const op = current();\n          index++;\n          const right = parseRightAssociative(nextFn, predicate);\n          return withLoc({\n            type: "BinaryExpression",\n            operator: op.value,\n            left,\n            right\n          }, startLocFromNode(left), endLocFromNode(right));\n        }\n        function parseUnary() {\n          if (current().type === "operator" && ["-", "+", "++", "--", "!", "~", "\\\\", "\\u221A", "\\xAC"].includes(current().value) || current().type === "keyword" && ["not", "typeof", "abs", "sqrt", "floor", "ceil", "round", "int", "length", "uc", "lc"].includes(current().value)) {\n            const op = current();\n            index++;\n            const argument = op.value === "\\\\" ? parseReferenceTarget() : parseUnary();\n            let expr = withLoc({\n              type: op.value === "\\\\" ? "RefExpression" : "UnaryExpression",\n              operator: op.value,\n              argument,\n              prefix: true\n            }, startLocFromToken(op), endLocFromNode(argument));\n            if (op.value === "\\\\") {\n              expr = parsePostfixSuffixes(expr);\n            }\n            return expr;\n          }\n          return parsePostfix();\n        }\n        function parseReferenceTarget() {\n          let expr = parsePrimary();\n          while (true) {\n            const nextExpr = parseMemberAccess(expr);\n            if (nextExpr === expr) {\n              break;\n            }\n            expr = nextExpr;\n          }\n          return expr;\n        }\n        function parsePostfix() {\n          return parsePostfixSuffixes(parsePrimary());\n        }\n        function parsePostfixSuffixes(expr) {\n          while (true) {\n            const nextExpr = parseMemberAccess(expr);\n            if (nextExpr !== expr) {\n              expr = nextExpr;\n              continue;\n            }\n            if (current().type === "punctuation" && current().value === "(") {\n              const args = parseCallArgumentsOnly();\n              expr = withLoc({\n                type: "CallExpression",\n                callee: expr,\n                arguments: args\n              }, startLocFromNode(expr), endLocFromToken(previous()));\n              continue;\n            }\n            if (current().type === "operator" && ["++", "--"].includes(current().value)) {\n              const op = current();\n              index++;\n              expr = withLoc({\n                type: "UpdateExpression",\n                operator: op.value,\n                argument: expr,\n                prefix: false\n              }, startLocFromNode(expr), endLocFromToken(op));\n              continue;\n            }\n            break;\n          }\n          return expr;\n        }\n        function parseMemberAccess(expr) {\n          if (match("punctuation", ".")) {\n            if (match("punctuation", "(")) {\n              const property2 = parseExpression();\n              expect("punctuation", ")", "Expected ) after dynamic member name");\n              return withLoc({\n                type: "MemberExpression",\n                object: expr,\n                property: property2,\n                computed: true\n              }, startLocFromNode(expr), endLocFromToken(previous()));\n            }\n            const property = expectIdentifier("Expected property name after .");\n            return withLoc({\n              type: "MemberExpression",\n              object: expr,\n              property: {\n                type: "Identifier",\n                name: property.value\n              },\n              computed: false\n            }, startLocFromNode(expr), endLocFromToken(property));\n          }\n          if (match("punctuation", "[")) {\n            const closeBracket = current().type === "punctuation" && current().value === "]";\n            const startsWithColon = current().type === "operator" && current().value === ":";\n            let first = null;\n            if (!closeBracket && !startsWithColon) {\n              first = parseExpression();\n            }\n            if (match("operator", ":")) {\n              let second = null;\n              if (!(current().type === "punctuation" && current().value === "]")) {\n                second = parseExpression();\n              }\n              expect("punctuation", "]");\n              return withLoc({\n                type: "SliceExpression",\n                object: expr,\n                start: first,\n                length: second\n              }, startLocFromNode(expr), endLocFromToken(previous()));\n            }\n            if (first == null) {\n              throw new TranspilerSyntaxError("Expected index or slice expression", current());\n            }\n            expect("punctuation", "]");\n            return withLoc({\n              type: "MemberExpression",\n              object: expr,\n              property: first,\n              computed: true\n            }, startLocFromNode(expr), endLocFromToken(previous()));\n          }\n          if (match("punctuation", "{")) {\n            let property;\n            if ((current().type === "identifier" || current().type === "keyword") && peekToken().type === "punctuation" && peekToken().value === "}") {\n              const key = current();\n              index++;\n              property = withLoc(\n                key.type === "identifier" ? {\n                  type: "BraceIdentifier",\n                  name: key.value\n                } : {\n                  type: "StringLiteral",\n                  value: key.value\n                },\n                key,\n                key\n              );\n            } else {\n              property = parseExpression();\n            }\n            expect("punctuation", "}");\n            return withLoc({\n              type: "MemberExpression",\n              object: expr,\n              property,\n              computed: true\n            }, startLocFromNode(expr), endLocFromToken(previous()));\n          }\n          return expr;\n        }\n        function parseCallArgumentsOnly() {\n          expect("punctuation", "(");\n          const args = [];\n          let closed = false;\n          if (!match("punctuation", ")")) {\n            while (true) {\n              if (match("punctuation", ",")) {\n                if (current().type === "punctuation" && current().value === ")") {\n                  break;\n                }\n                continue;\n              }\n              if (current().type === "punctuation" && current().value === ")") {\n                break;\n              }\n              args.push(parseCallArgument());\n              if (match("punctuation", ")")) {\n                closed = true;\n                break;\n              }\n              match("punctuation", ",");\n            }\n            if (!closed && current().type === "punctuation" && current().value === ")") {\n              expect("punctuation", ")", "Expected ) after call arguments");\n            }\n          }\n          return args;\n        }\n        function parseCallArgument() {\n          const start = current();\n          if (match("operator", "...")) {\n            const argument = parseExpression();\n            return withLoc({\n              type: "SpreadArgument",\n              argument\n            }, start, endLocFromNode(argument));\n          }\n          if (startsNamedKeyBeforeColon()) {\n            const normalized = parseNamedKeyBeforeColon();\n            expect("operator", ":", "Expected : in named argument");\n            const value = parseExpression();\n            return withLoc({\n              type: "NamedArgument",\n              key: normalized.key,\n              keyExpr: normalized.keyExpr,\n              value\n            }, startLocFromNode(normalized.keyExpr), previous());\n          }\n          const expr = parseExpression();\n          if (current().type === "keyword" && current().value === "but") {\n            throw new TranspilerSyntaxError(\n              "but weak is not valid as a function argument marker",\n              current()\n            );\n          }\n          if (current().type === "operator" && current().value === ":") {\n            const normalized = normalizeNamedArgumentKey(expr);\n            expect("operator", ":", "Expected : in named argument");\n            const value = parseExpression();\n            return withLoc({\n              type: "NamedArgument",\n              key: normalized.key,\n              keyExpr: normalized.keyExpr,\n              value\n            }, startLocFromNode(expr), previous());\n          }\n          return expr;\n        }\n        function startsNamedKeyBeforeColon() {\n          return ["identifier", "keyword", "string"].includes(current().type) && peekToken().type === "operator" && peekToken().value === ":";\n        }\n        function parseNamedKeyBeforeColon() {\n          const token = current();\n          index++;\n          return {\n            key: token.value,\n            keyExpr: withLoc({\n              type: "StringLiteral",\n              value: token.value\n            }, token, token)\n          };\n        }\n        function normalizeNamedArgumentKey(expr) {\n          if (expr.type === "Identifier") {\n            return {\n              key: expr.name,\n              keyExpr: withLoc({\n                type: "StringLiteral",\n                value: expr.name\n              }, startLocFromNode(expr), endLocFromNode(expr))\n            };\n          }\n          if (expr.type === "StringLiteral") {\n            return {\n              key: expr.value,\n              keyExpr: expr\n            };\n          }\n          if (expr.type === "GroupedExpression") {\n            return normalizeNamedArgumentKey(expr.expression);\n          }\n          if (expr.type === "MemberExpression") {\n            if (expr.computed && expr.property.type === "StringLiteral") {\n              return {\n                key: expr.property.value,\n                keyExpr: withLoc({\n                  type: "StringLiteral",\n                  value: expr.property.value\n                }, startLocFromNode(expr.property), endLocFromNode(expr.property))\n              };\n            }\n            if (!expr.computed && expr.property.type === "Identifier") {\n              return {\n                key: expr.property.name,\n                keyExpr: withLoc({\n                  type: "StringLiteral",\n                  value: expr.property.name\n                }, startLocFromNode(expr.property), endLocFromNode(expr.property))\n              };\n            }\n          }\n          return {\n            key: null,\n            keyExpr: expr\n          };\n        }\n        function parsePrimary() {\n          const token = current();\n          if (match("number")) {\n            return withLoc({\n              type: "NumericLiteral",\n              value: Number(token.value)\n            }, token, token);\n          }\n          if (match("string")) {\n            return withLoc({\n              type: "StringLiteral",\n              value: token.value\n            }, token, token);\n          }\n          if (match("binary_string")) {\n            return withLoc({\n              type: "BinaryStringLiteral",\n              value: token.value\n            }, token, token);\n          }\n          if (match("template")) {\n            const parts = parseInterpolationParts(token.value, token);\n            return withLoc({\n              type: "TemplateLiteral",\n              parts\n            }, token, token);\n          }\n          if (match("regexp")) {\n            return withLoc({\n              type: "RegExpLiteral",\n              pattern: token.value.pattern,\n              parts: parseInterpolationParts(token.value.parts || [], token),\n              flags: token.value.flags\n            }, token, token);\n          }\n          if (token.type === "keyword" && ["true", "false", "null"].includes(token.value)) {\n            index++;\n            return withLoc({\n              type: "Literal",\n              value: token.value === "null" ? null : token.value === "true"\n            }, token, token);\n          }\n          if (token.type === "keyword" && token.value === "super") {\n            index++;\n            return withLoc({\n              type: "Super"\n            }, token, token);\n          }\n          if (match("identifier")) {\n            return withLoc({\n              type: "Identifier",\n              name: token.value\n            }, token, token);\n          }\n          if (token.type === "keyword" && token.value === "say") {\n            index++;\n            return withLoc({\n              type: "Identifier",\n              name: token.value\n            }, token, token);\n          }\n          if (token.type === "keyword" && token.value === "function") {\n            index++;\n            const params = parseParameterList();\n            const body = parseBlockInAsyncContext(false);\n            return withLoc({\n              type: "FunctionExpression",\n              params,\n              isAsync: false,\n              body\n            }, token, previous());\n          }\n          if (token.type === "keyword" && token.value === "async") {\n            index++;\n            if (current().type === "keyword" && current().value === "function") {\n              const functionToken = current();\n              index++;\n              const params = parseParameterList();\n              const body = parseBlockInAsyncContext(true);\n              return withLoc({\n                type: "FunctionExpression",\n                params,\n                isAsync: true,\n                body\n              }, token, previous() || functionToken);\n            }\n            if (current().type === "keyword" && current().value === "fn") {\n              return parseFnExpression(token, true);\n            }\n            throw new TranspilerSyntaxError("Expected function or fn after async", current());\n          }\n          if (token.type === "keyword" && token.value === "fn") {\n            return parseFnExpression(token, false);\n          }\n          if (token.type === "operator" && (token.value === "->" || token.value === "\\u2192")) {\n            return parseArrowLambdaExpression(token);\n          }\n          if (token.type === "keyword" && token.value === "await") {\n            if (asyncContextDepth <= 0) {\n              throw new TranspilerSyntaxError("await may only be used inside async code", token);\n            }\n            index++;\n            const block = parseBlockStatement();\n            return withLoc({\n              type: "AwaitExpression",\n              block\n            }, token, previous());\n          }\n          if (token.type === "keyword" && token.value === "spawn") {\n            if (asyncContextDepth <= 0) {\n              throw new TranspilerSyntaxError("spawn may only be used inside async code", token);\n            }\n            index++;\n            const block = parseBlockStatement();\n            return withLoc({\n              type: "SpawnExpression",\n              block\n            }, token, previous());\n          }\n          if (token.type === "keyword" && token.value === "try") {\n            const parsed = parseTryLike();\n            return withLoc({\n              type: "TryExpression",\n              block: parsed.block,\n              handlers: parsed.handlers\n            }, parsed.start, previous());\n          }\n          if (token.type === "keyword" && token.value === "do") {\n            index++;\n            const block = parseBlockStatement();\n            return withLoc({\n              type: "DoExpression",\n              block\n            }, token, previous());\n          }\n          if (token.type === "keyword" && token.value === "new") {\n            index++;\n            let callee = parsePrimary();\n            while (true) {\n              const nextExpr = parseMemberAccess(callee);\n              if (nextExpr === callee) {\n                break;\n              }\n              callee = nextExpr;\n            }\n            const traits = parseTraitCompositionList();\n            if (current().type === "punctuation" && current().value === "(") {\n              const args = parseCallArgumentsOnly();\n              callee = withLoc({\n                type: "CallExpression",\n                callee,\n                arguments: args\n              }, startLocFromNode(callee), endLocFromToken(previous()));\n            }\n            return withLoc({\n              type: "NewExpression",\n              callee,\n              traits\n            }, token, previous());\n          }\n          if (token.type === "keyword" && ["let", "const"].includes(token.value) && peekToken().type === "punctuation" && peekToken().value === "{") {\n            throw new TranspilerSyntaxError(\n              "Expected name after let or const in expression",\n              peekToken()\n            );\n          }\n          if (token.type === "keyword" && ["let", "const"].includes(token.value)) {\n            return parseLetExpression();\n          }\n          if (token.type === "keyword") {\n            index++;\n            return withLoc({\n              type: "Identifier",\n              name: token.value\n            }, token, token);\n          }\n          if (match("operator", "\\u230A")) {\n            return parseCircumfixUnary(token, "floor", "\\u230B", "Expected closing floor operator");\n          }\n          if (match("operator", "\\u2308")) {\n            return parseCircumfixUnary(token, "ceil", "\\u2309", "Expected closing ceil operator");\n          }\n          if (match("punctuation", "(")) {\n            const expr = parseExpression();\n            expect("punctuation", ")", "Expected ) after grouped expression");\n            return withLoc({\n              type: "GroupedExpression",\n              expression: expr\n            }, token, previous());\n          }\n          if (match("punctuation", "[")) {\n            const elements = [];\n            if (!match("punctuation", "]")) {\n              while (true) {\n                if (match("punctuation", ",")) {\n                  continue;\n                }\n                if (match("punctuation", "]")) {\n                  break;\n                }\n                elements.push(parseExpression());\n                if (match("punctuation", "]")) {\n                  break;\n                }\n                match("punctuation", ",");\n              }\n            }\n            return withLoc({\n              type: "ArrayExpression",\n              elements\n            }, token, previous());\n          }\n          if (match("operator", "{{")) {\n            const opener = previous();\n            const entries = [];\n            if (!matchPairListClose()) {\n              while (true) {\n                if (match("punctuation", ",")) {\n                  continue;\n                }\n                if (matchPairListClose()) {\n                  break;\n                }\n                const start = current();\n                const literalKey = startsNamedKeyBeforeColon() ? parseNamedKeyBeforeColon() : null;\n                const keyExpr = literalKey ? literalKey.keyExpr : parseExpression();\n                if (current().type === "operator" && current().value === ":") {\n                  const normalized = literalKey || normalizeNamedArgumentKey(keyExpr);\n                  expect("operator", ":", "Expected : in pairlist literal");\n                  const value = parseExpression();\n                  entries.push(withLoc({\n                    type: "PairListEntry",\n                    key: normalized.key,\n                    keyExpr: normalized.keyExpr,\n                    value\n                  }, startLocFromNode(keyExpr), endLocFromNode(value)));\n                } else {\n                  entries.push(keyExpr);\n                }\n                if (matchPairListClose()) {\n                  break;\n                }\n                match("punctuation", ",");\n              }\n            }\n            return withLoc({\n              type: "PairListLiteral",\n              entries\n            }, opener, previous());\n          }\n          if (match("operator", "<<") || match("operator", "<<<") || match("operator", "\\xAB")) {\n            const opener = previous();\n            const closer = opener.value === "<<<" ? ">>>" : opener.value === "\\xAB" ? "\\xBB" : ">>";\n            const elements = parseDelimitedCollection(closer);\n            return withLoc({\n              type: opener.value === "<<<" ? "BagLiteral" : "SetLiteral",\n              elements\n            }, opener, previous());\n          }\n          if (match("punctuation", "{")) {\n            const properties = [];\n            if (!match("punctuation", "}")) {\n              while (true) {\n                if (match("punctuation", ",")) {\n                  continue;\n                }\n                if (match("punctuation", "}")) {\n                  break;\n                }\n                let key;\n                if (current().type === "identifier" || current().type === "keyword") {\n                  key = current().value;\n                  index++;\n                } else if (current().type === "string") {\n                  key = current().value;\n                  index++;\n                } else {\n                  throw new TranspilerSyntaxError("Expected object literal key", current());\n                }\n                expect("operator", ":", "Expected : in object literal");\n                const value = parseExpression();\n                properties.push({ key, value });\n                if (match("punctuation", "}")) {\n                  break;\n                }\n                match("punctuation", ",");\n              }\n            }\n            return withLoc({\n              type: "ObjectExpression",\n              properties\n            }, token, previous());\n          }\n          throw new TranspilerSyntaxError("Unexpected token in expression", token);\n        }\n        function parseFnExpression(token, isAsync) {\n          index++;\n          let params;\n          if (current().type === "punctuation" && current().value === "(") {\n            params = parseParameterList();\n          } else {\n            params = [parseParameter()];\n          }\n          if (current().type === "operator" && (current().value === "->" || current().value === "\\u2192")) {\n            index++;\n          } else {\n            throw new TranspilerSyntaxError("Expected -> after fn parameters", current());\n          }\n          const previousDepth = asyncContextDepth;\n          asyncContextDepth = isAsync ? previousDepth + 1 : 0;\n          let expr;\n          try {\n            expr = parseExpression();\n          } finally {\n            asyncContextDepth = previousDepth;\n          }\n          const returnStmt = withLoc({\n            type: "ReturnStatement",\n            argument: expr\n          }, token, token);\n          const body = withLoc({\n            type: "BlockStatement",\n            body: [returnStmt]\n          }, token, token);\n          return withLoc({\n            type: "FunctionExpression",\n            params,\n            isAsync,\n            body\n          }, token, previous() || token);\n        }\n        function parseArrowLambdaExpression(token) {\n          index++;\n          const expr = parseExpression();\n          const returnStmt = withLoc({\n            type: "ReturnStatement",\n            argument: expr\n          }, token, token);\n          const body = withLoc({\n            type: "BlockStatement",\n            body: [returnStmt]\n          }, token, token);\n          return withLoc({\n            type: "FunctionExpression",\n            params: [{\n              type: "Parameter",\n              name: "^^",\n              typeName: null,\n              optional: true,\n              defaultValue: null,\n              rest: false\n            }],\n            isAsync: false,\n            body\n          }, token, previous() || token);\n        }\n        function parseDelimitedCollection(closer) {\n          const elements = [];\n          if (match("operator", closer)) {\n            return elements;\n          }\n          pendingSetClosers.push(closer);\n          try {\n            while (true) {\n              if (match("punctuation", ",")) {\n                continue;\n              }\n              if (match("operator", closer)) {\n                break;\n              }\n              elements.push(parseExpression());\n              if (match("operator", closer)) {\n                break;\n              }\n              match("punctuation", ",");\n            }\n          } finally {\n            pendingSetClosers.pop();\n          }\n          return elements;\n        }\n        function parseLetExpression() {\n          const start = expect("keyword");\n          if (current().type === "punctuation" && current().value === "{") {\n            throw new TranspilerSyntaxError(\n              "Expected name after let or const in expression",\n              current()\n            );\n          }\n          return withLoc({\n            type: "LetExpression",\n            ...parseVariableDeclarationParts(start)\n          }, start, previous());\n        }\n        function parseCircumfixUnary(start, operator, close, message) {\n          const argument = parseExpression();\n          expect("operator", close, message);\n          return withLoc({\n            type: "UnaryExpression",\n            operator,\n            argument,\n            prefix: true\n          }, start, previous());\n        }\n        function parseTemplateExpression(source, token) {\n          try {\n            return parse(tokenize(source), { expression: true });\n          } catch (err) {\n            if (err instanceof TranspilerSyntaxError || err instanceof UnsupportedSyntaxError) {\n              throw new TranspilerSyntaxError("Invalid template interpolation", token);\n            }\n            throw err;\n          }\n        }\n        function parseInterpolationParts(parts, token) {\n          return parts.map((part) => {\n            if (part.type === "text") {\n              return withLoc({\n                type: "StringLiteral",\n                value: part.value\n              }, token, token);\n            }\n            return parseTemplateExpression(part.value, token);\n          });\n        }\n        if (options.expression) {\n          return parseExpressionRoot();\n        }\n        return parseProgram();\n      }\n      module2.exports = {\n        parse\n      };\n    }\n  });\n\n  // lib/transpiler-new/codegen.js\n  var require_codegen = __commonJS({\n    "lib/transpiler-new/codegen.js"(exports2, module2) {\n      "use strict";\n      var { UnsupportedSyntaxError } = require_errors();\n      var loopCounter = 0;\n      var chainCounter = 0;\n      var emitContextStack = [];\n      function currentEmitContext() {\n        return emitContextStack.length > 0 ? emitContextStack[emitContextStack.length - 1] : {};\n      }\n      function withEmitContext(options, fn2) {\n        emitContextStack.push(options || {});\n        try {\n          return fn2();\n        } finally {\n          emitContextStack.pop();\n        }\n      }\n      function emitProgram(ast, options = {}) {\n        loopCounter = 0;\n        chainCounter = 0;\n        const syncEval = options.syncEval === true;\n        const needsAsyncWrapper = programNeedsAsyncWrapper(ast) || options.asyncImports === true && !syncEval && programContainsImport(ast);\n        const expressionDeclaredNames = collectExpressionDeclaredNames(ast.body);\n        const sharedOptions = {\n          ...options,\n          asyncContext: needsAsyncWrapper && !syncEval,\n          asyncNames: new Set(collectAsyncFunctionNames(ast.body)),\n          evalNames: /* @__PURE__ */ new Set(["eval", ...collectEvalImportNames(ast.body)]),\n          weakStorageNames: new Set(collectWeakDeclaredNames(ast.body)),\n          scopeNames: /* @__PURE__ */ new Set([\n            ...expressionDeclaredNames\n          ]),\n          bodylessFunctionNames: /* @__PURE__ */ new Set(),\n          syncEval,\n          topLevel: !syncEval\n        };\n        if (syncEval) {\n          return `( () => {\n${emitExpressionBlock({ body: ast.body }, sharedOptions)}\n} )()`;\n        }\n        const body = ast.body.map((stmt) => emitStatement(stmt, {\n          ...sharedOptions,\n          topLevel: true\n        })).join("\\n");\n        const prelude = emitPredeclaredNames(expressionDeclaredNames);\n        const source = [prelude, body].filter(Boolean).join("\\n");\n        if (needsAsyncWrapper && !syncEval && options.deferAsyncWrapper !== true) {\n          return `( async () => {\n${source}\n} )()`;\n        }\n        return source;\n      }\n      function marshalSourceSlice(node, options = currentEmitContext()) {\n        if (!options.marshalSource || !node.loc || !node.loc.start || !node.loc.end) {\n          return null;\n        }\n        return options.marshalSource.slice(node.loc.start.offset, node.loc.end.offset);\n      }\n      function marshalFunctionSource(node, options = currentEmitContext()) {\n        const source = marshalSourceSlice(node, options);\n        if (!source) {\n          return null;\n        }\n        return source.replace(/^\\s*async\\s+function\\s+[A-Za-z_][A-Za-z0-9_]*/u, "async function").replace(/^\\s*function\\s+[A-Za-z_][A-Za-z0-9_]*/u, "function");\n      }\n      function marshalCaptureNames(node, options = currentEmitContext()) {\n        const names = /* @__PURE__ */ new Set();\n        const declared = new Set([\n          ...options.scopeNames || [],\n          ...extractDeclaredParamNames(node.params || []),\n          node.id && node.id.name,\n          "self",\n          "true",\n          "false",\n          "null",\n          "__argc__",\n          "__file__",\n          "__global__",\n          "__system__",\n          ...options.evalNames || []\n        ].filter(Boolean));\n        const localKinds = /* @__PURE__ */ new Set([\n          "FunctionDeclaration",\n          "VariableDeclaration",\n          "ClassDeclaration",\n          "TraitDeclaration"\n        ]);\n        function visit(value, parent = null) {\n          if (!value || typeof value !== "object") {\n            return;\n          }\n          if (Array.isArray(value)) {\n            for (const item of value) {\n              visit(item, parent);\n            }\n            return;\n          }\n          if (value.type === "Identifier") {\n            if (parent && (parent.type === "MemberExpression" && parent.property === value && !parent.computed || parent.type === "FieldDeclaration" && parent.id === value || parent.type === "MethodDeclaration" && parent.id === value)) {\n              return;\n            }\n            if (!declared.has(value.name)) {\n              names.add(value.name);\n            }\n            return;\n          }\n          if (value.type === "TryStatement") {\n            visit(value.block, value);\n            for (const handler of value.handlers || []) {\n              const paramName = handler.paramName;\n              const hadParam = paramName ? declared.has(paramName) : false;\n              if (paramName) {\n                declared.add(paramName);\n              }\n              visit(handler.body, handler);\n              if (paramName && !hadParam) {\n                declared.delete(paramName);\n              }\n            }\n            return;\n          }\n          if (value.type === "VariableUnpackDeclaration") {\n            visit(value.init, value);\n            for (const entry of bindingEntriesForPattern(value.pattern)) {\n              visit(entry.key, entry);\n              visit(entry.defaultValue, entry);\n            }\n            for (const name2 of declaredNamesForStatement(value)) {\n              declared.add(name2);\n            }\n            return;\n          }\n          if (localKinds.has(value.type)) {\n            for (const name2 of declaredNamesForStatement(value)) {\n              declared.add(name2);\n            }\n          }\n          for (const [key, child] of Object.entries(value)) {\n            if (key === "loc") {\n              continue;\n            }\n            visit(child, value);\n          }\n        }\n        visit(node.body || node);\n        return [...names].filter((name2) => /^[A-Za-z_][A-Za-z0-9_]*$/u.test(name2));\n      }\n      function marshalMetaExpression(kind, name2, source, captureNames = []) {\n        return `{ kind: ${JSON.stringify(kind)}, name: ${JSON.stringify(name2 || null)}, source: ${JSON.stringify(source || "")}, captures: ${marshalCapturesExpression(captureNames)} }`;\n      }\n      function marshalCapturesExpression(captureNames = []) {\n        const captures = captureNames.map((capture) => `${JSON.stringify(capture)}: typeof ${capture} !== "undefined" ? ${capture} : null`).join(", ");\n        return `{ ${captures} }`;\n      }\n      function marshalClassCaptureNames(node, options = currentEmitContext()) {\n        const names = new Set(marshalCaptureNames(node, options));\n        for (const trait of node.traits || []) {\n          if (trait && trait.type === "Identifier") {\n            names.add(trait.name);\n          }\n        }\n        for (const field of node.body.filter((entry) => entry.type === "FieldDeclaration")) {\n          names.delete(field.id.name);\n        }\n        for (const entry of node.body) {\n          if (entry.id && entry.id.name) {\n            names.delete(entry.id.name);\n          }\n          if (entry.type === "MethodDeclaration") {\n            for (const param of extractDeclaredParamNames(entry.params || [])) {\n              names.delete(param);\n            }\n          }\n        }\n        return [...names];\n      }\n      function marshalTraitCaptureNames(node, options = currentEmitContext()) {\n        const names = new Set(marshalCaptureNames(node, options));\n        for (const method of node.body || []) {\n          if (method.id && method.id.name) {\n            names.delete(method.id.name);\n          }\n          for (const param of extractDeclaredParamNames(method.params || [])) {\n            names.delete(param);\n          }\n        }\n        return [...names];\n      }\n      function nestedFunctionOptions(options = {}) {\n        return {\n          marshalSource: options.marshalSource,\n          syncEval: options.syncEval,\n          asyncContext: options.asyncContext,\n          asyncNames: options.asyncNames,\n          evalNames: options.evalNames,\n          weakStorageNames: options.weakStorageNames,\n          scopeNames: options.scopeNames,\n          bodylessFunctionNames: options.bodylessFunctionNames,\n          chainHereName: options.chainHereName\n        };\n      }\n      function emitStatement(node, options = {}) {\n        return withEmitContext(options, () => {\n          if (node.exported) {\n            return emitExportedStatement(node, options);\n          }\n          switch (node.type) {\n            case "EmptyStatement":\n              return ";";\n            case "ImportDeclaration":\n              return emitImportDeclaration(node, options);\n            case "VariableDeclaration": {\n              const value = emitVariableDeclarationValue(node);\n              return `${node.kind} ${emitExpression(node.id)} = ${value};`;\n            }\n            case "VariableUnpackDeclaration":\n              return emitVariableUnpackDeclaration(node, options);\n            case "FunctionDeclaration": {\n              const name2 = emitExpression(node.id);\n              if (node.isPredeclared) {\n                if (options.bodylessFunctionNames) {\n                  options.bodylessFunctionNames.add(node.id.name);\n                }\n                const declaration2 = `let ${name2} = __zuzu_bodyless_function( ${JSON.stringify(node.id.name)} );`;\n                return options.topLevel ? `${declaration2}\nglobalThis[${JSON.stringify(node.id.name)}] = ${name2};` : declaration2;\n              }\n              const fn2 = emitFunctionLike(node, `${node.isAsync ? "async " : ""}function ${name2}()`, {\n                ...nestedFunctionOptions(options),\n                returnTypeName: node.returnType,\n                callableName: node.id.name,\n                asyncContext: node.isAsync === true,\n                syncEval: options.syncEval === true\n              });\n              const meta = marshalMetaExpression(\n                "function",\n                node.id.name,\n                marshalFunctionSource(node, options),\n                marshalCaptureNames(node, options)\n              );\n              if (options.bodylessFunctionNames && options.bodylessFunctionNames.has(node.id.name)) {\n                options.bodylessFunctionNames.delete(node.id.name);\n                return `${name2} = __zuzu_complete_function( ${name2}, ${fn2}, ${meta} );`;\n              }\n              const declaration = `const ${name2} = __zuzu_with_marshal_meta( ${fn2}, ${meta} );`;\n              return options.topLevel ? `${declaration}\nglobalThis[${JSON.stringify(node.id.name)}] = ${name2};` : declaration;\n            }\n            case "ReturnStatement": {\n              if (node.argument == null && !options.returnTypeName) {\n                return options.inSwitchSection ? "return { __zuzu_return: true, value: undefined };" : "return;";\n              }\n              const value = node.argument ? emitReturnValue(node.argument, options) : emitReturnValue(null, options);\n              if (options.inSwitchSection) {\n                return `return { __zuzu_return: true, value: ${value} };`;\n              }\n              if (options.returnSlotName) {\n                return `return (${options.returnSlotName} = ${value});`;\n              }\n              return node.argument ? `return ${value};` : `return ${value};`;\n            }\n            case "IfStatement":\n              return [\n                node.declaration ? emitStatement(node.declaration, options) : "",\n                `if ( __zuzu_truthy( ${emitExpression(node.test)} ) ) ${emitBlock(node.consequent, options)}`,\n                node.alternate ? `else ${node.alternate.type === "BlockStatement" ? emitBlock(node.alternate, options) : emitStatement(node.alternate, options)}` : ""\n              ].filter(Boolean).join(" ");\n            case "BlockStatement":\n              return emitBlock(node, options);\n            case "ExpressionStatement":\n              return `${emitExpression(node.expression)};`;\n            case "ForInStatement":\n              return emitForInStatement(node, options);\n            case "WhileStatement":\n              return [\n                node.declaration ? emitStatement(node.declaration, options) : "",\n                `while ( __zuzu_truthy( ${emitExpression(node.test)} ) ) ${emitBlock(node.body, {\n                  ...options,\n                  loopDepth: (options.loopDepth || 0) + 1\n                })}`\n              ].filter(Boolean).join("\\n");\n            case "ContinueStatement":\n              if (options.inSwitchSection && (options.loopDepth || 0) === 0) {\n                return "return true;";\n              }\n              return "continue;";\n            case "BreakStatement":\n              return "break;";\n            case "ThrowStatement":\n              return `__zuzu_throw( ${emitExpression(node.argument)}, ${JSON.stringify(node.loc.start.line)} );`;\n            case "DieStatement":\n              return `__zuzu_die( ${emitExpression(node.argument)} );`;\n            case "WarnStatement":\n              return `__zuzu_warn( ${emitExpression(node.argument)} );`;\n            case "AssertStatement":\n              return `__zuzu_assert( () => ${emitExpression(node.argument)} );`;\n            case "DebugStatement":\n              return emitDebugStatement(node);\n            case "TryStatement":\n              return emitTryStatement(node, options);\n            case "SwitchStatement":\n              return emitSwitchStatement(node, options);\n            case "ClassDeclaration":\n              return emitClassDeclaration(node, options);\n            case "TraitDeclaration":\n              return emitTraitDeclaration(node, options);\n            default:\n              throw new UnsupportedSyntaxError(`Unsupported statement node ${node.type}`);\n          }\n        });\n      }\n      function emitExportedStatement(node, options = {}) {\n        if (node.type === "VariableUnpackDeclaration") {\n          const unexported2 = {\n            ...node,\n            exported: false\n          };\n          return [\n            emitStatement(unexported2, options),\n            ...declaredNamesForStatement(node).map((name3) => `module.exports[${JSON.stringify(name3)}] = ${name3};`)\n          ].join("\\n");\n        }\n        if (!node.id || !node.id.name) {\n          throw new UnsupportedSyntaxError(`Cannot export statement node ${node.type}`);\n        }\n        const unexported = {\n          ...node,\n          exported: false\n        };\n        const name2 = node.id.name;\n        return [\n          emitStatement(unexported, options),\n          `module.exports[${JSON.stringify(name2)}] = ${name2};`\n        ].join("\\n");\n      }\n      function emitDebugStatement(node) {\n        const args = node.arguments || [];\n        const level = args[0] ? emitExpression(args[0]) : "0";\n        const message = args[1] ? emitExpression(args[1]) : \'""\';\n        return `__zuzu_debug( () => ${level}, () => ${message} );`;\n      }\n      function emitFunctionLike(node, header, options = {}) {\n        const signature = analyzeSpecialSignature(node.params);\n        const cleanupNames = collectCleanupNames(node.body);\n        const returnSlotName = cleanupNames.length > 0 ? "__zuzu_returning" : null;\n        const functionOptions = {\n          ...createFunctionOptions(node, options),\n          returnSlotName\n        };\n        const bodySource = withEmitContext(\n          functionOptions,\n          () => emitFunctionBlock(node.body, cleanupNames, functionOptions)\n        );\n        const cleanup = cleanupNames.map((name2) => `__zuzu_maybe_demolish( ${name2}, ${returnSlotName} );`).join("\\n");\n        const bodyWrapper = [\n          returnSlotName ? `let ${returnSlotName} = null;` : "",\n          "try {",\n          bodySource,\n          "} catch ( __zuzu_nonlocal ) {",\n          returnSlotName ? `if ( __zuzu_nonlocal && __zuzu_nonlocal.__zuzu_nonlocal_return ) { ${returnSlotName} = __zuzu_nonlocal.value; return ${returnSlotName}; }` : "if ( __zuzu_nonlocal && __zuzu_nonlocal.__zuzu_nonlocal_return ) { return __zuzu_nonlocal.value; }",\n          "throw __zuzu_nonlocal;",\n          "}",\n          cleanupNames.length > 0 ? "finally {" : "",\n          cleanupNames.length > 0 ? cleanup : "",\n          cleanupNames.length > 0 ? "}" : ""\n        ].filter(Boolean).join("\\n");\n        if (node.isAsync === true) {\n          const taskName = options.callableName || (node.id ? node.id.name : null) || "<async>";\n          const line = node.loc && node.loc.start ? node.loc.start.line : null;\n          const syncHeader = header.replace(/^async\\s+/u, "");\n          const taskHelper = options.syncEval ? "__zuzu_task_sync" : "__zuzu_task";\n          const executorPrefix = options.syncEval ? "()" : "async ()";\n          return [\n            `${syncHeader} {`,\n            `return ${taskHelper}( ${executorPrefix} => {`,\n            emitFunctionPreamble(node.params, signature),\n            options.extraPreamble || "",\n            ...cleanupNames.map((name2) => `let ${name2} = null;`),\n            bodyWrapper,\n            `}, { name: ${JSON.stringify(taskName)}, line: ${JSON.stringify(line)} } );`,\n            "}"\n          ].filter(Boolean).join("\\n");\n        }\n        return [\n          `${header} {`,\n          emitFunctionPreamble(node.params, signature),\n          options.extraPreamble || "",\n          ...cleanupNames.map((name2) => `let ${name2} = null;`),\n          bodyWrapper,\n          "}"\n        ].filter(Boolean).join("\\n");\n      }\n      function emitFunctionBodyStatement(node, cleanupNames, options = {}) {\n        if (node.type === "VariableDeclaration" && node.id && cleanupNames.includes(node.id.name)) {\n          return `${emitExpression(node.id)} = ${emitVariableDeclarationValue(node)};`;\n        }\n        if (node.type === "VariableUnpackDeclaration" && bindingEntriesForPattern(node.pattern).some((entry) => cleanupNames.includes(entry.name))) {\n          return emitVariableUnpackAssignments(node);\n        }\n        return emitStatement(node, options);\n      }\n      function emitFunctionBlock(block, cleanupNames, options = {}) {\n        if (!block || !Array.isArray(block.body) || block.body.length === 0) {\n          return "";\n        }\n        return emitFunctionStatements(block.body, cleanupNames, options);\n      }\n      function emitFunctionStatements(statements, cleanupNames, options = {}) {\n        const lines = [];\n        const lastIndex = statements.length - 1;\n        for (let i = 0; i < statements.length; i++) {\n          const stmt = statements[i];\n          if (stmt.type === "VariableUnpackDeclaration") {\n            const unpack = emitVariableUnpackParts(stmt);\n            const rest = emitFunctionStatements(\n              statements.slice(i + 1),\n              cleanupNames,\n              {\n                ...options,\n                scopeNames: /* @__PURE__ */ new Set([\n                  ...options.scopeNames || [],\n                  ...declaredNamesForStatement(stmt)\n                ])\n              }\n            );\n            lines.push(...unpack.prelude);\n            lines.push("{");\n            lines.push(...unpack.declarations);\n            lines.push(emitUnpackScopedRest(stmt, rest));\n            lines.push("}");\n            return lines.filter((line) => line !== "").join("\\n");\n          }\n          if (i === lastIndex) {\n            lines.push(emitFunctionTailStatement(stmt, cleanupNames, options));\n          } else {\n            lines.push(emitFunctionBodyStatement(stmt, cleanupNames, options));\n          }\n        }\n        return lines.join("\\n");\n      }\n      function emitFunctionTailStatement(stmt, cleanupNames, options = {}) {\n        if (stmt.type === "ExpressionStatement") {\n          return `return ${emitExpression(stmt.expression)};`;\n        }\n        if (stmt.type === "BlockStatement") {\n          return emitBlock(stmt, options);\n        }\n        if (stmt.type === "IfStatement") {\n          const prefix = stmt.declaration ? `${emitStatement(stmt.declaration, options)}\n` : "";\n          const alternate = stmt.alternate ? emitFunctionTailStatement(stmt.alternate, cleanupNames, options) : "return null;";\n          return `${prefix}if ( __zuzu_truthy( ${emitExpression(stmt.test, options)} ) ) { ${emitFunctionBlock(stmt.consequent, cleanupNames, options)} } else { ${alternate} }`;\n        }\n        return emitFunctionBodyStatement(stmt, cleanupNames, options);\n      }\n      function collectCleanupNames(block) {\n        const names = [];\n        for (const stmt of block.body) {\n          if (["VariableDeclaration", "ClassDeclaration", "TraitDeclaration"].includes(stmt.type)) {\n            for (const name2 of declaredNamesForStatement(stmt)) {\n              if (name2 !== "self") {\n                names.push(name2);\n              }\n            }\n          }\n        }\n        names.push(...collectExpressionDeclaredNames(block.body));\n        return [...new Set(names)];\n      }\n      function collectWeakDeclaredNames(statements = []) {\n        const names = [];\n        for (const stmt of statements || []) {\n          if (stmt.type === "VariableDeclaration" && stmt.isWeakStorage && stmt.id && stmt.id.name) {\n            names.push(stmt.id.name);\n          } else if (stmt.type === "VariableUnpackDeclaration") {\n            for (const entry of bindingEntriesForPattern(stmt.pattern)) {\n              if (entry.isWeakStorage && entry.name) {\n                names.push(entry.name);\n              }\n            }\n          }\n        }\n        names.push(...collectExpressionDeclaredEntries(statements).filter((entry) => entry.isWeakStorage).map((entry) => entry.name));\n        return [...new Set(names)];\n      }\n      function createFunctionOptions(node, options = {}) {\n        const signature = analyzeSpecialSignature(node.params);\n        const paramNames = extractDeclaredParamNames(node.params);\n        const body = node.body ? node.body.body : [];\n        const expressionDeclaredNames = collectExpressionDeclaredNames(body);\n        const hereParamName = (node.params || []).some((param) => param.type === "Parameter" && param.name === "^^") ? "__zuzu_here" : null;\n        return {\n          ...options,\n          returnTypeName: options.returnTypeName || node.returnType || null,\n          callableName: options.callableName || (node.id ? node.id.name : null),\n          asyncContext: node.isAsync === true || options.asyncContext === true,\n          asyncNames: /* @__PURE__ */ new Set([...options.asyncNames || [], ...collectAsyncFunctionNames(body)]),\n          weakStorageNames: /* @__PURE__ */ new Set([\n            ...options.weakStorageNames || [],\n            ...collectWeakDeclaredNames(body)\n          ]),\n          scopeNames: /* @__PURE__ */ new Set([\n            ...options.scopeNames || [],\n            ...paramNames,\n            ...hereParamName ? [hereParamName] : [],\n            ...extractSpecialPreludeNames(signature),\n            ...expressionDeclaredNames\n          ]),\n          bodylessFunctionNames: /* @__PURE__ */ new Set(),\n          chainHereName: hereParamName || options.chainHereName,\n          returnSlotName: null\n        };\n      }\n      function extractDeclaredParamNames(params) {\n        const names = [];\n        for (const param of params) {\n          if (param.type === "Parameter") {\n            names.push(param.name);\n          } else if (param.type === "SpecialParameter") {\n            if (param.leadName) {\n              names.push(param.leadName);\n            }\n            names.push(param.name);\n          }\n        }\n        return names;\n      }\n      function extractSpecialPreludeNames(signature) {\n        if (!signature) {\n          return [];\n        }\n        switch (signature.kind) {\n          case "pairlist_only":\n            return ["__zuzu_call_args", signature.namedName];\n          case "pairlist_rest_array":\n          case "rest_array_pairlist":\n            return ["__zuzu_call_args", signature.namedName, signature.restName, "__a"];\n          case "lead_pairlist":\n            return ["__zuzu_call_args", signature.headName, signature.namedName, signature.restName, "__i", "__a"];\n          case "trail_pairlist":\n            return ["__zuzu_call_args", signature.headName, signature.restName, signature.namedName, "__i", "__a"];\n          case "scalar_pairlist":\n            return ["__zuzu_call_args", signature.headName, signature.namedName, "__i", "__a"];\n          case "scalar_pairlist_array":\n            return ["__zuzu_call_args", signature.headName, signature.namedName, signature.restName, "__i", "__a"];\n          case "variadic":\n            return ["__zuzu_call_args", signature.headName, signature.restName, "__i", "__a"];\n          default:\n            return [];\n        }\n      }\n      function analyzeSpecialSignature(params) {\n        if (params.length === 1 && params[0].type === "SpecialParameter" && params[0].special === "rest_only" && params[0].containerType === "PairList") {\n          return {\n            kind: "pairlist_only",\n            namedName: params[0].name\n          };\n        }\n        if (params.length === 2 && params[0].type === "SpecialParameter" && params[0].special === "rest_only" && params[0].containerType === "Array" && params[1].type === "Parameter" && params[1].typeName === "PairList") {\n          return {\n            kind: "rest_array_pairlist",\n            restName: params[0].name,\n            namedName: params[1].name\n          };\n        }\n        if (params.length === 2 && params[0].type === "SpecialParameter" && params[0].special === "rest_only" && params[0].containerType === "PairList" && params[1].type === "Parameter" && (params[1].typeName === "Array" || params[1].typeName == null)) {\n          return {\n            kind: "pairlist_rest_array",\n            namedName: params[0].name,\n            restName: params[1].name\n          };\n        }\n        if (params.length === 2 && params[0].type === "SpecialParameter" && params[0].special === "lead_rest" && params[0].containerType === "PairList" && params[1].type === "Parameter" && (params[1].typeName === "Array" || params[1].typeName == null)) {\n          return {\n            kind: "lead_pairlist",\n            headName: params[0].leadName,\n            namedName: params[0].name,\n            restName: params[1].name\n          };\n        }\n        if (params.length === 2 && params[0].type === "SpecialParameter" && params[0].special === "lead_rest" && params[0].containerType === "Array" && params[1].type === "Parameter" && params[1].typeName === "PairList") {\n          return {\n            kind: "trail_pairlist",\n            headName: params[0].leadName,\n            restName: params[0].name,\n            namedName: params[1].name\n          };\n        }\n        if (params.length === 2 && params[0].type === "Parameter" && params[1].type === "SpecialParameter" && params[1].special === "rest_only" && params[1].containerType === "PairList") {\n          return {\n            kind: "scalar_pairlist",\n            headName: params[0].name,\n            namedName: params[1].name\n          };\n        }\n        if (params.length === 3 && params[0].type === "Parameter" && params[1].type === "SpecialParameter" && params[1].special === "rest_only" && params[1].containerType === "PairList" && params[2].type === "Parameter" && (params[2].typeName === "Array" || params[2].typeName == null)) {\n          return {\n            kind: "scalar_pairlist_array",\n            headName: params[0].name,\n            namedName: params[1].name,\n            restName: params[2].name\n          };\n        }\n        if (params.length === 1 && params[0].type === "SpecialParameter" && params[0].special === "lead_rest" && params[0].containerType === "Array") {\n          return {\n            kind: "variadic",\n            headName: params[0].leadName,\n            restName: params[0].name\n          };\n        }\n        return null;\n      }\n      function emitFunctionPreamble(params, signature = null) {\n        if (signature) {\n          return emitSpecialFunctionPreamble(signature);\n        }\n        const lines = [];\n        const required = params.reduce((count, param) => {\n          if (param.type === "Parameter") {\n            return count + (!param.optional && param.defaultValue == null && !param.rest ? 1 : 0);\n          }\n          if (param.type === "SpecialParameter" && param.special === "lead_rest") {\n            return count + 1;\n          }\n          return count;\n        }, 0);\n        lines.push("const __argc__ = arguments.length;");\n        lines.push(`if ( arguments.length < ${required} ) { throw new Error( "Wrong number of arguments" ); }`);\n        let argIndex = 0;\n        for (const param of params) {\n          if (param.type === "SpecialParameter") {\n            if (param.special === "lead_rest") {\n              lines.push(`const ${param.leadName} = arguments[${argIndex}];`);\n              argIndex++;\n              lines.push(`const ${param.name} = Array.prototype.slice.call( arguments, ${argIndex} );`);\n              continue;\n            }\n            if (param.special === "rest_only") {\n              if (param.containerType === "PairList") {\n                lines.push(`let ${param.name} = __zuzu_pairlist_literal( [] );`);\n                lines.push(`for ( let __i = ${argIndex}; __i < arguments.length; __i++ ) {`);\n                lines.push("const __a = arguments[__i];");\n                lines.push(`if ( __zuzu_is_pairlist( __a ) ) { ${param.name} = __a; } else { throw new Exception( "named PairList parameter only accepts named arguments" ); }`);\n                lines.push("}");\n              } else {\n                lines.push(`const ${param.name} = Array.prototype.slice.call( arguments, ${argIndex} );`);\n              }\n              continue;\n            }\n          }\n          if (param.type !== "Parameter") {\n            continue;\n          }\n          const paramName = param.name === "^^" ? "__zuzu_here" : param.name;\n          if (param.rest) {\n            lines.push(`const ${paramName} = Array.prototype.slice.call( arguments, ${argIndex} );`);\n            continue;\n          }\n          if (param.defaultValue) {\n            lines.push(`const ${paramName} = __argc__ > ${argIndex} ? arguments[${argIndex}] : ${emitExpression(param.defaultValue)};`);\n          } else if (param.optional) {\n            lines.push(`const ${paramName} = __argc__ > ${argIndex} ? arguments[${argIndex}] : null;`);\n          } else {\n            lines.push(`const ${paramName} = arguments[${argIndex}];`);\n          }\n          if (param.typeName) {\n            lines.push(\n              `if ( ${paramName} != null && !__zuzu_type_matches( ${paramName}, ${JSON.stringify(param.typeName)} ) ) { throw new Error( \\`TypeException: \'${param.name}\' must be ${param.typeName}, got \\${ __zuzu_typeof( ${paramName} ) }\\` ); }`\n            );\n          }\n          argIndex++;\n        }\n        return lines.join("\\n");\n      }\n      function emitSpecialFunctionPreamble(signature) {\n        switch (signature.kind) {\n          case "pairlist_only":\n            return [\n              `const __zuzu_call_args = Array.prototype.slice.call( arguments );`,\n              "let __zuzu_named_args = __zuzu_pairlist_literal( [] );",\n              "for ( const __a of __zuzu_call_args ) {",\n              \'if ( __zuzu_is_pairlist( __a ) ) { __zuzu_named_args = __a; } else { throw new Exception( "named PairList parameter only accepts named arguments" ); }\',\n              "}",\n              `const ${signature.namedName} = __zuzu_named_args;`\n            ].join("\\n");\n          case "pairlist_rest_array":\n          case "rest_array_pairlist":\n            return [\n              `const __zuzu_call_args = Array.prototype.slice.call( arguments );`,\n              "let __zuzu_named_args = __zuzu_pairlist_literal( [] );",\n              "const __zuzu_rest_args = [];",\n              "for ( const __a of __zuzu_call_args ) {",\n              "if ( __zuzu_is_pairlist( __a ) ) { __zuzu_named_args = __a; } else { __zuzu_rest_args.push( __a ); }",\n              "}",\n              `const ${signature.namedName} = __zuzu_named_args;`,\n              `const ${signature.restName} = __zuzu_rest_args;`\n            ].join("\\n");\n          case "lead_pairlist":\n            return [\n              "const __zuzu_call_args = Array.prototype.slice.call( arguments );",\n              `const ${signature.headName} = __zuzu_call_args[0];`,\n              "let __zuzu_named_args = __zuzu_pairlist_literal( [] );",\n              "const __zuzu_rest_args = [];",\n              "for ( let __i = 1; __i < __zuzu_call_args.length; __i++ ) {",\n              "const __a = __zuzu_call_args[__i];",\n              "if ( __zuzu_is_pairlist( __a ) ) { __zuzu_named_args = __a; } else { __zuzu_rest_args.push( __a ); }",\n              "}",\n              `const ${signature.namedName} = __zuzu_named_args;`,\n              `const ${signature.restName} = __zuzu_rest_args;`\n            ].join("\\n");\n          case "trail_pairlist":\n            return [\n              "const __zuzu_call_args = Array.prototype.slice.call( arguments );",\n              `const ${signature.headName} = __zuzu_call_args[0];`,\n              "const __zuzu_rest_args = [];",\n              "let __zuzu_named_args = __zuzu_pairlist_literal( [] );",\n              "for ( let __i = 1; __i < __zuzu_call_args.length; __i++ ) {",\n              "const __a = __zuzu_call_args[__i];",\n              "if ( __zuzu_is_pairlist( __a ) ) { __zuzu_named_args = __a; } else { __zuzu_rest_args.push( __a ); }",\n              "}",\n              `const ${signature.restName} = __zuzu_rest_args;`,\n              `const ${signature.namedName} = __zuzu_named_args;`\n            ].join("\\n");\n          case "scalar_pairlist":\n            return [\n              "const __zuzu_call_args = Array.prototype.slice.call( arguments );",\n              `const ${signature.headName} = __zuzu_call_args[0];`,\n              "let __zuzu_named_args = __zuzu_pairlist_literal( [] );",\n              "for ( let __i = 1; __i < __zuzu_call_args.length; __i++ ) {",\n              "const __a = __zuzu_call_args[__i];",\n              \'if ( __zuzu_is_pairlist( __a ) ) { __zuzu_named_args = __a; } else { throw new Exception( "named arguments not allowed for this function" ); }\',\n              "}",\n              `const ${signature.namedName} = __zuzu_named_args;`\n            ].join("\\n");\n          case "scalar_pairlist_array":\n            return [\n              "const __zuzu_call_args = Array.prototype.slice.call( arguments );",\n              `const ${signature.headName} = __zuzu_call_args[0];`,\n              "let __zuzu_named_args = __zuzu_pairlist_literal( [] );",\n              "const __zuzu_rest_args = [];",\n              "for ( let __i = 1; __i < __zuzu_call_args.length; __i++ ) {",\n              "const __a = __zuzu_call_args[__i];",\n              "if ( __zuzu_is_pairlist( __a ) ) { __zuzu_named_args = __a; } else { __zuzu_rest_args.push( __a ); }",\n              "}",\n              `const ${signature.restName} = __zuzu_rest_args;`,\n              `const ${signature.namedName} = __zuzu_named_args;`\n            ].join("\\n");\n          case "variadic":\n            return [\n              "const __zuzu_call_args = Array.prototype.slice.call( arguments );",\n              `const ${signature.headName} = __zuzu_call_args[0];`,\n              "const __zuzu_rest_args = [];",\n              "for ( let __i = 1; __i < __zuzu_call_args.length; __i++ ) {",\n              "const __a = __zuzu_call_args[__i];",\n              \'if ( __zuzu_is_pairlist( __a ) ) { throw new Exception( "named arguments not allowed for this function" ); } __zuzu_rest_args.push( __a );\',\n              "}",\n              `const ${signature.restName} = __zuzu_rest_args;`\n            ].join("\\n");\n          default:\n            return "";\n        }\n      }\n      function emitReturnValue(argument, options = {}) {\n        let value;\n        if (argument == null) {\n          value = "undefined";\n        } else {\n          value = emitExpression(argument);\n        }\n        if (options.returnTypeName && options.returnTypeName !== "Any") {\n          return `__zuzu_checked_return( ${JSON.stringify(options.callableName || "")}, ${JSON.stringify(options.returnTypeName)}, ${value} )`;\n        }\n        return value;\n      }\n      function emitForInStatement(node, options = {}) {\n        const loopId = loopCounter++;\n        const implicitHere = node.left.name === "^^";\n        const loopName = implicitHere ? `__zuzu_loop_here_${loopId}` : node.left.name;\n        const iterName = `__zuzu_iterated_${implicitHere ? "here" : node.left.name}_${loopId}`;\n        const elsePart = node.elseBlock ? `if ( !${iterName} ) ${emitBlock(node.elseBlock, options)}` : "";\n        const loopKeyword = node.kind ? `${node.kind} ` : "";\n        const bodyOptions = implicitHere ? {\n          ...options,\n          chainHereName: loopName\n        } : options;\n        return [\n          `let ${iterName} = 0;`,\n          `for ( ${loopKeyword}${loopName} of __zuzu_iter( ${emitExpression(node.iterable)} ) ) {`,\n          `${iterName} = 1;`,\n          node.body.body.map((stmt) => emitStatement(stmt, {\n            ...bodyOptions,\n            loopDepth: (options.loopDepth || 0) + 1\n          })).join("\\n"),\n          "}",\n          elsePart\n        ].filter(Boolean).join("\\n");\n      }\n      function emitTryStatement(node, options = {}) {\n        const handlers = node.handlers || [];\n        let catchBody = "throw __zuzu_err;";\n        if (handlers.length > 0) {\n          const branches = handlers.map((handler, index) => {\n            const cond = handler.typeName === "Exception" || handler.typeName === "Any" ? "true" : `__zuzu_instanceof( __zuzu_err, ${handler.typeName} )`;\n            const prefix = index === 0 ? `if ( ${cond} )` : `else if ( ${cond} )`;\n            return `${prefix} { let ${handler.paramName} = __zuzu_err; ${handler.body.body.map((stmt) => emitStatement(stmt, options)).join("\\n")} }`;\n          });\n          catchBody = `if ( __zuzu_err && __zuzu_err.__zuzu_nonlocal_return ) { throw __zuzu_err; } __zuzu_err = __zuzu_normalize_exception( __zuzu_err ); ${branches.join(" ")} else { throw __zuzu_err; }`;\n        }\n        return `try ${emitBlock(node.block, options)} catch ( __zuzu_err ) { ${catchBody} }`;\n      }\n      function emitImportDeclaration(node, options = {}) {\n        const asyncImport = options.asyncImports === true && options.syncEval !== true;\n        const importModule = () => {\n          const call = `__zuzu_import( ${JSON.stringify(node.source)} )`;\n          return asyncImport ? `await ${call}` : call;\n        };\n        if (node.importAll) {\n          if (options.syncEval) {\n            return `{ const __zuzu_star = __zuzu_import( ${JSON.stringify(node.source)} ); }`;\n          }\n          if (node.source === "std/eval") {\n            return `{ const __zuzu_star = ${importModule()}; for ( const __zuzu_key of Object.keys( __zuzu_star ) ) { if ( __zuzu_key === "eval" ) { continue; } const __zuzu_desc = Object.create( null ); __zuzu_desc.configurable = true; __zuzu_desc.enumerable = true; __zuzu_desc.get = function() { return __zuzu_star[ __zuzu_key ] ?? null; }; __zuzu_desc.set = function( value ) { __zuzu_star[ __zuzu_key ] = value; }; Object.defineProperty( globalThis, __zuzu_key, __zuzu_desc ); } }`;\n          }\n          return `{ const __zuzu_star = ${importModule()}; if ( Object.prototype.hasOwnProperty.call( __zuzu_star, "done_testing" ) ) { var done_testing = __zuzu_star.done_testing ?? null; } for ( const __zuzu_key of Object.keys( __zuzu_star ) ) { if ( __zuzu_key === "done_testing" ) { continue; } const __zuzu_desc = Object.create( null ); __zuzu_desc.configurable = true; __zuzu_desc.enumerable = true; __zuzu_desc.get = function() { return __zuzu_star[ __zuzu_key ] ?? null; }; __zuzu_desc.set = function( value ) { __zuzu_star[ __zuzu_key ] = value; }; Object.defineProperty( globalThis, __zuzu_key, __zuzu_desc ); } }`;\n        }\n        const moduleName = `__zuzu_imported_${Math.abs(hashString(node.source))}_${node.specifiers.length}_${options.syncEval ? loopCounter++ : 0}`;\n        const defineImports = node.specifiers.map((specifier) => {\n          const importedName = normalizeImportedName(node.source, specifier.imported);\n          if (node.source === "std/eval" && importedName === "eval") {\n            return "";\n          }\n          return defineLiveImport(specifier.local, moduleName, importedName, options);\n        }).filter(Boolean);\n        const legacyImports = node.specifiers.map((specifier) => {\n          const importedName = normalizeImportedName(node.source, specifier.imported);\n          const mapped = importedName === specifier.local ? importedName : `${importedName}: ${specifier.local}`;\n          return node.tryMode ? `${mapped} = null` : mapped;\n        });\n        const legacyShape = `/* const { ${legacyImports.join(", ")} } = __zuzu_import( ${JSON.stringify(node.source)} ); */`;\n        const importCondition = node.condition ? node.condition.keyword === "unless" ? `!__zuzu_truthy( ${emitExpression(node.condition.test)} )` : `__zuzu_truthy( ${emitExpression(node.condition.test)} )` : null;\n        const disabledImports = `{ ${node.specifiers.map((specifier) => {\n          const importedName = normalizeImportedName(node.source, specifier.imported);\n          return `${importedName}: null`;\n        }).join(", ")} }`;\n        if (options.syncEval) {\n          if (node.tryMode) {\n            return [\n              `const ${moduleName} = ( () => {`,\n              "try {",\n              importCondition ? `if ( !( ${importCondition} ) ) { return {}; }` : "",\n              `return __zuzu_import( ${JSON.stringify(node.source)} );`,\n              "}",\n              "catch ( __zuzu_err ) {",\n              "if ( __zuzu_err && __zuzu_err.__zuzu_nonlocal_return ) { throw __zuzu_err; }",\n              "return {};",\n              "}",\n              "} )();",\n              ...defineImports\n            ].filter(Boolean).join(" ");\n          }\n          if (importCondition) {\n            return [\n              `const ${moduleName} = ( () => {`,\n              `if ( !( ${importCondition} ) ) { return ${disabledImports}; }`,\n              `return __zuzu_import( ${JSON.stringify(node.source)} );`,\n              "} )();",\n              ...defineImports\n            ].join(" ");\n          }\n          return `const ${moduleName} = __zuzu_import( ${JSON.stringify(node.source)} ); ${defineImports.join(" ")}`;\n        }\n        if (node.tryMode) {\n          if (asyncImport) {\n            return [\n              `{ ${legacyShape} const ${moduleName} = await ( async () => {`,\n              "try {",\n              importCondition ? `if ( !( ${importCondition} ) ) { return {}; }` : "",\n              `return ${importModule()};`,\n              "}",\n              "catch ( __zuzu_err ) {",\n              "if ( __zuzu_err && __zuzu_err.__zuzu_nonlocal_return ) { throw __zuzu_err; }",\n              "return {};",\n              "}",\n              "} )();",\n              ...defineImports,\n              "}"\n            ].filter(Boolean).join(" ");\n          }\n          return [\n            `{ ${legacyShape} const ${moduleName} = ( () => {`,\n            "try {",\n            importCondition ? `if ( !( ${importCondition} ) ) { return {}; }` : "",\n            `return __zuzu_import( ${JSON.stringify(node.source)} );`,\n            "}",\n            "catch ( __zuzu_err ) {",\n            "if ( __zuzu_err && __zuzu_err.__zuzu_nonlocal_return ) { throw __zuzu_err; }",\n            "return {};",\n            "}",\n            "} )();",\n            ...defineImports,\n            "}"\n          ].filter(Boolean).join(" ");\n        }\n        if (importCondition) {\n          if (asyncImport) {\n            return [\n              `{ ${legacyShape} const ${moduleName} = await ( async () => {`,\n              `if ( !( ${importCondition} ) ) { return ${disabledImports}; }`,\n              `return ${importModule()};`,\n              "} )();",\n              ...defineImports,\n              "}"\n            ].join(" ");\n          }\n          return [\n            `{ ${legacyShape} const ${moduleName} = ( () => {`,\n            `if ( !( ${importCondition} ) ) { return ${disabledImports}; }`,\n            `return __zuzu_import( ${JSON.stringify(node.source)} );`,\n            "} )();",\n            ...defineImports,\n            "}"\n          ].join(" ");\n        }\n        return `{ ${legacyShape} const ${moduleName} = ${importModule()}; ${defineImports.join(" ")} }`;\n      }\n      function normalizeImportedName(source, imported) {\n        return source === "std/math" && imported === "pi" ? "\\u03C0" : imported;\n      }\n      function hashString(value) {\n        let hash = 0;\n        for (let i = 0; i < value.length; i++) {\n          hash = (hash << 5) - hash + value.charCodeAt(i);\n          hash |= 0;\n        }\n        return hash;\n      }\n      function defineLiveImport(localName, moduleName, importedName, options = {}) {\n        if (options.syncEval) {\n          return `const ${localName} = ${moduleName}[${JSON.stringify(importedName)}] ?? null;`;\n        }\n        if (localName === "done_testing") {\n          return `var done_testing = ${moduleName}[${JSON.stringify(importedName)}] ?? null;`;\n        }\n        return [\n          "{",\n          "const __zuzu_desc = Object.create( null );",\n          "__zuzu_desc.configurable = true;",\n          "__zuzu_desc.enumerable = true;",\n          `__zuzu_desc.get = function() { return ${moduleName}[${JSON.stringify(importedName)}] ?? null; };`,\n          `__zuzu_desc.set = function( value ) { ${moduleName}[${JSON.stringify(importedName)}] = value; };`,\n          "Object.defineProperty( globalThis,",\n          `${JSON.stringify(localName)},`,\n          "__zuzu_desc );",\n          "}"\n        ].join(" ");\n      }\n      function emitBlock(node, options = {}) {\n        const expressionDeclaredNames = collectExpressionDeclaredNames(node.body);\n        const scopedOptions = {\n          ...options,\n          asyncNames: /* @__PURE__ */ new Set([...options.asyncNames || [], ...collectAsyncFunctionNames(node.body)]),\n          weakStorageNames: /* @__PURE__ */ new Set([\n            ...options.weakStorageNames || [],\n            ...collectWeakDeclaredNames(node.body)\n          ]),\n          bodylessFunctionNames: /* @__PURE__ */ new Set(),\n          scopeNames: /* @__PURE__ */ new Set([\n            ...options.scopeNames || [],\n            ...collectDeclaredNames(node.body),\n            ...expressionDeclaredNames\n          ])\n        };\n        const cleanupNames = collectCleanupNames(node);\n        const body = emitBlockBodyStatements(node.body, cleanupNames, scopedOptions);\n        if (cleanupNames.length === 0) {\n          return `{\n${body}\n}`;\n        }\n        const cleanup = cleanupNames.map((name2) => options.returnSlotName ? `__zuzu_maybe_demolish( ${name2}, ${options.returnSlotName} );` : `__zuzu_maybe_demolish( ${name2} );`).join("\\n");\n        return `{\n${cleanupNames.map((name2) => `let ${name2} = null;`).join("\\n")}\ntry {\n${body}\n} finally {\n${cleanup}\n}\n}`;\n      }\n      function emitBlockBodyStatements(statements, cleanupNames, options = {}) {\n        const lines = [];\n        for (let i = 0; i < statements.length; i++) {\n          const stmt = statements[i];\n          if (stmt.type === "VariableUnpackDeclaration") {\n            const unpack = emitVariableUnpackParts(stmt);\n            const rest = emitBlockBodyStatements(\n              statements.slice(i + 1),\n              cleanupNames,\n              {\n                ...options,\n                scopeNames: /* @__PURE__ */ new Set([\n                  ...options.scopeNames || [],\n                  ...declaredNamesForStatement(stmt)\n                ])\n              }\n            );\n            lines.push(...unpack.prelude);\n            lines.push("{");\n            lines.push(...unpack.declarations);\n            lines.push(emitUnpackScopedRest(stmt, rest));\n            lines.push("}");\n            return lines.filter((line) => line !== "").join("\\n");\n          }\n          lines.push(emitBlockStatement(stmt, cleanupNames, options));\n        }\n        return lines.join("\\n");\n      }\n      function emitUnpackScopedRest(stmt, rest) {\n        const cleanupNames = declaredNamesForStatement(stmt).filter((name2) => name2 !== "self");\n        if (cleanupNames.length === 0) {\n          return rest;\n        }\n        const cleanup = cleanupNames.map((name2) => `__zuzu_maybe_demolish( ${name2} );`).join("\\n");\n        return `try {\n${rest}\n} finally {\n${cleanup}\n}`;\n      }\n      function collectAsyncFunctionNames(statements = []) {\n        const names = [];\n        for (const stmt of statements) {\n          if (stmt.type === "FunctionDeclaration" && stmt.isAsync && stmt.id && stmt.id.name) {\n            names.push(stmt.id.name);\n          } else if (stmt.type === "VariableDeclaration" && stmt.init && stmt.init.type === "FunctionExpression" && stmt.init.isAsync && stmt.id && stmt.id.name) {\n            names.push(stmt.id.name);\n          }\n        }\n        return names;\n      }\n      function collectEvalImportNames(statements = []) {\n        const names = [];\n        for (const stmt of statements) {\n          if (stmt.type !== "ImportDeclaration" || stmt.source !== "std/eval") {\n            continue;\n          }\n          for (const specifier of stmt.specifiers || []) {\n            const importedName = normalizeImportedName(stmt.source, specifier.imported);\n            if (importedName === "eval" && specifier.local) {\n              names.push(specifier.local);\n            }\n          }\n        }\n        return names;\n      }\n      function collectDeclaredNames(statements) {\n        const names = [];\n        for (const stmt of statements || []) {\n          names.push(...declaredNamesForStatement(stmt));\n        }\n        return names;\n      }\n      function declaredNamesForStatement(stmt) {\n        if (!stmt) {\n          return [];\n        }\n        if (["VariableDeclaration", "FunctionDeclaration", "ClassDeclaration", "TraitDeclaration"].includes(stmt.type) && stmt.id && stmt.id.name) {\n          return [stmt.id.name];\n        }\n        if (stmt.type === "VariableUnpackDeclaration") {\n          return bindingEntriesForPattern(stmt.pattern).map((entry) => entry.name).filter(Boolean);\n        }\n        return [];\n      }\n      function emitPredeclaredNames(names) {\n        const unique = [...new Set(names || [])].filter(Boolean);\n        return unique.length > 0 ? `let ${unique.map((name2) => `${name2} = null`).join(", ")};` : "";\n      }\n      function collectExpressionDeclaredNames(statements = []) {\n        return collectExpressionDeclaredEntries(statements).map((entry) => entry.name).filter(Boolean);\n      }\n      function collectExpressionDeclaredEntries(statements = []) {\n        const entries = [];\n        for (const stmt of statements || []) {\n          collectExpressionDeclaredEntriesFromNode(stmt, entries);\n        }\n        return entries;\n      }\n      function collectExpressionDeclaredEntriesFromNode(node, entries) {\n        if (!node || typeof node !== "object") {\n          return;\n        }\n        if (Array.isArray(node)) {\n          for (const item of node) {\n            collectExpressionDeclaredEntriesFromNode(item, entries);\n          }\n          return;\n        }\n        if (node.type === "LetExpression") {\n          if (node.id && node.id.name) {\n            entries.push({\n              name: node.id.name,\n              isWeakStorage: node.isWeakStorage === true\n            });\n          }\n          collectExpressionDeclaredEntriesFromNode(node.init, entries);\n          return;\n        }\n        if ([\n          "BlockStatement",\n          "ClassDeclaration",\n          "DoExpression",\n          "FunctionDeclaration",\n          "FunctionExpression",\n          "MethodDeclaration",\n          "TraitDeclaration",\n          "TryExpression",\n          "AwaitExpression",\n          "SpawnExpression"\n        ].includes(node.type)) {\n          return;\n        }\n        for (const [key, value] of Object.entries(node)) {\n          if (key === "loc") {\n            continue;\n          }\n          collectExpressionDeclaredEntriesFromNode(value, entries);\n        }\n      }\n      function bindingEntriesForPattern(pattern) {\n        return pattern && Array.isArray(pattern.entries) ? pattern.entries : [];\n      }\n      function scopeHasName(options, name2) {\n        return !!(options.scopeNames && options.scopeNames.has(name2));\n      }\n      function emitStoredValue(value, isWeakStorage) {\n        return isWeakStorage ? `__zuzu_make_weak_value( ${value} )` : `__zuzu_retain_value( ${value} )`;\n      }\n      function expressionRetainsCollectionValues(node) {\n        return [\n          "ArrayExpression",\n          "BagLiteral",\n          "ObjectExpression",\n          "PairListLiteral",\n          "SetLiteral"\n        ].includes(node.type);\n      }\n      function emitVariableDeclarationValue(node) {\n        let value = node.init ? emitExpression(node.init) : "null";\n        if (node.init && node.declaredType && node.declaredType !== "Any") {\n          value = `__zuzu_checked_declaration( ${JSON.stringify(node.id.name)}, ${JSON.stringify(node.declaredType)}, ${value} )`;\n        }\n        return emitStoredValue(value, node.isWeakStorage);\n      }\n      function emitLetExpression(node) {\n        const name2 = emitExpression(node.id);\n        const value = emitVariableDeclarationValue(node);\n        return `( ${name2} = ${value}, __zuzu_resolve_weak_value( ${name2} ) )`;\n      }\n      function emitVariableUnpackDeclaration(node) {\n        const parts = emitVariableUnpackParts(node);\n        return [...parts.prelude, ...parts.declarations].join("\\n");\n      }\n      function emitVariableUnpackParts(node) {\n        const sourceName = `__zuzu_unpack_source_${loopCounter++}`;\n        const entries = bindingEntriesForPattern(node.pattern);\n        const prelude = [\n          `const ${sourceName} = __zuzu_unpack_source( ${emitExpression(node.init)} );`\n        ];\n        const valueNames = entries.map(() => `__zuzu_unpack_value_${loopCounter++}`);\n        for (let i = 0; i < entries.length; i++) {\n          prelude.push(\n            `const ${valueNames[i]} = ${emitUnpackEntryValue(sourceName, entries[i])};`\n          );\n        }\n        if (node.init && expressionRetainsCollectionValues(node.init)) {\n          prelude.push(`__zuzu_release_collection_values( ${sourceName} );`);\n        }\n        const declarations = [];\n        for (let i = 0; i < entries.length; i++) {\n          const entry = entries[i];\n          declarations.push(\n            `${node.kind} ${entry.name} = ${valueNames[i]};`\n          );\n        }\n        return { prelude, declarations, entries, valueNames };\n      }\n      function emitVariableUnpackAssignments(node) {\n        const sourceName = `__zuzu_unpack_source_${loopCounter++}`;\n        const lines = [\n          `const ${sourceName} = __zuzu_unpack_source( ${emitExpression(node.init)} );`\n        ];\n        const entries = bindingEntriesForPattern(node.pattern);\n        const valueNames = entries.map(() => `__zuzu_unpack_value_${loopCounter++}`);\n        for (let i = 0; i < entries.length; i++) {\n          lines.push(\n            `const ${valueNames[i]} = ${emitUnpackEntryValue(sourceName, entries[i])};`\n          );\n        }\n        if (node.init && expressionRetainsCollectionValues(node.init)) {\n          lines.push(`__zuzu_release_collection_values( ${sourceName} );`);\n        }\n        for (let i = 0; i < entries.length; i++) {\n          lines.push(`${entries[i].name} = ${valueNames[i]};`);\n        }\n        return lines.join("\\n");\n      }\n      function emitUnpackEntryValue(sourceName, entry) {\n        const defaultThunk = entry.defaultValue ? `() => ${emitExpression(entry.defaultValue)}` : "null";\n        return `__zuzu_unpack_value( ${sourceName}, ${emitExpression(entry.key)}, ${defaultThunk}, ${JSON.stringify(entry.name)}, ${entry.declaredType ? JSON.stringify(entry.declaredType) : "null"}, ${entry.isWeakStorage ? "true" : "false"} )`;\n      }\n      function emitBlockStatement(node, cleanupNames, options = {}) {\n        if (node.type === "VariableDeclaration" && node.id && cleanupNames.includes(node.id.name)) {\n          return `${emitExpression(node.id)} = ${emitVariableDeclarationValue(node)};`;\n        }\n        if (node.type === "VariableUnpackDeclaration" && bindingEntriesForPattern(node.pattern).some((entry) => cleanupNames.includes(entry.name))) {\n          return emitVariableUnpackAssignments(node);\n        }\n        return emitStatement(node, options);\n      }\n      function emitSwitchStatement(node, options = {}) {\n        if (options.asyncContext && !options.syncEval) {\n          const cases2 = node.cases.map((section) => `{ tests: [ ${section.values.map((value, index) => `async function( __zuzu_switch_value ) { return __zuzu_truthy( ${emitSwitchTestExpression(section, index, node.comparator)} ); }`).join(", ")} ], body: async function() ${emitBlock(section.consequent, {\n            ...options,\n            inSwitchSection: true,\n            loopDepth: 0\n          })} }`);\n          const defaultBody2 = node.defaultCase ? `async function() ${emitBlock(node.defaultCase.consequent, {\n            ...options,\n            inSwitchSection: true,\n            loopDepth: 0\n          })}` : "null";\n          const tail2 = switchStatementContainsReturn(node) ? options.inSwitchSection ? "if ( __zuzu_switch_result && __zuzu_switch_result.__zuzu_return ) { return __zuzu_switch_result; }" : "if ( __zuzu_switch_result && __zuzu_switch_result.__zuzu_return ) { return __zuzu_switch_result.value; }" : "";\n          return `{ let __zuzu_switch_result = await __zuzu_switch_async( ${emitExpression(node.discriminant)}, ${JSON.stringify(node.comparator)}, [ ${cases2.join(", ")} ], ${defaultBody2} ); ${tail2} }`;\n        }\n        const cases = node.cases.map((section) => `{ tests: [ ${section.values.map((value, index) => `function( __zuzu_switch_value ) { return __zuzu_truthy( ${emitSwitchTestExpression(section, index, node.comparator)} ); }`).join(", ")} ], body: function() ${emitBlock(section.consequent, {\n          ...options,\n          inSwitchSection: true,\n          loopDepth: 0\n        })} }`);\n        const defaultBody = node.defaultCase ? `function() ${emitBlock(node.defaultCase.consequent, {\n          ...options,\n          inSwitchSection: true,\n          loopDepth: 0\n        })}` : "null";\n        const tail = switchStatementContainsReturn(node) ? options.inSwitchSection ? "if ( __zuzu_switch_result && __zuzu_switch_result.__zuzu_return ) { return __zuzu_switch_result; }" : "if ( __zuzu_switch_result && __zuzu_switch_result.__zuzu_return ) { return __zuzu_switch_result.value; }" : "";\n        return `{ let __zuzu_switch_result = __zuzu_switch( ${emitExpression(node.discriminant)}, ${JSON.stringify(node.comparator)}, [ ${cases.join(", ")} ], ${defaultBody} ); ${tail} }`;\n      }\n      function emitSwitchTestExpression(section, index, defaultComparator) {\n        const right = section.values[index];\n        const operator = section.operators && section.operators[index] || defaultComparator || "==";\n        return emitBinaryExpression({\n          type: "BinaryExpression",\n          operator,\n          left: {\n            type: "Identifier",\n            name: "__zuzu_switch_value"\n          },\n          right\n        });\n      }\n      function emitTraitDeclaration(node, options = {}) {\n        const methods = completeMethodDeclarations(node.body || []).map((method) => {\n          const value = emitMethodFunction(method, {\n            ...options,\n            callableName: method.id.name,\n            returnTypeName: method.returnType,\n            fieldNames: [],\n            className: null,\n            isStatic: false,\n            methodSelfName: "self"\n          });\n          return `${JSON.stringify(method.id.name)}: ${value}`;\n        });\n        return `let ${emitExpression(node.id)} = __zuzu_trait( ${JSON.stringify(node.id.name)}, { ${methods.join(", ")} }, ${JSON.stringify(marshalSourceSlice(node, options) || "")}, ${marshalCapturesExpression(marshalTraitCaptureNames(node, options))} );`;\n      }\n      function emitClassDeclaration(node, options = {}) {\n        return emitClassDeclarationWithName(node, node.id.name, options);\n      }\n      function emitFieldSpec(node) {\n        return `{ kind: ${JSON.stringify(node.kind || "let")}, name: ${JSON.stringify(node.id.name)}, typeName: ${node.typeName ? JSON.stringify(node.typeName) : "null"}, isWeakStorage: ${node.isWeakStorage ? "true" : "false"}, accessors: [ ${node.accessors.map((item) => JSON.stringify(item)).join(", ")} ], defaultValue: ${node.defaultValue ? `function() { return ${emitExpression(node.defaultValue)}; }` : "null"} }`;\n      }\n      function emitNestedDeclarationEntry(node, parentName, options = {}) {\n        if (node.type === "ClassDeclaration") {\n          const qualified = `${parentName}{${JSON.stringify(node.id.name)}}`;\n          return `${JSON.stringify(node.id.name)}: ( function() { ${emitClassDeclarationWithName(node, qualified, options)} return ${node.id.name}; } )()`;\n        }\n        return `${JSON.stringify(node.id.name)}: ( function() { ${emitStatement(node, options)} return ${node.id.name}; } )()`;\n      }\n      function emitMethodFunction(node, meta) {\n        if (node.isPredeclared) {\n          return `__zuzu_bodyless_function( ${JSON.stringify(node.id.name)} )`;\n        }\n        return `( ${emitFunctionLike(node, `${node.isAsync ? "async " : ""}function()`, {\n          ...meta,\n          asyncContext: node.isAsync === true,\n          extraPreamble: [\n            "let self = this;",\n            `let __zuzu_super_class__ = ${meta.className ? meta.className : "null"};`,\n            `let __zuzu_super_method__ = ${JSON.stringify(node.id.name)};`,\n            `let __zuzu_super_static__ = ${meta.isStatic ? 1 : 0};`,\n            ...(meta.nestedNames || []).map((name2) => `let ${name2} = self[${JSON.stringify(name2)}];`)\n          ].join("\\n"),\n          scopeNames: /* @__PURE__ */ new Set(["self", "__zuzu_super_class__", "__zuzu_super_method__", "__zuzu_super_static__"]),\n          fieldNames: meta.fieldNames || [],\n          methodSelfName: meta.methodSelfName || "self"\n        })} )`;\n      }\n      function emitClassDeclarationWithName(node, runtimeName, options = {}) {\n        if (node.shorthand && node.traits.length === 0) {\n          return `let ${emitExpression(node.id)} = __zuzu_make_class( ${JSON.stringify(runtimeName)}, ${node.base ? emitExpression(node.base) : "Object"} );`;\n        }\n        const fields = node.body.filter((entry) => entry.type === "FieldDeclaration");\n        const methodEntries = completeMethodDeclarations(node.body.filter((entry) => entry.type === "MethodDeclaration"));\n        const methods = methodEntries.filter((entry) => !entry.static);\n        const statics = methodEntries.filter((entry) => entry.static);\n        const nested = node.body.filter((entry) => ["ClassDeclaration", "TraitDeclaration"].includes(entry.type));\n        const fieldNames = fields.map((field) => field.id.name);\n        const nestedNames = nested.map((entry) => entry.id.name);\n        return `let ${emitExpression(node.id)} = __zuzu_define_class( ${JSON.stringify(runtimeName)}, ${node.base ? emitExpression(node.base) : "Object"}, { "marshalSource": ${JSON.stringify(marshalSourceSlice(node, options) || "")}, "marshalCaptures": ${marshalCapturesExpression(marshalClassCaptureNames(node, options))}, "traits": [ ${node.traits.map(emitExpression).join(", ")} ], "fields": [ ${fields.map(emitFieldSpec).join(", ")} ], "methods": { ${methods.map((method) => `${JSON.stringify(method.id.name)}: ${emitMethodFunction(method, {\n          ...options,\n          callableName: method.id.name,\n          returnTypeName: method.returnType,\n          fieldNames,\n          className: node.id.name,\n          isStatic: false,\n          methodSelfName: "self",\n          nestedNames\n        })}`).join(", ")} }, "statics": { ${statics.map((method) => `${JSON.stringify(method.id.name)}: ${emitMethodFunction(method, {\n          ...options,\n          callableName: method.id.name,\n          returnTypeName: method.returnType,\n          fieldNames: [],\n          className: node.id.name,\n          isStatic: true,\n          methodSelfName: "self",\n          nestedNames\n        })}`).join(", ")} }, "nested": { ${nested.map((entry) => emitNestedDeclarationEntry(entry, runtimeName, options)).join(", ")} } } );`;\n      }\n      function completeMethodDeclarations(entries) {\n        const ordered = [];\n        const indexes = /* @__PURE__ */ new Map();\n        for (const entry of entries || []) {\n          if (entry.type !== "MethodDeclaration") {\n            continue;\n          }\n          const key = `${entry.static ? "static:" : "instance:"}${entry.id.name}`;\n          if (indexes.has(key)) {\n            const index = indexes.get(key);\n            if (ordered[index].isPredeclared && !entry.isPredeclared) {\n              ordered[index] = entry;\n            }\n            continue;\n          }\n          indexes.set(key, ordered.length);\n          ordered.push(entry);\n        }\n        return ordered;\n      }\n      function switchStatementContainsReturn(node) {\n        return node.cases.some((section) => blockContainsReturn(section.consequent)) || node.defaultCase && blockContainsReturn(node.defaultCase.consequent);\n      }\n      function blockContainsReturn(block) {\n        return block.body.some(statementContainsReturn);\n      }\n      function statementContainsReturn(stmt) {\n        switch (stmt.type) {\n          case "ReturnStatement":\n            return true;\n          case "BlockStatement":\n            return blockContainsReturn(stmt);\n          case "IfStatement":\n            return blockContainsReturn(stmt.consequent) || (stmt.alternate ? stmt.alternate.type === "BlockStatement" ? blockContainsReturn(stmt.alternate) : statementContainsReturn(stmt.alternate) : false);\n          case "ForInStatement":\n            return blockContainsReturn(stmt.body) || (stmt.elseBlock ? blockContainsReturn(stmt.elseBlock) : false);\n          case "WhileStatement":\n            return blockContainsReturn(stmt.body);\n          case "TryStatement":\n            return blockContainsReturn(stmt.block) || (stmt.handlers || []).some((handler) => blockContainsReturn(handler.body));\n          case "SwitchStatement":\n            return switchStatementContainsReturn(stmt);\n          default:\n            return false;\n        }\n      }\n      function emitExpression(node) {\n        const options = currentEmitContext();\n        switch (node.type) {\n          case "Identifier":\n            if (node.name === "^^") {\n              return options.chainHereName || `( () => { throw new Error( "Undeclared variable \'^^\'" ); } )()`;\n            }\n            if (options.fieldNames && options.fieldNames.includes(node.name) && !scopeHasName(options, node.name)) {\n              return `${options.methodSelfName || "self"}[${JSON.stringify(node.name)}]`;\n            }\n            return node.name === "__argc__" ? "__argc__" : node.name;\n          case "NumericLiteral":\n            return String(node.value);\n          case "StringLiteral":\n            return JSON.stringify(node.value);\n          case "BinaryStringLiteral":\n            return `__zuzu_binary_literal( ${JSON.stringify(node.value)} )`;\n          case "TemplateLiteral":\n            return emitTemplateLiteral(node);\n          case "RegExpLiteral":\n            return `new RegExp( ${emitRegExpPattern(node)}, ${JSON.stringify(node.flags)} )`;\n          case "Literal":\n            if (node.value === null) {\n              return "null";\n            }\n            return node.value ? "true" : "false";\n          case "Super":\n            throw new UnsupportedSyntaxError("super must be called like a method");\n          case "GroupedExpression":\n            return `( ${emitExpression(node.expression)} )`;\n          case "ArrayExpression":\n            return `__zuzu_array( [ ${node.elements.map((element) => {\n              if (element.type === "BinaryExpression" && element.operator === "...") {\n                return `...${emitExpression(element)}`;\n              }\n              return emitExpression(element);\n            }).join(", ")} ] )`;\n          case "SetLiteral":\n            return `__zuzu_set( [ ${emitCollectionElements(node.elements)} ] )`;\n          case "BagLiteral":\n            return `__zuzu_bag( [ ${emitCollectionElements(node.elements)} ] )`;\n          case "PairListLiteral":\n            return `__zuzu_pairlist_literal( [ ${emitPairListEntries(node.entries)} ] )`;\n          case "ObjectExpression":\n            return `( () => { const __zuzu_obj = {}; ${node.properties.map(\n              (prop) => `__zuzu_obj[${JSON.stringify(prop.key)}] = __zuzu_retain_collection_value( __zuzu_obj, ${emitExpression(prop.value)} );`\n            ).join(" ")} return __zuzu_obj; } )()`;\n          case "NamedArgument":\n            return `[ ${emitExpression(node.keyExpr || { type: "StringLiteral", value: node.key })}, ${emitExpression(node.value)} ]`;\n          case "BraceIdentifier":\n            return JSON.stringify(node.name);\n          case "SliceExpression":\n            return emitSliceExpression(node);\n          case "MemberExpression":\n            if (node.computed) {\n              if (node.property.type === "BraceIdentifier") {\n                return `__zuzu_get_brace_member( ${emitExpression(node.object)}, ${JSON.stringify(node.property.name)}, () => ${node.property.name} )`;\n              }\n              return `__zuzu_get_index( ${emitExpression(node.object)}, ${emitExpression(node.property)} )`;\n            }\n            if (node.property.name === "length") {\n              return `__zuzu_length( ${emitExpression(node.object)} )`;\n            }\n            return `__zuzu_call_member( ${emitExpression(node.object)}, ${JSON.stringify(node.property.name)} )`;\n          case "CallExpression":\n            return emitCallExpression(node, options);\n          case "RegexReplaceExpression":\n            return emitRegexReplaceExpression(node);\n          case "RefExpression":\n            return emitRefExpression(node);\n          case "AssignmentExpression":\n            return emitAssignmentExpression(node);\n          case "LetExpression":\n            return emitLetExpression(node);\n          case "ConditionalExpression":\n            return `( __zuzu_truthy( ${emitExpression(node.test)} ) ? ${emitExpression(node.consequent)} : ${emitExpression(node.alternate)} )`;\n          case "ShortTernaryExpression":\n            return `( () => { const __zuzu_left = ${emitExpression(node.test)}; return __zuzu_resolve_weak_value( __zuzu_left ) != null ? __zuzu_left : ${emitExpression(node.alternate)}; } )()`;\n          case "TryExpression":\n            return emitTryExpression(node);\n          case "DoExpression":\n            return emitDoExpression(node);\n          case "UnaryExpression":\n            return emitUnaryExpression(node);\n          case "BinaryExpression":\n            return emitBinaryExpression(node);\n          case "UpdateExpression":\n            {\n              const target = unwrapGroupedExpression(node.argument);\n              if (target && target.type === "BinaryExpression" && ["@", "@@", "@?"].includes(target.operator)) {\n                const mode = target.operator === "@@" ? "all" : target.operator === "@?" ? "maybe" : "first";\n                return `__zuzu_path_update( ${emitExpression(target.left)}, ${emitExpression(target.right)}, "${mode}", ${JSON.stringify(node.operator)}, ${node.prefix ? "true" : "false"} )`;\n              }\n            }\n            return node.prefix ? `( ${emitAssignmentTarget(node.argument)} = __zuzu_${node.operator === "++" ? "add" : "sub"}( ${emitAssignmentTarget(node.argument)}, 1 ) )` : `( () => { const __zuzu_old = __zuzu_num( ${emitAssignmentTarget(node.argument)} ); ${emitAssignmentTarget(node.argument)} = __zuzu_${node.operator === "++" ? "add" : "sub"}( __zuzu_old, 1 ); return __zuzu_old; } )()`;\n          case "FunctionExpression": {\n            const fn2 = emitFunctionLike(node, `${node.isAsync ? "async " : ""}function()`, {\n              ...nestedFunctionOptions(options),\n              asyncContext: node.isAsync === true,\n              syncEval: options.syncEval === true\n            });\n            const meta = marshalMetaExpression(\n              "function",\n              node.id && node.id.name,\n              marshalFunctionSource(node),\n              marshalCaptureNames(node)\n            );\n            return `__zuzu_with_marshal_meta( ( ${fn2} ), ${meta} )`;\n          }\n          case "AwaitExpression":\n            if (currentEmitContext().syncEval) {\n              return `__zuzu_await_block_sync( ( () => { ${emitExpressionBlock(node.block, {\n                ...options,\n                asyncContext: false,\n                nonLocalReturn: true,\n                boxResult: true,\n                syncEval: true\n              })} } )() )`;\n            }\n            return `await __zuzu_await_block( ( async () => { ${emitExpressionBlock(node.block, {\n              ...options,\n              asyncContext: true,\n              nonLocalReturn: true,\n              boxResult: true\n            })} } )() )`;\n          case "SpawnExpression":\n            return `__zuzu_spawn( async () => { ${emitExpressionBlock(node.block, {\n              ...options,\n              asyncContext: true,\n              nonLocalReturn: true\n            })} }, { name: "<spawn>", line: ${JSON.stringify(node.loc.start.line)} } )`;\n          case "NewExpression":\n            return emitNewExpression(node);\n          default:\n            throw new UnsupportedSyntaxError(`Unsupported expression node ${node.type}`);\n        }\n      }\n      function emitNewExpression(node) {\n        const traitList = Array.isArray(node.traits) && node.traits.length > 0 ? `[ ${node.traits.map(emitExpression).join(", ")} ]` : null;\n        if (node.callee.type === "CallExpression") {\n          const callee = emitExpression(node.callee.callee);\n          const constructor = traitList ? `__zuzu_class_with_traits( ${callee}, ${traitList} )` : callee;\n          const args = emitCallArgumentList(node.callee.arguments);\n          if (traitList) {\n            return `new (${constructor})( ${args} )`;\n          }\n          if (node.callee.callee.type === "Identifier" || node.callee.callee.type === "MemberExpression" && !node.callee.callee.computed) {\n            return `new ${constructor}( ${args} )`;\n          }\n          return `new (${constructor})( ${args} )`;\n        }\n        if (traitList) {\n          return `new (__zuzu_class_with_traits( ${emitExpression(node.callee)}, ${traitList} ))`;\n        }\n        return `new ${emitExpression(node.callee)}`;\n      }\n      function emitCallExpression(node, options = {}) {\n        let source;\n        if (node.callee.type === "Super") {\n          const argArray = emitCallArgumentArray(node.arguments);\n          source = `__zuzu_super_dispatch( __zuzu_super_static__, self, __zuzu_super_class__, __zuzu_super_method__, ${argArray} )`;\n        } else if (node.callee.type === "Identifier" && (options.evalNames || /* @__PURE__ */ new Set(["eval"])).has(node.callee.name) && node.arguments.length > 0) {\n          source = emitEvalCall(node.arguments);\n        } else if (node.callee.type === "MemberExpression" && !node.callee.computed && node.callee.property.type === "Identifier" && node.callee.property.name === "length" && node.arguments.length === 0) {\n          source = `__zuzu_length( ${emitExpression(node.callee.object)} )`;\n        } else if (callReleasesTemporaryCollectionReceiver(node)) {\n          const object = emitExpression(node.callee.object);\n          const property = JSON.stringify(node.callee.property.name);\n          source = `( () => { const __zuzu_receiver = ${object}; const __zuzu_result = __zuzu_call_member( __zuzu_receiver, ${property} ); __zuzu_release_collection_values( __zuzu_receiver ); return __zuzu_result; } )()`;\n        } else if (node.callee.type === "MemberExpression") {\n          const args = emitCallArgumentList(node.arguments);\n          if (options.asyncContext && !options.syncEval && !node.callee.computed && node.callee.property.type === "Identifier" && ["map", "grep", "reduce"].includes(node.callee.property.name) && node.arguments.length > 0) {\n            const object = emitExpression(node.callee.object);\n            const method = node.callee.property.name;\n            source = `await __zuzu_collection_${method}_async( ${object}, ${args} )`;\n          } else if (node.arguments.length === 0) {\n            const object = emitExpression(node.callee.object);\n            if (node.callee.computed) {\n              const property = node.callee.property.type === "BraceIdentifier" ? `__zuzu_resolve_brace_key( __zuzu_receiver, ${JSON.stringify(node.callee.property.name)}, () => ${node.callee.property.name} )` : emitExpression(node.callee.property);\n              source = `( () => { const __zuzu_receiver = ${object}; return __zuzu_call_member( __zuzu_receiver, ${property} ); } )()`;\n            } else {\n              source = `__zuzu_call_member( ${object}, ${JSON.stringify(node.callee.property.name)} )`;\n            }\n          } else {\n            const object = emitExpression(node.callee.object);\n            if (node.callee.computed) {\n              const property = node.callee.property.type === "BraceIdentifier" ? `__zuzu_resolve_brace_key( __zuzu_receiver, ${JSON.stringify(node.callee.property.name)}, () => ${node.callee.property.name} )` : emitExpression(node.callee.property);\n              source = `( () => { const __zuzu_receiver = ${object}; return __zuzu_call_member( __zuzu_receiver, ${property}, ${args} ); } )()`;\n            } else {\n              source = `__zuzu_call_member( ${object}, ${JSON.stringify(node.callee.property.name)}, ${args} )`;\n            }\n          }\n        } else {\n          source = `${emitExpression(node.callee)}( ${emitCallArgumentList(node.arguments)} )`;\n        }\n        if (!callNeedsTraceMetadata(node, options) || /\\bawait\\b/u.test(source)) {\n          return source;\n        }\n        const line = node.loc && node.loc.start ? node.loc.start.line : null;\n        return `__zuzu_callsite( { line: ${JSON.stringify(line)} }, () => ${source} )`;\n      }\n      function callReleasesTemporaryCollectionReceiver(node) {\n        return node.callee.type === "MemberExpression" && !node.callee.computed && node.callee.property.type === "Identifier" && node.arguments.length === 0 && node.callee.object.type === "ArrayExpression" && ["copy", "to_Array", "to_Bag", "to_List", "to_Set"].includes(node.callee.property.name);\n      }\n      function callNeedsTraceMetadata(node, options = {}) {\n        if (node.callee.type === "Identifier") {\n          if (options.asyncNames && options.asyncNames.has(node.callee.name)) {\n            return true;\n          }\n          return [\n            "all",\n            "failed",\n            "race",\n            "resolved",\n            "sleep",\n            "timeout",\n            "yield"\n          ].includes(node.callee.name);\n        }\n        if (node.callee.type === "MemberExpression" && !node.callee.computed && node.callee.property.type === "Identifier") {\n          return [\n            "append_async",\n            "append_utf8_async",\n            "each_line",\n            "lines",\n            "lines_async",\n            "lines_utf8",\n            "lines_utf8_async",\n            "next_line",\n            "pipeline",\n            "pipeline_async",\n            "recv",\n            "request",\n            "request_async",\n            "run",\n            "run_async",\n            "send",\n            "send_async",\n            "sleep_async",\n            "slurp",\n            "slurp_async",\n            "slurp_utf8",\n            "slurp_utf8_async",\n            "spew",\n            "spew_async",\n            "spew_utf8",\n            "spew_utf8_async"\n          ].includes(node.callee.property.name);\n        }\n        return false;\n      }\n      function emitUnaryExpression(node) {\n        const target = unwrapGroupedExpression(node.argument);\n        if ((node.operator === "++" || node.operator === "--") && target && target.type === "BinaryExpression" && ["@", "@@", "@?"].includes(target.operator)) {\n          const mode = target.operator === "@@" ? "all" : target.operator === "@?" ? "maybe" : "first";\n          return `__zuzu_path_update( ${emitExpression(target.left)}, ${emitExpression(target.right)}, "${mode}", ${JSON.stringify(node.operator)}, true )`;\n        }\n        if (node.operator === "not") {\n          return `__zuzu_not( ${emitExpression(node.argument)} )`;\n        }\n        if (node.operator === "\\xAC") {\n          return `__zuzu_not( ${emitExpression(node.argument)} )`;\n        }\n        if (node.operator === "!") {\n          return `__zuzu_not( ${emitExpression(node.argument)} )`;\n        }\n        if (node.operator === "~") {\n          return `__zuzu_bit_not( ${emitExpression(node.argument)} )`;\n        }\n        if (node.operator === "typeof") {\n          return `__zuzu_typeof( ${emitExpression(node.argument)} )`;\n        }\n        if (node.operator === "abs") {\n          return `__zuzu_abs( ${emitExpression(node.argument)} )`;\n        }\n        if (node.operator === "sqrt") {\n          return `__zuzu_sqrt( ${emitExpression(node.argument)} )`;\n        }\n        if (node.operator === "\\u221A") {\n          return `__zuzu_sqrt( ${emitExpression(node.argument)} )`;\n        }\n        if (node.operator === "floor") {\n          return `__zuzu_floor( ${emitExpression(node.argument)} )`;\n        }\n        if (node.operator === "ceil") {\n          return `__zuzu_ceil( ${emitExpression(node.argument)} )`;\n        }\n        if (node.operator === "round") {\n          return `__zuzu_round( ${emitExpression(node.argument)} )`;\n        }\n        if (node.operator === "int") {\n          return `__zuzu_int( ${emitExpression(node.argument)} )`;\n        }\n        if (node.operator === "length") {\n          return `__zuzu_length( ${emitExpression(node.argument)} )`;\n        }\n        if (node.operator === "uc") {\n          return `__zuzu_uc( ${emitExpression(node.argument)} )`;\n        }\n        if (node.operator === "lc") {\n          return `__zuzu_lc( ${emitExpression(node.argument)} )`;\n        }\n        if (node.operator === "+") {\n          return `__zuzu_num( ${emitExpression(node.argument)} )`;\n        }\n        if (node.operator === "-") {\n          return `( -__zuzu_num( ${emitExpression(node.argument)} ) )`;\n        }\n        return `${node.operator}${emitExpression(node.argument)}`;\n      }\n      function emitTemplateLiteral(node) {\n        if (!node.parts || node.parts.length === 0) {\n          return \'""\';\n        }\n        let out = emitExpression(node.parts[0]);\n        for (let i = 1; i < node.parts.length; i++) {\n          out = `__zuzu_concat( ${out}, ${emitExpression(node.parts[i])} )`;\n        }\n        return out;\n      }\n      function emitRegExpPattern(node) {\n        if (!node.parts || node.parts.length === 0) {\n          return JSON.stringify(node.pattern);\n        }\n        return emitTemplateLiteral({\n          type: "TemplateLiteral",\n          parts: node.parts\n        });\n      }\n      function emitCollectionElements(elements) {\n        return elements.map((element) => {\n          if (element.type === "BinaryExpression" && element.operator === "...") {\n            return `...${emitExpression(element)}`;\n          }\n          return emitExpression(element);\n        }).join(", ");\n      }\n      function emitPairListEntries(entries) {\n        return entries.map((entry) => {\n          if (entry.type === "PairListEntry") {\n            const keyExpr = entry.keyExpr || { type: "StringLiteral", value: entry.key };\n            return `[ ${emitExpression(keyExpr)}, ${emitExpression(entry.value)} ]`;\n          }\n          return emitExpression(entry);\n        }).join(", ");\n      }\n      function emitBinaryExpression(node) {\n        if (node.operator === "\\u25B7" || node.operator === "|>") {\n          const input = emitExpression(node.left);\n          const hereName = `__zuzu_chain_${chainCounter++}`;\n          const right2 = withEmitContext({\n            ...currentEmitContext(),\n            chainHereName: hereName\n          }, () => emitExpression(node.right));\n          return `( () => { const ${hereName} = ${input}; return ${right2}; } )()`;\n        }\n        if (node.operator === "\\u25C1" || node.operator === "<|") {\n          const input = emitExpression(node.right);\n          const hereName = `__zuzu_chain_${chainCounter++}`;\n          const left2 = withEmitContext({\n            ...currentEmitContext(),\n            chainHereName: hereName\n          }, () => emitExpression(node.left));\n          return `( () => { const ${hereName} = ${input}; return ${left2}; } )()`;\n        }\n        const left = emitExpression(node.left);\n        const right = emitExpression(node.right);\n        switch (node.operator) {\n          case "and":\n          case "\\u22C0":\n            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? __zuzu_truthy( ${right} ) : false; } )()`;\n          case "and?":\n          case "\\u22C0?":\n            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? ${right} : __zuzu_left; } )()`;\n          case "or":\n          case "\\u22C1":\n            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? true : __zuzu_truthy( ${right} ); } )()`;\n          case "or?":\n          case "\\u22C1?":\n            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? __zuzu_left : ${right}; } )()`;\n          case "nor":\n          case "\\u22BD":\n            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? false : !__zuzu_truthy( ${right} ); } )()`;\n          case "nor?":\n          case "\\u22BD?":\n            return `( () => { const __zuzu_left = ${left}; const __zuzu_right = ${right}; return __zuzu_truthy( __zuzu_left ) ? ( __zuzu_truthy( __zuzu_right ) ? false : __zuzu_right ) : ( __zuzu_truthy( __zuzu_right ) ? __zuzu_left : true ); } )()`;\n          case "xor":\n          case "\\u22BB":\n            return `__zuzu_xor( ${left}, ${right} )`;\n          case "xor?":\n          case "\\u22BB?":\n            return `( () => { const __zuzu_left = ${left}; const __zuzu_right = ${right}; return __zuzu_truthy( __zuzu_left ) ? ( __zuzu_truthy( __zuzu_right ) ? false : __zuzu_left ) : ( __zuzu_truthy( __zuzu_right ) ? __zuzu_right : false ); } )()`;\n          case "xnor":\n          case "\\u2194":\n            return `( __zuzu_truthy( ${left} ) === __zuzu_truthy( ${right} ) )`;\n          case "xnor?":\n          case "\\u2194?":\n            return `( () => { const __zuzu_left = ${left}; const __zuzu_right = ${right}; return __zuzu_truthy( __zuzu_left ) ? __zuzu_right : ( __zuzu_truthy( __zuzu_right ) ? __zuzu_left : true ); } )()`;\n          case "nand":\n          case "\\u22BC":\n            return `__zuzu_nand( ${left}, ${right} )`;\n          case "nand?":\n          case "\\u22BC?":\n            return `( () => { const __zuzu_left = ${left}; const __zuzu_right = ${right}; return __zuzu_truthy( __zuzu_left ) ? ( __zuzu_truthy( __zuzu_right ) ? false : true ) : ( __zuzu_truthy( __zuzu_right ) ? __zuzu_right : true ); } )()`;\n          case "onlyif":\n          case "\\u22A8":\n            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? __zuzu_truthy( ${right} ) : true; } )()`;\n          case "onlyif?":\n          case "\\u22A8?":\n            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? ${right} : true; } )()`;\n          case "butnot":\n          case "\\u22AD":\n            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? !__zuzu_truthy( ${right} ) : false; } )()`;\n          case "butnot?":\n          case "\\u22AD?":\n            return `( () => { const __zuzu_left = ${left}; return __zuzu_truthy( __zuzu_left ) ? ( __zuzu_truthy( ${right} ) ? false : __zuzu_left ) : __zuzu_left; } )()`;\n          case "eq":\n            return `__zuzu_str_eq( ${left}, ${right} )`;\n          case "ne":\n            return `( __zuzu_str_eq( ${left}, ${right} ) ? 0 : 1 )`;\n          case "default":\n            return `__zuzu_default( ${left}, ${right} )`;\n          case "==":\n            return `__zuzu_eq( ${left}, ${right} )`;\n          case "=":\n            return `__zuzu_num_eq( ${left}, ${right} )`;\n          case "\\u2261":\n            return `__zuzu_eq( ${left}, ${right} )`;\n          case "\\u2262":\n            return `__zuzu_ne( ${left}, ${right} )`;\n          case "!=":\n          case "\\u2260":\n            return `__zuzu_ne( ${left}, ${right} )`;\n          case "~":\n            return `__zuzu_match( ${left}, ${right} )`;\n          case "_":\n            return `__zuzu_concat( ${left}, ${right} )`;\n          case "+":\n            return `__zuzu_add( ${left}, ${right} )`;\n          case "-":\n            return `__zuzu_sub( ${left}, ${right} )`;\n          case "*":\n          case "\\xD7":\n            return `__zuzu_mul( ${left}, ${right} )`;\n          case "/":\n          case "\\xF7":\n            return `__zuzu_div( ${left}, ${right} )`;\n          case "**":\n            return `__zuzu_pow( ${left}, ${right} )`;\n          case "mod":\n            return `( __zuzu_num( ${left} ) % __zuzu_num( ${right} ) )`;\n          case "...":\n            return `__zuzu_range( ${left}, ${right} )`;\n          case "<=>":\n          case "\\u2276":\n          case "\\u2277":\n            return `__zuzu_cmp( ${left}, ${right} )`;\n          case "cmp":\n            return `__zuzu_str_cmp( ${left}, ${right} )`;\n          case "gt":\n            return `__zuzu_str_gt( ${left}, ${right} )`;\n          case "ge":\n            return `__zuzu_str_ge( ${left}, ${right} )`;\n          case "lt":\n            return `__zuzu_str_lt( ${left}, ${right} )`;\n          case "le":\n            return `__zuzu_str_le( ${left}, ${right} )`;\n          case "eqi":\n            return `__zuzu_str_eqi( ${left}, ${right} )`;\n          case "nei":\n            return `__zuzu_str_nei( ${left}, ${right} )`;\n          case "gti":\n            return `__zuzu_str_gti( ${left}, ${right} )`;\n          case "gei":\n            return `__zuzu_str_gei( ${left}, ${right} )`;\n          case "lti":\n            return `__zuzu_str_lti( ${left}, ${right} )`;\n          case "lei":\n            return `__zuzu_str_lei( ${left}, ${right} )`;\n          case "cmpi":\n            return `__zuzu_str_cmpi( ${left}, ${right} )`;\n          case "\\u2264":\n            return `__zuzu_num_lte( ${left}, ${right} )`;\n          case "\\u2265":\n            return `__zuzu_num_gte( ${left}, ${right} )`;\n          case "<":\n            return `__zuzu_num_lt( ${left}, ${right} )`;\n          case "<=":\n            return `__zuzu_num_lte( ${left}, ${right} )`;\n          case ">":\n            return `__zuzu_num_gt( ${left}, ${right} )`;\n          case ">=":\n            return `__zuzu_num_gte( ${left}, ${right} )`;\n          case "union":\n          case "\\u22C3":\n            return `__zuzu_union( ${left}, ${right} )`;\n          case "intersection":\n          case "\\u22C2":\n            return `__zuzu_intersection( ${left}, ${right} )`;\n          case "\\\\":\n          case "\\u2216":\n          case "difference":\n            return `__zuzu_difference( ${left}, ${right} )`;\n          case "subsetof":\n          case "\\u2282":\n            return `__zuzu_subsetof( ${left}, ${right} )`;\n          case "supersetof":\n          case "\\u2283":\n            return `__zuzu_supersetof( ${left}, ${right} )`;\n          case "equivalentof":\n          case "\\u2282\\u2283":\n            return `__zuzu_equivalentof( ${left}, ${right} )`;\n          case "instanceof":\n            return `__zuzu_instanceof( ${left}, ${right} )`;\n          case "does":\n            return `__zuzu_does( ${left}, ${right} )`;\n          case "can":\n            if (node.right.type === "Identifier") {\n              return `__zuzu_can( ${left}, ${JSON.stringify(node.right.name)} )`;\n            }\n            return `__zuzu_can( ${left}, ${right} )`;\n          case "in":\n          case "\\u2208":\n            return `__zuzu_contains( ${right}, ${left} )`;\n          case "not_in":\n          case "\\u2209":\n            return `( __zuzu_contains( ${right}, ${left} ) ? 0 : 1 )`;\n          case "@":\n            return `__zuzu_path_op( ${left}, ${right}, "first" )`;\n          case "@@":\n            return `__zuzu_path_op( ${left}, ${right}, "all" )`;\n          case "@?":\n            return `__zuzu_path_op( ${left}, ${right}, "exists" )`;\n          case "&":\n            return `__zuzu_bit_and( ${left}, ${right} )`;\n          case "|":\n            return `__zuzu_bit_or( ${left}, ${right} )`;\n          case "^":\n            return `__zuzu_bit_xor( ${left}, ${right} )`;\n          case "<<":\n          case "\\xAB":\n            return `__zuzu_shift_left( ${left}, ${right} )`;\n          case "\\u2223":\n          case "divides":\n            return `__zuzu_divides( ${left}, ${right} )`;\n          case "\\u2224":\n            return `__zuzu_ndivides( ${left}, ${right} )`;\n          case ">>":\n          case "\\xBB":\n            return `__zuzu_shift_right( ${left}, ${right} )`;\n          default:\n            return `( ${left} ${node.operator} ${right} )`;\n        }\n      }\n      function emitAssignmentExpression(node) {\n        const options = currentEmitContext();\n        if (node.left && node.left.type === "BinaryExpression" && ["@", "@@", "@?"].includes(node.left.operator)) {\n          const target = emitExpression(node.left.left);\n          const path = emitExpression(node.left.right);\n          const right2 = emitExpression(node.right);\n          const mode = node.left.operator === "@@" ? "all" : node.left.operator === "@?" ? "maybe" : "first";\n          return `__zuzu_path_assign( ${target}, ${path}, ${right2}, "${mode}", ${JSON.stringify(node.operator)}, ${node.isWeakWrite ? "true" : "false"} )`;\n        }\n        if (node.left && node.left.type === "SliceExpression" && node.operator === ":=") {\n          const objectTarget = emitAssignmentTarget(node.left.object);\n          const objectValue = emitExpression(node.left.object);\n          const start = node.left.start ? emitExpression(node.left.start) : "0";\n          const length = node.left.length == null ? "null" : emitExpression(node.left.length);\n          const right2 = emitExpression(node.right);\n          return `${objectTarget} = __zuzu_assign_slice( ${objectValue}, ${start}, ${length}, ${right2} )`;\n        }\n        const left = emitAssignmentTarget(node.left);\n        const right = emitExpression(node.right);\n        switch (node.operator) {\n          case ":=":\n            if (node.left && node.left.type === "Identifier") {\n              const weakStorage = options.weakStorageNames && options.weakStorageNames.has(node.left.name);\n              return weakStorage || node.isWeakWrite ? `${left} = __zuzu_assign_weak( ${left}, ${right} )` : `${left} = __zuzu_assign_strong( ${left}, ${right} )`;\n            }\n            if (node.left && node.left.type === "MemberExpression") {\n              if (!node.left.computed) {\n                throw new UnsupportedSyntaxError("Invalid assignment target");\n              }\n              const object = emitExpression(node.left.object);\n              const objectTarget = emitAssignmentTarget(node.left.object);\n              const key = node.left.computed ? node.left.property.type === "BraceIdentifier" ? `__zuzu_resolve_brace_key( ${object}, ${JSON.stringify(node.left.property.name)}, () => ${node.left.property.name} )` : emitExpression(node.left.property) : JSON.stringify(node.left.property.name);\n              return `__zuzu_assign_index( ${object}, ${key}, ${right}, ${node.isWeakWrite ? "true" : "false"}, ( __zuzu_updated ) => ( ${objectTarget} = __zuzu_updated ) )`;\n            }\n            return `${left} = ${right}`;\n          case "+=":\n            return `${left} = __zuzu_add( ${left}, ${right} )`;\n          case "-=":\n            return `${left} = __zuzu_sub( ${left}, ${right} )`;\n          case "*=":\n          case "\\xD7=":\n            return `${left} = __zuzu_mul( ${left}, ${right} )`;\n          case "/=":\n          case "\\xF7=":\n            return `${left} = __zuzu_div( ${left}, ${right} )`;\n          case "%=":\n            return `${left} = __zuzu_mod( ${left}, ${right} )`;\n          case "**=":\n            return `${left} = __zuzu_pow( ${left}, ${right} )`;\n          case "_=":\n            return `${left} = __zuzu_concat( ${left}, ${right} )`;\n          case "?:=":\n            return `( ${left} == null ? ( ${left} = ${right} ) : ${left} )`;\n          default:\n            throw new UnsupportedSyntaxError(`Unsupported assignment operator ${node.operator}`);\n        }\n      }\n      function emitAssignmentTarget(node) {\n        if (node && node.type === "MemberExpression" && node.computed && node.property) {\n          if (node.property.type === "BraceIdentifier") {\n            const object = emitExpression(node.object);\n            return `${object}[__zuzu_resolve_brace_key( ${object}, ${JSON.stringify(node.property.name)}, () => ${node.property.name} )]`;\n          }\n          return `${emitExpression(node.object)}[${emitExpression(node.property)}]`;\n        }\n        return emitExpression(node);\n      }\n      function emitSliceExpression(node) {\n        const object = emitExpression(node.object);\n        const start = node.start ? emitExpression(node.start) : "0";\n        const length = node.length == null ? "null" : emitExpression(node.length);\n        return `__zuzu_get_slice( ${object}, ${start}, ${length} )`;\n      }\n      function unwrapGroupedExpression(node) {\n        let current = node;\n        while (current && current.type === "GroupedExpression") {\n          current = current.expression;\n        }\n        return current;\n      }\n      function emitRegexReplaceExpression(node) {\n        const leftTarget = unwrapGroupedExpression(node.left);\n        if (leftTarget && leftTarget.type === "BinaryExpression" && ["@", "@@", "@?"].includes(leftTarget.operator)) {\n          const mode = leftTarget.operator === "@@" ? "all" : leftTarget.operator === "@?" ? "maybe" : "first";\n          const pattern2 = node.pattern.type === "RegExpLiteral" ? emitExpression(node.pattern) : `__zuzu_to_regexp( ${emitExpression(node.pattern)} )`;\n          return `__zuzu_path_assign( ${emitExpression(leftTarget.left)}, ${emitExpression(leftTarget.right)}, [ ${pattern2}, ( m ) => ${emitExpression(node.replacement)} ], "${mode}", "~=" )`;\n        }\n        const left = emitExpression(node.left);\n        const pattern = node.pattern.type === "RegExpLiteral" ? emitExpression(node.pattern) : `__zuzu_to_regexp( ${emitExpression(node.pattern)} )`;\n        const replacement = emitExpression(node.replacement);\n        return `${left} = __zuzu_regex_replace( ${left}, ${pattern}, ( ...__zuzu_match_args ) => { const m = __zuzu_match_args; return ${replacement}; } )`;\n      }\n      function emitRefExpression(node) {\n        const arg = unwrapGroupedExpression(node.argument);\n        if (arg && arg.type === "BinaryExpression" && ["@", "@@", "@?"].includes(arg.operator)) {\n          const mode = arg.operator === "@@" ? "all" : arg.operator === "@?" ? "maybe" : "first";\n          return `__zuzu_path_ref( ${emitExpression(arg.left)}, ${emitExpression(arg.right)}, "${mode}" )`;\n        }\n        if (arg.type === "SliceExpression") {\n          return `__zuzu_ref_slice( ${emitExpression(arg.object)}, ${arg.start ? emitExpression(arg.start) : "0"}, ${arg.length == null ? "null" : emitExpression(arg.length)} )`;\n        }\n        if (arg.type === "MemberExpression") {\n          if (arg.computed) {\n            if (arg.property.type === "BraceIdentifier") {\n              return `__zuzu_ref_index( ${emitExpression(arg.object)}, ${JSON.stringify(arg.property.name)} )`;\n            }\n            return `__zuzu_ref_index( ${emitExpression(arg.object)}, ${emitExpression(arg.property)} )`;\n          }\n          return `__zuzu_ref_key( ${emitExpression(arg.object)}, ${JSON.stringify(arg.property.name)} )`;\n        }\n        throw new UnsupportedSyntaxError("Unsupported reference target");\n      }\n      function emitExpressionBlock(block, options = {}) {\n        return withEmitContext(options, () => {\n          if (!block || !Array.isArray(block.body) || block.body.length === 0) {\n            return options.boxResult ? "return { __zuzu_await_block_value: null };" : "return null;";\n          }\n          const expressionDeclaredNames = collectExpressionDeclaredNames(block.body);\n          const scopedOptions = {\n            ...options,\n            weakStorageNames: /* @__PURE__ */ new Set([\n              ...options.weakStorageNames || [],\n              ...collectWeakDeclaredNames(block.body)\n            ]),\n            scopeNames: /* @__PURE__ */ new Set([\n              ...options.scopeNames || [],\n              ...expressionDeclaredNames\n            ])\n          };\n          return withEmitContext(scopedOptions, () => {\n            const lines = [];\n            const prelude = emitPredeclaredNames(expressionDeclaredNames);\n            if (prelude) {\n              lines.push(prelude);\n            }\n            const lastIndex = block.body.length - 1;\n            for (let i = 0; i < block.body.length; i++) {\n              const stmt = block.body[i];\n              if (i === lastIndex) {\n                lines.push(emitExpressionTail(stmt, scopedOptions));\n              } else {\n                lines.push(emitExpressionInnerStatement(stmt, scopedOptions));\n              }\n            }\n            return lines.join("\\n");\n          });\n        });\n      }\n      function emitExpressionInnerStatement(stmt, options = {}) {\n        if (options.nonLocalReturn && stmt.type === "ReturnStatement") {\n          return emitDoReturnStatement(stmt);\n        }\n        return emitStatement(stmt, options);\n      }\n      function emitExpressionTail(stmt, options = {}) {\n        if (stmt.type === "ExpressionStatement") {\n          const value = emitExpression(stmt.expression);\n          return options.boxResult ? `return { __zuzu_await_block_value: ${value} };` : `return ${value};`;\n        }\n        if (stmt.type === "ReturnStatement") {\n          return options.nonLocalReturn ? emitDoReturnStatement(stmt) : emitStatement(stmt);\n        }\n        if (stmt.type === "BlockStatement") {\n          return emitExpressionBlock(stmt, options);\n        }\n        if (stmt.type === "IfStatement") {\n          const prefix = stmt.declaration ? `${emitStatement(stmt.declaration, options)}\n` : "";\n          const alternate = stmt.alternate ? emitExpressionTail(stmt.alternate, options) : options.boxResult ? "return { __zuzu_await_block_value: null };" : "return null;";\n          return `${prefix}if ( __zuzu_truthy( ${emitExpression(stmt.test)} ) ) { ${emitExpressionBlock(stmt.consequent, options)} } else { ${alternate} }`;\n        }\n        return emitStatement(stmt, options);\n      }\n      function emitDoReturnStatement(stmt) {\n        return `throw { __zuzu_nonlocal_return: true, value: ${stmt.argument ? emitExpression(stmt.argument) : "null"} };`;\n      }\n      function emitTryExpression(node) {\n        const options = currentEmitContext();\n        const handlers = node.handlers || [];\n        let catchBody = "throw __zuzu_err;";\n        if (handlers.length > 0) {\n          const branches = handlers.map((handler, index) => {\n            const cond = handler.typeName === "Exception" || handler.typeName === "Any" ? "true" : `__zuzu_instanceof( __zuzu_err, ${handler.typeName} )`;\n            const prefix = index === 0 ? `if ( ${cond} )` : `else if ( ${cond} )`;\n            return `${prefix} { let ${handler.paramName} = __zuzu_err; ${emitExpressionBlock(handler.body, options)} }`;\n          });\n          catchBody = `if ( __zuzu_err && __zuzu_err.__zuzu_nonlocal_return ) { throw __zuzu_err; } __zuzu_err = __zuzu_normalize_exception( __zuzu_err ); ${branches.join(" ")} else { throw __zuzu_err; }`;\n        }\n        return `( ${options.asyncContext ? "async " : ""}() => { try { ${emitExpressionBlock(node.block, options)} } catch ( __zuzu_err ) { ${catchBody} } } )()`;\n      }\n      function emitDoExpression(node) {\n        return `( () => { ${emitExpressionBlock(node.block, {\n          ...currentEmitContext(),\n          nonLocalReturn: true\n        })} } )()`;\n      }\n      function emitCallArguments(args) {\n        const positional = [];\n        const named = [];\n        for (const arg of args) {\n          if (arg.type === "NamedArgument") {\n            named.push(arg);\n          } else {\n            positional.push(emitExpression(arg));\n          }\n        }\n        if (named.length > 0) {\n          positional.push(`__zuzu_temp_pairlist( [ ${named.map((arg) => emitExpression(arg)).join(", ")} ] )`);\n        }\n        return positional;\n      }\n      function emitCallArgumentList(args) {\n        if (!callArgumentsHaveSpread(args)) {\n          return emitCallArguments(args).join(", ");\n        }\n        return `...${emitSpreadCallArguments(args)}`;\n      }\n      function emitCallArgumentArray(args) {\n        if (args.length === 0) {\n          return "[]";\n        }\n        if (!callArgumentsHaveSpread(args)) {\n          return `[ ${emitCallArguments(args).join(", ")} ]`;\n        }\n        return emitSpreadCallArguments(args);\n      }\n      function callArgumentsHaveSpread(args) {\n        return args.some((arg) => arg.type === "SpreadArgument");\n      }\n      function emitSpreadCallArguments(args) {\n        return `__zuzu_spread_call_args( [ ${args.map(emitSpreadCallArgumentPart).join(", ")} ] )`;\n      }\n      function emitSpreadCallArgumentPart(arg) {\n        if (arg.type === "SpreadArgument") {\n          return `__zuzu_snapshot_spread_arg( ${emitExpression(arg.argument)} )`;\n        }\n        if (arg.type === "NamedArgument") {\n          return `{ type: "named", value: ${emitExpression(arg)} }`;\n        }\n        return `{ type: "positional", value: ${emitExpression(arg)} }`;\n      }\n      function emitEvalCall(args) {\n        if (callArgumentsHaveSpread(args)) {\n          return `eval( __zuzu_prepare_eval_call_args( ${emitSpreadCallArguments(args)} ) )`;\n        }\n        const positional = [];\n        const named = [];\n        for (const arg of args) {\n          if (arg.type === "NamedArgument") {\n            named.push(arg);\n          } else {\n            positional.push(arg);\n          }\n        }\n        const source = positional.length > 0 ? emitExpression(positional[0]) : \'""\';\n        const namedArgs = named.length > 0 ? `__zuzu_pairlist_literal( [ ${named.map((arg) => emitExpression(arg)).join(", ")} ] )` : "null";\n        return `eval( __zuzu_prepare_eval( ${source}, ${namedArgs} ) )`;\n      }\n      module2.exports = {\n        emitProgram\n      };\n      function programNeedsAsyncWrapper(ast) {\n        return ast.body.some((stmt) => nodeContainsAsyncControl(stmt));\n      }\n      function programContainsImport(ast) {\n        return ast.body.some((stmt) => stmt && stmt.type === "ImportDeclaration");\n      }\n      function nodeContainsAsyncControl(node) {\n        if (!node || typeof node !== "object") {\n          return false;\n        }\n        if (node.type === "AwaitExpression" || node.type === "SpawnExpression") {\n          return true;\n        }\n        if (["FunctionDeclaration", "FunctionExpression", "MethodDeclaration"].includes(node.type)) {\n          return false;\n        }\n        for (const value of Object.values(node)) {\n          if (Array.isArray(value)) {\n            if (value.some(nodeContainsAsyncControl)) {\n              return true;\n            }\n          } else if (nodeContainsAsyncControl(value)) {\n            return true;\n          }\n        }\n        return false;\n      }\n    }\n  });\n\n  // lib/transpiler-new/validate-bindings.js\n  var require_validate_bindings = __commonJS({\n    "lib/transpiler-new/validate-bindings.js"(exports2, module2) {\n      "use strict";\n      var { TranspilerSyntaxError } = require_errors();\n      var Scope = class {\n        constructor(parent = null) {\n          this.parent = parent;\n          this.bindings = /* @__PURE__ */ new Map();\n        }\n        declare(name2, mutable, node) {\n          if (!name2) {\n            return;\n          }\n          if (this.bindings.has(name2)) {\n            throw syntaxError(`Redeclaration of \'${name2}\' in the same scope`, node);\n          }\n          this.bindings.set(name2, { mutable, bodylessFunction: false });\n        }\n        declareFunction(node) {\n          const name2 = node.id && node.id.name;\n          if (!name2) {\n            return;\n          }\n          const existing = this.bindings.get(name2);\n          if (existing && existing.bodylessFunction && !node.isPredeclared) {\n            existing.bodylessFunction = false;\n            return;\n          }\n          if (existing) {\n            throw syntaxError(`Redeclaration of \'${name2}\' in the same scope`, node);\n          }\n          this.bindings.set(name2, {\n            mutable: false,\n            bodylessFunction: node.isPredeclared === true\n          });\n        }\n        lookup(name2) {\n          if (this.bindings.has(name2)) {\n            return this.bindings.get(name2);\n          }\n          return this.parent ? this.parent.lookup(name2) : null;\n        }\n      };\n      function tokenFor(node) {\n        const start = node && node.loc && node.loc.start;\n        if (!start) {\n          return null;\n        }\n        return {\n          line: start.line,\n          column: start.column\n        };\n      }\n      function syntaxError(message, node) {\n        return new TranspilerSyntaxError(message, tokenFor(node));\n      }\n      function validateBindings(ast) {\n        const scope = new Scope();\n        for (const name2 of [\n          "__argc__",\n          "__file__",\n          "__global__",\n          "__system__"\n        ]) {\n          scope.declare(name2, false, null);\n        }\n        validateStatements(ast.body || [], scope);\n        return ast;\n      }\n      function validateStatements(statements, scope) {\n        for (const statement of statements || []) {\n          validateStatement(statement, scope);\n        }\n      }\n      function validateStatement(node, scope) {\n        if (!node) {\n          return;\n        }\n        switch (node.type) {\n          case "BlockStatement":\n            validateStatements(node.body, new Scope(scope));\n            return;\n          case "VariableDeclaration":\n            validateExpression(node.init, scope);\n            scope.declare(node.id && node.id.name, node.kind !== "const", node);\n            return;\n          case "VariableUnpackDeclaration":\n            validateVariableUnpackDeclaration(node, scope);\n            return;\n          case "FunctionDeclaration":\n            scope.declareFunction(node);\n            if (!node.isPredeclared) {\n              validateFunctionBody(node, scope);\n            }\n            return;\n          case "ClassDeclaration":\n            scope.declare(node.id && node.id.name, false, node);\n            validateClassBody(node, scope);\n            return;\n          case "TraitDeclaration":\n            scope.declare(node.id && node.id.name, false, node);\n            validateTraitBody(node, scope);\n            return;\n          case "ForInStatement":\n            validateExpression(node.iterable, scope);\n            validateForBody(node, scope);\n            return;\n          case "ExpressionStatement":\n            validateExpression(node.expression, scope);\n            return;\n          default:\n            validateChildNodes(node, scope);\n        }\n      }\n      function validateVariableUnpackDeclaration(node, scope) {\n        validateExpression(node.init, scope);\n        const names = /* @__PURE__ */ new Set();\n        for (const entry of bindingEntriesForPattern(node.pattern)) {\n          if (names.has(entry.name)) {\n            throw syntaxError(\n              `Duplicate unpacked binding \'${entry.name}\' in declaration`,\n              entry\n            );\n          }\n          names.add(entry.name);\n        }\n        for (const entry of bindingEntriesForPattern(node.pattern)) {\n          validateExpression(entry.key, scope);\n          validateExpression(entry.defaultValue, scope);\n        }\n        for (const entry of bindingEntriesForPattern(node.pattern)) {\n          scope.declare(entry.name, node.kind !== "const", entry);\n        }\n      }\n      function bindingEntriesForPattern(pattern) {\n        return pattern && Array.isArray(pattern.entries) ? pattern.entries : [];\n      }\n      function validateForBody(node, scope) {\n        const loopScope = new Scope(scope);\n        loopScope.declare(\n          node.left && node.left.name,\n          node.kind !== "const",\n          node.left || node\n        );\n        validateStatement(node.body, loopScope);\n        validateStatement(node.elseBlock, new Scope(scope));\n      }\n      function validateFunctionBody(node, parentScope) {\n        const scope = new Scope(parentScope);\n        for (const param of node.params || []) {\n          if (param.type === "Parameter") {\n            scope.declare(param.name, true, param);\n          } else if (param.type === "SpecialParameter") {\n            scope.declare(param.leadName, true, param);\n            scope.declare(param.name, true, param);\n          }\n        }\n        validateStatements(node.body && node.body.body, scope);\n      }\n      function validateClassBody(node, scope) {\n        const classScope = new Scope(scope);\n        const methodNames = /* @__PURE__ */ new Map();\n        validateExpression(node.base, scope);\n        for (const trait of node.traits || []) {\n          validateExpression(trait, scope);\n        }\n        for (const entry of node.body || []) {\n          if (entry.type === "FieldDeclaration") {\n            validateExpression(entry.defaultValue, classScope);\n          } else if (entry.type === "MethodDeclaration") {\n            recordMethodDeclaration(methodNames, entry);\n            if (!entry.isPredeclared) {\n              validateFunctionBody(entry, classScope);\n            }\n          } else {\n            validateStatement(entry, classScope);\n          }\n        }\n      }\n      function validateTraitBody(node, scope) {\n        const methodNames = /* @__PURE__ */ new Map();\n        for (const entry of node.body || []) {\n          recordMethodDeclaration(methodNames, entry);\n          if (!entry.isPredeclared) {\n            validateFunctionBody(entry, scope);\n          }\n        }\n      }\n      function recordMethodDeclaration(methodNames, node) {\n        const name2 = node.id && node.id.name;\n        const existing = methodNames.get(name2);\n        if (existing && existing.bodyless && !node.isPredeclared) {\n          existing.bodyless = false;\n          return;\n        }\n        if (existing) {\n          throw syntaxError(`Redeclaration of \'${name2}\' in the same scope`, node);\n        }\n        methodNames.set(name2, { bodyless: node.isPredeclared === true });\n      }\n      function validateExpression(node, scope) {\n        if (!node) {\n          return;\n        }\n        switch (node.type) {\n          case "AssignmentExpression":\n            validateExpression(node.right, scope);\n            requireValidAssignmentTarget(node.left);\n            if (node.left && node.left.type === "Identifier") {\n              requireMutable(node.left, scope);\n            } else {\n              validateExpression(node.left, scope);\n            }\n            return;\n          case "UpdateExpression":\n            requireValidAssignmentTarget(node.argument);\n            if (node.argument && node.argument.type === "Identifier") {\n              requireMutable(node.argument, scope);\n            } else {\n              validateExpression(node.argument, scope);\n            }\n            return;\n          case "UnaryExpression":\n            if (node.operator === "++" || node.operator === "--") {\n              requireValidAssignmentTarget(node.argument);\n              if (node.argument && node.argument.type === "Identifier") {\n                requireMutable(node.argument, scope);\n              } else {\n                validateExpression(node.argument, scope);\n              }\n              return;\n            }\n            validateChildNodes(node, scope);\n            return;\n          case "RefExpression":\n            requireValidAssignmentTarget(node.argument);\n            validateExpression(node.argument, scope);\n            return;\n          case "FunctionExpression":\n            validateFunctionBody(node, scope);\n            return;\n          case "LetExpression":\n            validateExpression(node.init, scope);\n            scope.declare(node.id && node.id.name, node.kind !== "const", node);\n            return;\n          default:\n            validateChildNodes(node, scope);\n        }\n      }\n      function requireValidAssignmentTarget(node) {\n        const target = unwrapGroupedExpression(node);\n        if (!target) {\n          throw syntaxError("Invalid assignment target", node);\n        }\n        if (target.type === "Identifier" || target.type === "SliceExpression") {\n          return;\n        }\n        if (target.type === "MemberExpression" && target.computed) {\n          return;\n        }\n        if (target.type === "BinaryExpression" && ["@", "@@", "@?"].includes(target.operator)) {\n          return;\n        }\n        throw syntaxError("Invalid assignment target", node);\n      }\n      function unwrapGroupedExpression(node) {\n        let current = node;\n        while (current && current.type === "GroupedExpression") {\n          current = current.expression;\n        }\n        return current;\n      }\n      function requireMutable(node, scope) {\n        const binding = scope.lookup(node.name);\n        if (binding && !binding.mutable) {\n          throw syntaxError(`Cannot assign to const \'${node.name}\' (compile-time)`, node);\n        }\n      }\n      function validateChildNodes(node, scope) {\n        if (!node || typeof node !== "object") {\n          return;\n        }\n        for (const value of Object.values(node)) {\n          if (!value) {\n            continue;\n          }\n          if (Array.isArray(value)) {\n            for (const item of value) {\n              validateChildNode(item, scope);\n            }\n          } else {\n            validateChildNode(value, scope);\n          }\n        }\n      }\n      function validateChildNode(node, scope) {\n        if (!node || typeof node !== "object" || typeof node.type !== "string") {\n          return;\n        }\n        if (node.type.endsWith("Statement") || node.type.endsWith("Declaration")) {\n          validateStatement(node, scope);\n        } else {\n          validateExpression(node, scope);\n        }\n      }\n      module2.exports = {\n        validateBindings\n      };\n    }\n  });\n\n  // lib/transpiler-new/index.js\n  var require_transpiler_new = __commonJS({\n    "lib/transpiler-new/index.js"(exports2, module2) {\n      "use strict";\n      var { stripPod } = require_transpiler_utils();\n      var { tokenize } = require_lexer();\n      var { parse } = require_parser();\n      var { emitProgram } = require_codegen();\n      var { validateBindings } = require_validate_bindings();\n      function transpileWithoutFallback(source, options = {}) {\n        const preprocessed = stripPod(String(source ?? ""));\n        const tokens = tokenize(preprocessed);\n        const ast = parse(tokens);\n        validateBindings(ast);\n        return emitProgram(ast, { ...options, marshalSource: preprocessed });\n      }\n      function transpile(source, options = {}) {\n        return transpileWithoutFallback(source, options);\n      }\n      module2.exports = {\n        tokenize,\n        parse,\n        transpileWithoutFallback,\n        transpile\n      };\n    }\n  });\n\n  // lib/transpiler.js\n  var require_transpiler = __commonJS({\n    "lib/transpiler.js"(exports2, module2) {\n      "use strict";\n      var { stripPod } = require_transpiler_utils();\n      var { transpile: transpileNew } = require_transpiler_new();\n      var DEFAULT_TRANSPILER = "new-only";\n      var VALID_TRANSPILERS = /* @__PURE__ */ new Set([DEFAULT_TRANSPILER]);\n      function normalizeTranspilerName(value) {\n        if (value == null || value === "") {\n          return DEFAULT_TRANSPILER;\n        }\n        const name2 = String(value).trim().toLowerCase();\n        if (!VALID_TRANSPILERS.has(name2)) {\n          throw new Error(\n            `Unknown transpiler: ${value}. Expected: ${DEFAULT_TRANSPILER}`\n          );\n        }\n        return name2;\n      }\n      function transpile(source, options = {}) {\n        normalizeTranspilerName(options.transpiler);\n        return transpileNew(source, options);\n      }\n      module2.exports = {\n        DEFAULT_TRANSPILER,\n        VALID_TRANSPILERS,\n        normalizeTranspilerName,\n        transpile,\n        stripPod\n      };\n    }\n  });\n\n  // lib/host/capabilities.js\n  var require_capabilities = __commonJS({\n    "lib/host/capabilities.js"(exports2, module2) {\n      "use strict";\n      var MODULE_CAPABILITIES = {\n        "std/io": ["fs"],\n        "std/io/socks": ["fs", "net"],\n        "std/proc": ["proc"],\n        "std/db": ["db"],\n        "std/clib": ["clib"],\n        "std/gui/objects": ["gui"],\n        "std/net/dns": ["net"],\n        "std/net/http": ["http"],\n        "std/worker": ["worker"],\n        "perl": ["perl"],\n        "javascript": ["js"]\n      };\n      var BROWSER_SAFE_MODULES = /* @__PURE__ */ new Set([\n        "std/string",\n        "std/time",\n        "std/data/json",\n        "std/data/xml",\n        "std/net/http",\n        "std/net/smtp",\n        "std/secure",\n        "std/math",\n        "std/eval",\n        "std/colour",\n        "std/gui",\n        "std/gui/dialogue",\n        "std/gui/objects",\n        "std/tui"\n      ]);\n      function capabilitiesForModule(moduleName) {\n        for (const [prefix, capabilities2] of Object.entries(MODULE_CAPABILITIES)) {\n          if (moduleName === prefix || moduleName.startsWith(`${prefix}/`)) {\n            return capabilities2.slice();\n          }\n        }\n        return [];\n      }\n      module2.exports = {\n        MODULE_CAPABILITIES,\n        BROWSER_SAFE_MODULES,\n        capabilitiesForModule\n      };\n    }\n  });\n\n  // lib/execution-metadata.js\n  var require_execution_metadata = __commonJS({\n    "lib/execution-metadata.js"(exports2, module2) {\n      "use strict";\n      var compiledSources = /* @__PURE__ */ new Map();\n      function setCompiledSource(filename, source) {\n        if (typeof filename === "string" && typeof source === "string") {\n          compiledSources.set(filename, source);\n        }\n      }\n      function getCompiledSource(filename) {\n        return compiledSources.get(filename) || null;\n      }\n      module2.exports = {\n        getCompiledSource,\n        setCompiledSource\n      };\n    }\n  });\n\n  // modules/std/task.js\n  var require_task = __commonJS({\n    "modules/std/task.js"(exports2, module2) {\n      "use strict";\n      var AsyncLocalStorage = null;\n      try {\n        AsyncLocalStorage = __require("node:async_hooks").AsyncLocalStorage;\n      } catch (_err) {\n      }\n      var Exception = class extends Error {\n        constructor(message = "") {\n          super(String(message ?? ""));\n          this.name = "Exception";\n        }\n        to_String() {\n          const name2 = this.name || this.constructor.name || "Exception";\n          const message = String(this.message ?? "");\n          if (message === name2 || message.startsWith(`${name2}:`)) {\n            return message;\n          }\n          return message === "" ? name2 : `${name2}: ${message}`;\n        }\n      };\n      var CancelledException = class extends Exception {\n        constructor(message = "Task cancelled") {\n          super(message);\n          this.name = "CancelledException";\n        }\n      };\n      var TimeoutException = class extends Exception {\n        constructor(message = "timeout") {\n          super(message);\n          this.name = "TimeoutException";\n        }\n      };\n      var ChannelClosedException = class extends Exception {\n        constructor(message = "send on closed channel") {\n          super(message);\n          this.name = "ChannelClosedException";\n        }\n      };\n      var taskStorage = AsyncLocalStorage ? new AsyncLocalStorage() : null;\n      var fallbackCurrentTask = null;\n      var debugLevel = 0;\n      var nextTaskId = 1;\n      var activeTasks = /* @__PURE__ */ new Map();\n      var traceEvents = [];\n      var callsiteStack = [];\n      function globalTimerRoot() {\n        if (typeof globalThis !== "undefined") {\n          return globalThis;\n        }\n        if (typeof global !== "undefined") {\n          return global;\n        }\n        return {};\n      }\n      function safeSetTimeout(callback, delay) {\n        const root = globalTimerRoot();\n        return root.setTimeout.call(root, callback, delay);\n      }\n      function safeClearTimeout(timer) {\n        const root = globalTimerRoot();\n        return root.clearTimeout.call(root, timer);\n      }\n      function safeQueueMicrotask(callback) {\n        const root = globalTimerRoot();\n        if (typeof root.queueMicrotask === "function") {\n          return root.queueMicrotask.call(root, callback);\n        }\n        return safeSetTimeout(callback, 0);\n      }\n      function currentTask() {\n        return taskStorage ? taskStorage.getStore() : fallbackCurrentTask;\n      }\n      function runWithTask(task2, fn2) {\n        if (taskStorage) {\n          return taskStorage.run(task2, fn2);\n        }\n        const previous = fallbackCurrentTask;\n        fallbackCurrentTask = task2;\n        try {\n          return fn2();\n        } finally {\n          fallbackCurrentTask = previous;\n        }\n      }\n      function normalizeException(value, ExceptionClass = Exception) {\n        if (value instanceof Error) {\n          return value;\n        }\n        return new ExceptionClass(value == null ? "" : String(value));\n      }\n      function currentCallsite() {\n        return callsiteStack.length > 0 ? callsiteStack[callsiteStack.length - 1] : null;\n      }\n      function withCallsite(metadata, fn2) {\n        callsiteStack.push(metadata || null);\n        try {\n          return fn2();\n        } finally {\n          callsiteStack.pop();\n        }\n      }\n      function traceTask(event, task2 = null, extra = null) {\n        if (debugLevel <= 0) {\n          return null;\n        }\n        const record = {\n          event,\n          task_id: task2 ? task2._id : null,\n          parent_task_id: task2 ? task2._parentId : null,\n          name: task2 ? task2._name : null,\n          status: task2 ? task2._status : null,\n          file: task2 ? task2._file : null,\n          line: task2 ? task2._line : null\n        };\n        if (extra && typeof extra === "object") {\n          Object.assign(record, extra);\n        }\n        traceEvents.push(record);\n        return record;\n      }\n      function cleanupTask(task2) {\n        if (!task2 || !task2.done()) {\n          return;\n        }\n        activeTasks.delete(task2._id);\n        traceTask("cleanup", task2);\n      }\n      var Task = class _Task {\n        constructor(executor = null, options = {}) {\n          const parent = currentTask();\n          const callsite = currentCallsite();\n          this._id = nextTaskId++;\n          this._parentId = options.parentTaskId != null ? options.parentTaskId : parent ? parent._id : null;\n          this._name = options.name || "<task>";\n          this._file = options.file || (callsite ? callsite.file : null) || null;\n          this._line = options.line || (callsite ? callsite.line : null) || null;\n          this._status = options.status || "pending";\n          this._value = void 0;\n          this._reason = null;\n          this._children = /* @__PURE__ */ new Set();\n          this._cancelHook = typeof options.cancel === "function" ? options.cancel : null;\n          this._pollHook = typeof options.poll === "function" ? options.poll : null;\n          activeTasks.set(this._id, this);\n          traceTask("schedule", this);\n          this._promise = new Promise((resolve, reject) => {\n            this._resolve = (value) => {\n              if (this.done()) {\n                return;\n              }\n              this._status = "fulfilled";\n              this._value = value;\n              traceTask("fulfill", this);\n              resolve(value);\n              cleanupTask(this);\n            };\n            this._reject = (err, forcedStatus = null) => {\n              if (this.done()) {\n                return;\n              }\n              this._status = forcedStatus || (err instanceof CancelledException ? "cancelled" : "rejected");\n              this._reason = err;\n              traceTask(this._status === "cancelled" ? "cancel" : "reject", this);\n              reject(err);\n              cleanupTask(this);\n            };\n          });\n          this._promise.catch(() => {\n          });\n          if (executor) {\n            safeQueueMicrotask(() => {\n              if (this.done()) {\n                return;\n              }\n              this._status = options.status || "running";\n              traceTask("start", this);\n              runWithTask(this, async () => {\n                try {\n                  this._resolve(await executor());\n                } catch (err) {\n                  this._reject(err);\n                }\n              });\n            });\n          }\n        }\n        static resolved(value = null) {\n          const task2 = new _Task();\n          task2._resolve(value);\n          return task2;\n        }\n        static failed(value) {\n          const task2 = new _Task();\n          task2._reject(normalizeException(value));\n          return task2;\n        }\n        static from(value) {\n          if (value instanceof _Task) {\n            return value;\n          }\n          if (value && typeof value.then === "function") {\n            const task2 = new _Task();\n            Promise.resolve(value).then(\n              (result) => task2._resolve(result),\n              (err) => task2._reject(err)\n            );\n            return task2;\n          }\n          return _Task.resolved(value);\n        }\n        then(resolve, reject) {\n          return this._promise.then(resolve, reject);\n        }\n        catch(reject) {\n          return this._promise.catch(reject);\n        }\n        finally(callback) {\n          return this._promise.finally(callback);\n        }\n        status() {\n          return this._status;\n        }\n        id() {\n          return this._id;\n        }\n        parent_id() {\n          return this._parentId;\n        }\n        name() {\n          return this._name;\n        }\n        is_done() {\n          return this.done();\n        }\n        done() {\n          return ["fulfilled", "rejected", "cancelled"].includes(this._status) ? 1 : 0;\n        }\n        poll() {\n          if (!this.done() && this._pollHook) {\n            try {\n              this._pollHook();\n            } catch (err) {\n              this._reject(err);\n            }\n          }\n          return this.done();\n        }\n        to_String() {\n          return `[Task ${this._status}]`;\n        }\n        cancel(reason = null) {\n          if (this.done()) {\n            return this;\n          }\n          const err = normalizeException(\n            reason == null ? "Task cancelled" : reason,\n            CancelledException\n          );\n          this._reason = err;\n          for (const child of this._children) {\n            if (child && typeof child.cancel === "function") {\n              child.cancel(err);\n            }\n          }\n          if (this._cancelHook) {\n            try {\n              this._cancelHook(err);\n            } catch (_err) {\n            }\n          }\n          this._reject(err, "cancelled");\n          return this;\n        }\n        _track(child) {\n          if (child instanceof _Task) {\n            this._children.add(child);\n          }\n        }\n        _untrack(child) {\n          if (child instanceof _Task) {\n            this._children.delete(child);\n          }\n        }\n      };\n      Object.defineProperty(Task.prototype, "__zuzu_type_name", {\n        value: "Task",\n        enumerable: false,\n        configurable: true,\n        writable: true\n      });\n      async function awaitValueWithParent(value, parent) {\n        if (parent && parent.status() === "cancelled") {\n          throw parent._reason || new CancelledException();\n        }\n        const task2 = Task.from(value);\n        if (parent) {\n          parent._track(task2);\n        }\n        try {\n          return await task2;\n        } finally {\n          if (parent) {\n            parent._untrack(task2);\n            if (parent.status() === "cancelled") {\n              throw parent._reason || new CancelledException();\n            }\n          }\n        }\n      }\n      async function awaitValue(value) {\n        return awaitValueWithParent(value, currentTask());\n      }\n      async function awaitBlock(value) {\n        const parent = currentTask();\n        const boxedValue = value && typeof value.then === "function" ? await value : value;\n        const resolvedValue = boxedValue && typeof boxedValue === "object" && Object.prototype.hasOwnProperty.call(boxedValue, "__zuzu_await_block_value") ? boxedValue.__zuzu_await_block_value : boxedValue;\n        if (!(resolvedValue instanceof Task)) {\n          throw new Exception("await block must return a Task");\n        }\n        return awaitValueWithParent(resolvedValue, parent);\n      }\n      function awaitValueSync(value) {\n        const task2 = Task.from(value);\n        if (task2.status() === "fulfilled") {\n          return task2._value;\n        }\n        if (task2.status() === "rejected" || task2.status() === "cancelled") {\n          throw task2._reason || new Exception("Task failed");\n        }\n        throw new Exception("cannot synchronously await pending task");\n      }\n      function awaitBlockSync(value) {\n        const resolvedValue = value && typeof value === "object" && Object.prototype.hasOwnProperty.call(value, "__zuzu_await_block_value") ? value.__zuzu_await_block_value : value;\n        if (!(resolvedValue instanceof Task)) {\n          throw new Exception("await block must return a Task");\n        }\n        return awaitValueSync(resolvedValue);\n      }\n      function task(fn2, _metadata = {}) {\n        const callsite = currentCallsite();\n        return new Task(async () => fn2(), {\n          name: _metadata.name || "<async>",\n          file: (callsite ? callsite.file : null) || _metadata.file || null,\n          line: (callsite ? callsite.line : null) || _metadata.line || null\n        });\n      }\n      function taskSync(fn2, _metadata = {}) {\n        const callsite = currentCallsite();\n        const task2 = new Task(null, {\n          name: _metadata.name || "<async>",\n          file: (callsite ? callsite.file : null) || _metadata.file || null,\n          line: (callsite ? callsite.line : null) || _metadata.line || null\n        });\n        task2._status = "running";\n        traceTask("start", task2);\n        try {\n          const value = runWithTask(task2, () => fn2());\n          if (value instanceof Task) {\n            if (value.status() === "fulfilled") {\n              task2._resolve(value._value);\n            } else if (value.status() === "rejected" || value.status() === "cancelled") {\n              task2._reject(value._reason || new Exception("Task failed"));\n            } else {\n              task2._reject(new Exception("cannot synchronously await pending task"));\n            }\n          } else if (value && typeof value.then === "function") {\n            Task.from(value).then(\n              (result) => task2._resolve(result),\n              (err) => task2._reject(err)\n            );\n          } else {\n            task2._resolve(value);\n          }\n        } catch (err) {\n          task2._reject(err);\n        }\n        return task2;\n      }\n      function spawn(fn2, _metadata = {}) {\n        return new Task(async () => fn2(), {\n          status: "running",\n          name: _metadata.name || "<spawn>",\n          file: _metadata.file || (currentCallsite() ? currentCallsite().file : null) || null,\n          line: _metadata.line || (currentCallsite() ? currentCallsite().line : null) || null\n        });\n      }\n      function resolved(value = null) {\n        return Task.resolved(value);\n      }\n      function failed(value) {\n        return Task.failed(value == null ? "Task failed" : value);\n      }\n      function sleep(seconds = 0) {\n        let timer = null;\n        const readyAt = Date.now() + Math.max(0, Number(seconds) || 0) * 1e3;\n        const task2 = new Task(null, {\n          status: "sleeping",\n          name: "sleep",\n          poll() {\n            if (Date.now() >= readyAt) {\n              if (timer != null) {\n                safeClearTimeout(timer);\n                timer = null;\n              }\n              task2._resolve(null);\n            }\n          },\n          cancel() {\n            if (timer != null) {\n              safeClearTimeout(timer);\n              timer = null;\n            }\n          }\n        });\n        timer = safeSetTimeout(() => {\n          timer = null;\n          task2._resolve(null);\n        }, Math.max(0, Number(seconds) || 0) * 1e3);\n        return task2;\n      }\n      function yieldTask() {\n        let timer = null;\n        const task2 = new Task(null, {\n          status: "waiting",\n          name: "yield",\n          cancel() {\n            if (timer != null) {\n              safeClearTimeout(timer);\n              timer = null;\n            }\n          }\n        });\n        timer = safeSetTimeout(() => {\n          timer = null;\n          task2._resolve(null);\n        }, 0);\n        return task2;\n      }\n      function all(values = []) {\n        const tasks = taskItems(values, "all");\n        return new Task(\n          () => new Promise((resolve, reject) => {\n            if (tasks.length === 0) {\n              resolve([]);\n              return;\n            }\n            const results = new Array(tasks.length);\n            let remaining = tasks.length;\n            let settled = false;\n            tasks.forEach((task2, index) => {\n              task2.then(\n                (value) => {\n                  if (settled) {\n                    return;\n                  }\n                  results[index] = value;\n                  remaining--;\n                  if (remaining === 0) {\n                    settled = true;\n                    resolve(results);\n                  }\n                },\n                (err) => {\n                  if (settled) {\n                    return;\n                  }\n                  settled = true;\n                  for (const child of tasks) {\n                    if (child !== task2) {\n                      child.cancel();\n                    }\n                  }\n                  reject(err);\n                }\n              );\n            });\n          }),\n          {\n            status: "waiting",\n            name: "all",\n            cancel(reason) {\n              for (const task2 of tasks) {\n                task2.cancel(reason);\n              }\n            }\n          }\n        );\n      }\n      function race(values = []) {\n        const tasks = taskItems(values, "race");\n        if (tasks.length === 0) {\n          return Task.failed(new Exception("race expects at least one task"));\n        }\n        return new Task(\n          () => new Promise((resolve, reject) => {\n            let settled = false;\n            for (const task2 of tasks) {\n              task2.then(\n                (value) => {\n                  if (settled) {\n                    return;\n                  }\n                  settled = true;\n                  for (const loser of tasks) {\n                    if (loser !== task2) {\n                      loser.cancel(new CancelledException("race loser cancelled"));\n                    }\n                  }\n                  resolve(value);\n                },\n                (err) => {\n                  if (settled) {\n                    return;\n                  }\n                  settled = true;\n                  for (const loser of tasks) {\n                    if (loser !== task2) {\n                      loser.cancel(new CancelledException("race loser cancelled"));\n                    }\n                  }\n                  reject(err);\n                }\n              );\n            }\n          }),\n          {\n            status: "waiting",\n            name: "race",\n            cancel(reason) {\n              for (const task2 of tasks) {\n                task2.cancel(reason);\n              }\n            }\n          }\n        );\n      }\n      function timeout(seconds, value) {\n        if (!(value instanceof Task)) {\n          throw new Exception("timeout expects a Task");\n        }\n        const waited = value;\n        const timeoutError = () => new TimeoutException(`timeout after ${Number(seconds) || 0}s`);\n        let settled = false;\n        let timer = null;\n        return new Task(\n          () => new Promise((resolve, reject) => {\n            timer = safeSetTimeout(() => {\n              if (settled) {\n                return;\n              }\n              settled = true;\n              const err = timeoutError();\n              waited.cancel(err);\n              reject(err);\n            }, Math.max(0, Number(seconds) || 0) * 1e3);\n            waited.then(\n              (result) => {\n                if (settled) {\n                  return;\n                }\n                settled = true;\n                if (timer != null) {\n                  safeClearTimeout(timer);\n                  timer = null;\n                }\n                resolve(result);\n              },\n              (err) => {\n                if (settled) {\n                  return;\n                }\n                settled = true;\n                if (timer != null) {\n                  safeClearTimeout(timer);\n                  timer = null;\n                }\n                reject(err);\n              }\n            );\n          }),\n          {\n            status: "waiting",\n            name: "timeout",\n            cancel(reason) {\n              settled = true;\n              if (timer != null) {\n                safeClearTimeout(timer);\n                timer = null;\n              }\n              waited.cancel(reason);\n            }\n          }\n        );\n      }\n      var Channel = class {\n        constructor() {\n          this._closed = false;\n          this._queue = [];\n          this._receivers = [];\n        }\n        send(value = null) {\n          if (this._closed) {\n            return Task.failed(new ChannelClosedException());\n          }\n          const receiver = this._receivers.shift();\n          if (receiver) {\n            receiver._resolve(value);\n          } else {\n            this._queue.push(value);\n          }\n          return Task.resolved(value);\n        }\n        recv() {\n          if (this._queue.length > 0) {\n            return Task.resolved(this._queue.shift());\n          }\n          if (this._closed) {\n            return Task.resolved(null);\n          }\n          const task2 = new Task(null, {\n            status: "waiting",\n            name: "channel.recv",\n            cancel: () => {\n              this._receivers = this._receivers.filter((item) => item !== task2);\n            }\n          });\n          this._receivers.push(task2);\n          return task2;\n        }\n        close() {\n          this._closed = true;\n          while (this._receivers.length > 0) {\n            this._receivers.shift()._resolve(null);\n          }\n          return null;\n        }\n      };\n      var CancellationToken = class {\n        constructor() {\n          this._cancelled = false;\n          this._reason = null;\n          this._tasks = /* @__PURE__ */ new Set();\n        }\n        cancelled() {\n          return this._cancelled ? 1 : 0;\n        }\n        reason() {\n          return this._reason;\n        }\n        throw_if_cancelled() {\n          if (this._cancelled) {\n            throw this._reason || new CancelledException();\n          }\n          return null;\n        }\n        watch(task2) {\n          if (!(task2 instanceof Task)) {\n            throw new Exception("CancellationToken.watch expects a Task");\n          }\n          if (this._cancelled) {\n            task2.cancel(this._reason);\n          } else {\n            this._tasks.add(task2);\n          }\n          return task2;\n        }\n      };\n      var CancellationSource = class {\n        constructor() {\n          this._token = new CancellationToken();\n        }\n        token() {\n          return this._token;\n        }\n        cancel(reason = null) {\n          if (this._token._cancelled) {\n            return this;\n          }\n          this._token._cancelled = true;\n          this._token._reason = normalizeException(\n            reason == null ? "Task cancelled" : reason,\n            CancelledException\n          );\n          for (const task2 of this._token._tasks) {\n            task2.cancel(this._token._reason);\n          }\n          this._token._tasks.clear();\n          return this;\n        }\n        cancelled() {\n          return this._token.cancelled();\n        }\n        reason() {\n          return this._token.reason();\n        }\n      };\n      function setDebugLevel(level = 0) {\n        debugLevel = Number(level) || 0;\n      }\n      function clearTrace() {\n        traceEvents.length = 0;\n        return null;\n      }\n      function taskTrace() {\n        return traceEvents.map((record) => ({ ...record }));\n      }\n      function activeCount() {\n        for (const task2 of [...activeTasks.values()]) {\n          cleanupTask(task2);\n        }\n        return activeTasks.size;\n      }\n      function traceBlockingOperation(operation, metadata = {}) {\n        const task2 = currentTask();\n        if (!task2 || debugLevel <= 0) {\n          return null;\n        }\n        return traceTask("blocked_operation", task2, {\n          operation: String(operation ?? ""),\n          ...metadata\n        });\n      }\n      function shutdown(reason = null) {\n        for (const task2 of [...activeTasks.values()]) {\n          if (!task2.done()) {\n            task2.cancel(reason == null ? "Task cancelled" : reason);\n          }\n        }\n        traceTask("shutdown", null);\n        return null;\n      }\n      function resetForRun(level = 0) {\n        const previousDebugLevel = debugLevel;\n        debugLevel = 0;\n        shutdown("Task cancelled");\n        debugLevel = Number(level) || 0;\n        traceEvents.length = 0;\n        nextTaskId = 1;\n        fallbackCurrentTask = null;\n        callsiteStack.length = 0;\n        return previousDebugLevel;\n      }\n      function withoutAsyncLocalStorageForTesting(fn2) {\n        const previous = taskStorage;\n        taskStorage = null;\n        try {\n          const result = fn2();\n          if (result && typeof result.then === "function") {\n            return Promise.resolve(result).finally(() => {\n              taskStorage = previous;\n              fallbackCurrentTask = null;\n            });\n          }\n          taskStorage = previous;\n          fallbackCurrentTask = null;\n          return result;\n        } catch (err) {\n          taskStorage = previous;\n          fallbackCurrentTask = null;\n          throw err;\n        }\n      }\n      function taskItems(values, label) {\n        if (!Array.isArray(values)) {\n          throw new Exception("TypeException: task combinator expects Array");\n        }\n        const out = [];\n        for (const value of values) {\n          if (!(value instanceof Task)) {\n            throw new Exception(`${label} expects only Task values`);\n          }\n          out.push(value);\n        }\n        return out;\n      }\n      module2.exports = {\n        Task,\n        Exception,\n        CancelledException,\n        TimeoutException,\n        ChannelClosedException,\n        Channel,\n        CancellationToken,\n        CancellationSource,\n        awaitValue,\n        awaitBlock,\n        awaitValueSync,\n        awaitBlockSync,\n        withCallsite,\n        runWithTask,\n        currentTask,\n        setDebugLevel,\n        clearTrace,\n        taskTrace,\n        activeCount,\n        traceBlockingOperation,\n        shutdown,\n        resetForRun,\n        withoutAsyncLocalStorageForTesting,\n        task,\n        taskSync,\n        spawn,\n        resolved,\n        failed,\n        sleep,\n        yield: yieldTask,\n        all,\n        race,\n        timeout\n      };\n    }\n  });\n\n  // package.json\n  var require_package = __commonJS({\n    "package.json"(exports2, module2) {\n      module2.exports = {\n        name: "zuzu-js",\n        version: "0.6.0",\n        description: "JavaScript runtime, compiler, and browser bundle for ZuzuScript.",\n        main: "lib/zuzu.js",\n        bin: {\n          zuzu: "bin/zuzu",\n          "zuzu-js": "bin/zuzu-js",\n          "zuzu-js-compile": "bin/zuzu-js-compile",\n          "zuzu-js-electron": "bin/zuzu-js-electron"\n        },\n        files: [\n          "bin/",\n          "dist/zuzu-browser.js",\n          "dist/zuzu-browser-worker.js",\n          "lib/",\n          "modules/",\n          "stdlib/modules/"\n        ],\n        directories: {\n          example: "examples",\n          lib: "lib",\n          test: "test"\n        },\n        scripts: {\n          "electron:demo": "electron bin/zuzu-js-electron docs/examples/09_gui_dialogue_demo.zzs",\n          test: "node test/cli.js && node test/argument-spread.js && node test/default-operator.js && node test/declaration-unpacking.js && node test/collection-copy.js && node test/std-marshal-cbor.js && node test/std-marshal-data-graph.js && node test/std-marshal-user-object.js && node test/std-marshal-code-table.js && node test/async-parity.js && node test/browser-stdlib-generator.js && node test/browser-gui.js && node test/electron-gui.js && node test/electron-renderer.js && node test/electron-packaging.js",\n          "test:electron": "node test/electron-gui.js && node test/electron-renderer.js && node test/electron-packaging.js"\n        },\n        keywords: [\n          "zuzu",\n          "zuzuscript",\n          "language",\n          "runtime",\n          "compiler"\n        ],\n        author: "",\n        license: "Artistic-1.0 OR GPL-2.0-or-later",\n        repository: {\n          type: "git",\n          url: "git+ssh://git@github.com/zuzuscript/zuzu-js.git"\n        },\n        bugs: {\n          url: "https://github.com/zuzuscript/zuzu-js/issues"\n        },\n        homepage: "https://zuzulang.org/",\n        engines: {\n          node: ">=16"\n        },\n        dependencies: {\n          "@std-uritemplate/std-uritemplate": "^2.0.10",\n          "@xmldom/xmldom": "^0.9.10",\n          "adm-zip": "^0.5.17",\n          "better-sqlite3": "^11.10.0",\n          "cbor-x": "^1.6.4",\n          cborg: "^5.1.1",\n          compressjs: "^1.0.3",\n          "js-yaml": "^4.1.1",\n          koffi: "^2.16.1",\n          mysql2: "^3.22.3",\n          "node-forge": "^1.4.0",\n          pg: "^8.20.0",\n          xpath: "^0.0.34"\n        },\n        devDependencies: {\n          electron: "^41.3.0"\n        }\n      };\n    }\n  });\n\n  // modules/std/io.js\n  var require_io = __commonJS({\n    "modules/std/io.js"(exports2, module2) {\n      "use strict";\n      var fs = __require("node:fs");\n      var os = __require("node:os");\n      var path = __require("node:path");\n      var { BinaryString: BinaryString2 } = require_runtime_helpers();\n      var { Task, traceBlockingOperation } = require_task();\n      var runtimePolicy2 = {};\n      function makeTempFilePath() {\n        for (let attempt = 0; attempt < 1e3; attempt++) {\n          const nonce = `${process.pid}-${Date.now()}-${attempt}-${Math.random().toString(36).slice(2)}`;\n          const file = path.join(os.tmpdir(), `zuzu-js-${nonce}.tmp`);\n          let fd = null;\n          try {\n            fd = fs.openSync(file, "wx");\n            return file;\n          } catch (err) {\n            if (err && err.code === "EEXIST") {\n              continue;\n            }\n            throw err;\n          } finally {\n            if (fd !== null) {\n              fs.closeSync(fd);\n            }\n          }\n        }\n        throw new Error("IOError: could not create temporary file");\n      }\n      function typeName2(value) {\n        if (value == null) {\n          return "Null";\n        }\n        if (typeof value === "string") {\n          return "String";\n        }\n        if (value.bytes instanceof Uint8Array) {\n          return "BinaryString";\n        }\n        return value.constructor && value.constructor.name ? value.constructor.name : typeof value;\n      }\n      function bool(value) {\n        return value ? 1 : 0;\n      }\n      function formatSizeHuman(size) {\n        const units = ["B", "KB", "MB", "GB", "TB"];\n        let value = Number(size);\n        let unit = 0;\n        while (value >= 1024 && unit < units.length - 1) {\n          value /= 1024;\n          unit++;\n        }\n        if (unit === 0) {\n          return `${value} ${units[unit]}`;\n        }\n        return `${value.toFixed(1)} ${units[unit]}`;\n      }\n      function binaryLinesFromBuffer(buffer) {\n        const out = [];\n        let start = 0;\n        for (let i = 0; i < buffer.length; i++) {\n          if (buffer[i] === 10) {\n            out.push(new BinaryString2(Uint8Array.from(buffer.slice(start, i + 1))));\n            start = i + 1;\n          }\n        }\n        if (start < buffer.length) {\n          out.push(new BinaryString2(Uint8Array.from(buffer.slice(start))));\n        }\n        return out;\n      }\n      function textLinesFromString(text) {\n        const out = [];\n        let start = 0;\n        for (let i = 0; i < text.length; i++) {\n          if (text[i] === "\\n") {\n            out.push(text.slice(start, i + 1));\n            start = i + 1;\n          }\n        }\n        if (start < text.length) {\n          out.push(text.slice(start));\n        }\n        return out;\n      }\n      function renderValue(value) {\n        if (value && value.bytes instanceof Uint8Array) {\n          return value.to_String();\n        }\n        if (typeof runtimePolicy2.to_String === "function") {\n          return runtimePolicy2.to_String(value);\n        }\n        return String(value ?? "");\n      }\n      function writeStdout(text) {\n        if (typeof runtimePolicy2.stdout_write === "function") {\n          runtimePolicy2.stdout_write(text);\n          return;\n        }\n        process.stdout.write(text);\n      }\n      function writeStderr(text) {\n        if (typeof runtimePolicy2.stderr_write === "function") {\n          runtimePolicy2.stderr_write(text);\n          return;\n        }\n        process.stderr.write(text);\n      }\n      function streamPayload(values, newline) {\n        const text = values.map(renderValue).join("");\n        return newline ? `${text}\n` : text;\n      }\n      var StandardOutputStream = class {\n        print(...values) {\n          writeStdout(streamPayload(values, false));\n          return null;\n        }\n        say(...values) {\n          writeStdout(streamPayload(values, true));\n          return null;\n        }\n      };\n      var StandardErrorStream = class {\n        print(...values) {\n          writeStderr(streamPayload(values, false));\n          return null;\n        }\n        say(...values) {\n          writeStderr(streamPayload(values, true));\n          return null;\n        }\n      };\n      var StandardInputStream = class {\n        constructor() {\n          this._buffer = null;\n          this._linePos = 0;\n          this._lineMode = "text";\n        }\n        _bufferBytes() {\n          if (this._buffer == null) {\n            this._buffer = fs.readFileSync(0);\n          }\n          return this._buffer;\n        }\n        _lines(raw) {\n          const buffer = this._bufferBytes();\n          return raw ? binaryLinesFromBuffer(buffer) : textLinesFromString(buffer.toString("utf8"));\n        }\n        next_line(raw = false) {\n          const mode = raw ? "raw" : "text";\n          if (this._lineMode !== mode) {\n            this._lineMode = mode;\n            this._linePos = 0;\n          }\n          const lines = this._lines(raw);\n          if (this._linePos >= lines.length) {\n            return null;\n          }\n          return lines[this._linePos++];\n        }\n        each_line(fn2, raw = false) {\n          for (const line of this._lines(raw).slice(this._linePos)) {\n            fn2(line);\n            this._linePos++;\n          }\n          return this;\n        }\n      };\n      function statToDict(stats) {\n        if (!stats) {\n          return null;\n        }\n        const out = {\n          dev: stats.dev,\n          ino: stats.ino,\n          mode: stats.mode,\n          nlink: stats.nlink,\n          uid: stats.uid,\n          gid: stats.gid,\n          rdev: stats.rdev,\n          size: stats.size,\n          atime: Math.floor(stats.atimeMs / 1e3),\n          mtime: Math.floor(stats.mtimeMs / 1e3),\n          ctime: Math.floor(stats.ctimeMs / 1e3),\n          blksize: stats.blksize ?? 0,\n          blocks: stats.blocks ?? 0\n        };\n        Object.defineProperty(out, "has", {\n          value(key) {\n            return Object.prototype.hasOwnProperty.call(out, String(key)) ? 1 : 0;\n          },\n          enumerable: false\n        });\n        Object.defineProperty(out, "get", {\n          value(key, fallback = null) {\n            return Object.prototype.hasOwnProperty.call(out, String(key)) ? out[String(key)] : fallback;\n          },\n          enumerable: false\n        });\n        return out;\n      }\n      var Path = class _Path {\n        constructor(rawPath, options = {}) {\n          const pathValue = rawPath && typeof rawPath === "object" && !Array.isArray(rawPath) && (Object.prototype.hasOwnProperty.call(rawPath, "path") || typeof rawPath.get === "function" && typeof rawPath.has === "function" && rawPath.has("path")) ? typeof rawPath.get === "function" ? rawPath.get("path") : rawPath.path : rawPath;\n          this.value = String(pathValue ?? "");\n          this._linePos = 0;\n          this._lineMode = "text";\n          this._tempCleanup = options.tempCleanup || null;\n        }\n        __demolish__() {\n          const cleanup = this._tempCleanup;\n          this._tempCleanup = null;\n          if (cleanup === "dir") {\n            try {\n              fs.rmSync(this.value, { recursive: true, force: true });\n            } catch (_err) {\n            }\n          } else if (cleanup === "file") {\n            try {\n              fs.rmSync(this.value, { force: true });\n            } catch (_err) {\n            }\n          }\n          return null;\n        }\n        to_String() {\n          return this.value;\n        }\n        parent() {\n          const dir = path.dirname(this.value);\n          return new _Path(dir === "" ? "." : dir);\n        }\n        sibling(name2) {\n          return this.parent().child(name2);\n        }\n        absolute() {\n          return new _Path(path.resolve(this.value));\n        }\n        realpath() {\n          try {\n            return new _Path(fs.realpathSync(this.value));\n          } catch (_err) {\n            return null;\n          }\n        }\n        is_absolute() {\n          return path.isAbsolute(this.value) ? 1 : 0;\n        }\n        basename() {\n          return path.basename(this.value);\n        }\n        exists() {\n          return bool(fs.existsSync(this.value));\n        }\n        is_file() {\n          try {\n            return bool(fs.statSync(this.value).isFile());\n          } catch (_err) {\n            return 0;\n          }\n        }\n        is_dir() {\n          try {\n            return bool(fs.statSync(this.value).isDirectory());\n          } catch (_err) {\n            return 0;\n          }\n        }\n        size() {\n          return fs.statSync(this.value).size;\n        }\n        size_human() {\n          return formatSizeHuman(this.size());\n        }\n        stat() {\n          return statToDict(fs.statSync(this.value));\n        }\n        lstat() {\n          return statToDict(fs.lstatSync(this.value));\n        }\n        child(name2) {\n          return new _Path(path.join(this.value, String(name2)));\n        }\n        children() {\n          return fs.readdirSync(this.value).map((name2) => new _Path(path.join(this.value, name2)));\n        }\n        iterator() {\n          const kids = this.children();\n          let i = 0;\n          return {\n            next() {\n              if (i >= kids.length) {\n                return null;\n              }\n              return kids[i++];\n            }\n          };\n        }\n        chmod(mode) {\n          fs.chmodSync(this.value, Number(mode));\n          return Number(mode);\n        }\n        copy(target) {\n          const dest = target instanceof _Path ? target : new _Path(target);\n          fs.copyFileSync(this.value, dest.value);\n          return dest;\n        }\n        move(target) {\n          const dest = target instanceof _Path ? target : new _Path(target);\n          fs.renameSync(this.value, dest.value);\n          return dest;\n        }\n        remove() {\n          try {\n            fs.rmSync(this.value, { force: true });\n            return 1;\n          } catch (_err) {\n            return 0;\n          }\n        }\n        remove_tree() {\n          try {\n            fs.rmSync(this.value, { recursive: true, force: true });\n            return 1;\n          } catch (_err) {\n            return 0;\n          }\n        }\n        touchpath() {\n          fs.mkdirSync(path.dirname(this.value), { recursive: true });\n          if (!fs.existsSync(this.value)) {\n            fs.writeFileSync(this.value, "");\n          }\n          return this;\n        }\n        mkdir() {\n          fs.mkdirSync(this.value, { recursive: true });\n          return 1;\n        }\n        mkdir_exclusive() {\n          try {\n            fs.mkdirSync(this.value);\n            return 1;\n          } catch (err) {\n            if (err && err.code === "EEXIST") {\n              return 0;\n            }\n            throw err;\n          }\n        }\n        spew(value) {\n          traceBlockingOperation("std/io Path.spew");\n          if (!(value && value.bytes instanceof Uint8Array)) {\n            throw new Error(`TypeException: Path.spew expects BinaryString, got ${typeName2(value)}`);\n          }\n          fs.writeFileSync(this.value, Buffer.from(value.bytes));\n          return this;\n        }\n        spew_async(value) {\n          return new Task(async () => {\n            this.spew(value);\n            return this;\n          });\n        }\n        slurp() {\n          traceBlockingOperation("std/io Path.slurp");\n          return new BinaryString2(Uint8Array.from(fs.readFileSync(this.value)));\n        }\n        slurp_async() {\n          return new Task(async () => new BinaryString2(Uint8Array.from(await fs.promises.readFile(this.value))));\n        }\n        spew_utf8(text) {\n          traceBlockingOperation("std/io Path.spew_utf8");\n          if (typeof text !== "string") {\n            throw new Error(`TypeException: Path.spew_utf8 expects String, got ${typeName2(text)}`);\n          }\n          fs.writeFileSync(this.value, text, "utf8");\n          return this;\n        }\n        spew_utf8_async(text) {\n          return new Task(async () => {\n            if (typeof text !== "string") {\n              throw new Error(`TypeException: Path.spew_utf8 expects String, got ${typeName2(text)}`);\n            }\n            await fs.promises.writeFile(this.value, text, "utf8");\n            return this;\n          });\n        }\n        slurp_utf8() {\n          traceBlockingOperation("std/io Path.slurp_utf8");\n          return fs.readFileSync(this.value, "utf8");\n        }\n        slurp_utf8_async() {\n          return new Task(async () => fs.promises.readFile(this.value, "utf8"));\n        }\n        append(value) {\n          traceBlockingOperation("std/io Path.append");\n          if (!(value && value.bytes instanceof Uint8Array)) {\n            throw new Error(`TypeException: Path.append expects BinaryString, got ${typeName2(value)}`);\n          }\n          fs.appendFileSync(this.value, Buffer.from(value.bytes));\n          return this;\n        }\n        append_async(value) {\n          return new Task(async () => {\n            if (!(value && value.bytes instanceof Uint8Array)) {\n              throw new Error(`TypeException: Path.append expects BinaryString, got ${typeName2(value)}`);\n            }\n            await fs.promises.appendFile(this.value, Buffer.from(value.bytes));\n            return this;\n          });\n        }\n        append_utf8(text) {\n          traceBlockingOperation("std/io Path.append_utf8");\n          if (typeof text !== "string") {\n            throw new Error(`TypeException: Path.append_utf8 expects String, got ${typeName2(text)}`);\n          }\n          fs.appendFileSync(this.value, text, "utf8");\n          return this;\n        }\n        append_utf8_async(text) {\n          return new Task(async () => {\n            if (typeof text !== "string") {\n              throw new Error(`TypeException: Path.append_utf8 expects String, got ${typeName2(text)}`);\n            }\n            await fs.promises.appendFile(this.value, text, "utf8");\n            return this;\n          });\n        }\n        lines_async() {\n          return new Task(async () => binaryLinesFromBuffer(await fs.promises.readFile(this.value)));\n        }\n        lines_utf8_async() {\n          return new Task(async () => textLinesFromString(await fs.promises.readFile(this.value, "utf8")));\n        }\n        each_line(fn2, raw = false) {\n          traceBlockingOperation("std/io Path.each_line");\n          const lines = raw ? binaryLinesFromBuffer(fs.readFileSync(this.value)) : textLinesFromString(this.slurp_utf8());\n          for (const line of lines) {\n            fn2(line);\n          }\n          return this;\n        }\n        next_line(raw = false) {\n          traceBlockingOperation("std/io Path.next_line");\n          const mode = raw ? "raw" : "text";\n          if (this._lineMode !== mode) {\n            this._lineMode = mode;\n            this._linePos = 0;\n          }\n          const lines = raw ? binaryLinesFromBuffer(fs.readFileSync(this.value)) : textLinesFromString(this.slurp_utf8());\n          if (this._linePos >= lines.length) {\n            return null;\n          }\n          return lines[this._linePos++];\n        }\n        static cwd() {\n          return new _Path(process.cwd());\n        }\n        static tempfile() {\n          return new _Path(makeTempFilePath(), { tempCleanup: "file" });\n        }\n        static tempdir() {\n          return new _Path(\n            fs.mkdtempSync(path.join(os.tmpdir(), "zuzu-js-dir-")),\n            { tempCleanup: "dir" }\n          );\n        }\n        static join(parts) {\n          return new _Path(path.join(...parts.map((p) => String(p))));\n        }\n        static split(source) {\n          return path.normalize(String(source)).split(path.sep).filter(Boolean);\n        }\n        static normalize(source) {\n          return new _Path(path.normalize(String(source)));\n        }\n        static glob(pattern) {\n          const text = String(pattern ?? "");\n          const star = text.indexOf("*");\n          if (star < 0) {\n            return fs.existsSync(text) ? [new _Path(text)] : [];\n          }\n          const dir = path.dirname(text);\n          const ext = text.slice(star + 1);\n          return fs.readdirSync(dir).filter((name2) => ext === "" || name2.endsWith(ext.replace(/^\\./u, "."))).map((name2) => new _Path(path.join(dir, name2)));\n        }\n      };\n      module2.exports = {\n        Path,\n        STDIN: new StandardInputStream(),\n        STDOUT: new StandardOutputStream(),\n        STDERR: new StandardErrorStream()\n      };\n      Object.defineProperty(module2.exports, "__zuzu_set_runtime_policy", {\n        value(policy = {}) {\n          runtimePolicy2 = policy || {};\n        },\n        enumerable: false\n      });\n    }\n  });\n\n  // lib/runtime.js\n  var require_runtime = __commonJS({\n    "lib/runtime.js"(exports2, module2) {\n      "use strict";\n      var { capabilitiesForModule } = require_capabilities();\n      var { setCompiledSource } = require_execution_metadata();\n      var {\n        DEFAULT_TRANSPILER,\n        normalizeTranspilerName,\n        transpile,\n        stripPod\n      } = require_transpiler();\n      var {\n        collectTopLevelDeclarations,\n        runSwitch,\n        runMatch,\n        contains,\n        collectionUnion,\n        collectionIntersection,\n        collectionDifference,\n        collectionSubsetOf,\n        collectionSupersetOf,\n        collectionEquivalentOf,\n        makeArray,\n        makeSet,\n        makeBag,\n        makePairList,\n        makeTemporaryPairList,\n        lengthOf,\n        operatorString,\n        operatorRegexp,\n        ZuzuBinary,\n        BinaryString: BinaryString2,\n        Pair,\n        PairList,\n        withArrayMethods,\n        ZuzuBag,\n        isPairListLike,\n        isWeakableValue,\n        makeWeakValue,\n        resolveWeakValue,\n        retainValue,\n        releaseValue,\n        strongReferenceCount,\n        retainCollectionValue,\n        releaseCollectionValue,\n        releaseCollectionValues,\n        addSetValue,\n        assignStrongValue,\n        assignWeakValue,\n        codePointStringCompare,\n        stringSortComparator\n      } = require_runtime_helpers();\n      var taskRuntime2 = require_task();\n      var textEncoder = new TextEncoder();\n      var utf8Decoder = new TextDecoder("utf-8", { fatal: true });\n      var ZUZU_SKIP_BUILD = /* @__PURE__ */ Symbol.for("zuzu.skip_build");\n      var runtimeVersion = (() => {\n        if (typeof globalThis === "object" && globalThis !== null) {\n          const globalVersion = globalThis.__ZUZU_RUNTIME_VERSION;\n          if (typeof globalVersion === "string" && globalVersion.trim()) {\n            return String(globalVersion);\n          }\n        }\n        if (typeof process === "object" && process && process.versions) {\n          try {\n            const packageMetadata = require_package();\n            const packageVersion = packageMetadata && packageMetadata.version;\n            if (packageVersion) {\n              return String(packageVersion);\n            }\n          } catch (err) {\n            return "dev";\n          }\n        }\n        return "dev";\n      })();\n      function defaultModuleSearchRoots(host, repoRoot, includePaths) {\n        if (host.name === "browser") {\n          return [\n            host.join(repoRoot, "modules"),\n            ...includePaths\n          ];\n        }\n        const pathsModule = "./paths";\n        return __require(pathsModule).defaultModuleSearchRoots({\n          includePaths,\n          packageRoot: repoRoot,\n          initialCwd: host.cwd()\n        });\n      }\n      function installHostCollectionMethods() {\n        withArrayMethods();\n        const define = (proto, name2, fn2) => {\n          if (!Object.prototype.hasOwnProperty.call(proto, name2)) {\n            const desc = /* @__PURE__ */ Object.create(null);\n            desc.value = fn2;\n            desc.enumerable = false;\n            desc.configurable = true;\n            desc.writable = true;\n            Object.defineProperty(proto, name2, desc);\n          }\n        };\n        define(Array.prototype, "push_weak", function _pushWeak(...values) {\n          this.push(...values.map(makeWeakValue));\n          return this;\n        });\n        define(Array.prototype, "unshift_weak", function _unshiftWeak(...values) {\n          this.unshift(...values.map(makeWeakValue));\n          return this;\n        });\n        define(Array.prototype, "set_weak", function _setWeak(index, value) {\n          releaseCollectionValue(this, this[index]);\n          this[index] = makeWeakValue(value);\n          return this;\n        });\n        define(Set.prototype, "add_weak", function _addWeak(value) {\n          this.add(makeWeakValue(value));\n          return this;\n        });\n        define(Set.prototype, "push_weak", function _pushWeak(...values) {\n          for (const value of values) {\n            this.add(makeWeakValue(value));\n          }\n          return this;\n        });\n        define(Set.prototype, "copy", function _copy() {\n          return makeSet(this);\n        });\n        define(ZuzuBag.prototype, "add_weak", function _addWeak(...values) {\n          this.items.push(...values.map(makeWeakValue));\n          return this;\n        });\n        define(ZuzuBag.prototype, "push_weak", function _pushWeak(...values) {\n          return this.add_weak(...values);\n        });\n        define(PairList.prototype, "add_weak", function _addWeak(key, value) {\n          this.list.push([String(key), makeWeakValue(value)]);\n          return this;\n        });\n        define(PairList.prototype, "set_weak", function _setWeak(key, value) {\n          return this.add_weak(key, value);\n        });\n        Object.defineProperty(ZuzuBag.prototype, "contains", {\n          value: function _containsWeakAware(value) {\n            const resolved = resolveWeakValue(value);\n            return this.items.some((item) => resolveWeakValue(item) === resolved) ? 1 : 0;\n          },\n          enumerable: false,\n          configurable: true,\n          writable: true\n        });\n        Object.defineProperty(Set.prototype, "contains", {\n          value: function _containsWeakAware(value) {\n            const resolved = resolveWeakValue(value);\n            for (const item of this) {\n              if (resolveWeakValue(item) === resolved) {\n                return 1;\n              }\n            }\n            return 0;\n          },\n          enumerable: false,\n          configurable: true,\n          writable: true\n        });\n      }\n      function createObjectFacade() {\n        function ZuzuContextObject(value) {\n          if (new.target) {\n            return void 0;\n          }\n          return Object(value);\n        }\n        Object.setPrototypeOf(ZuzuContextObject, Object);\n        Object.defineProperty(ZuzuContextObject, "prototype", {\n          value: Object.prototype,\n          enumerable: false,\n          configurable: false,\n          writable: false\n        });\n        return ZuzuContextObject;\n      }\n      function zuzuStringify(value) {\n        value = resolveWeakValue(value);\n        if (value == null) {\n          return "";\n        }\n        if (typeof value === "boolean") {\n          return value ? "1" : "0";\n        }\n        if (value instanceof RegExp) {\n          return value.source;\n        }\n        if (value instanceof ZuzuBinary) {\n          return value.to_String();\n        }\n        if (value && typeof value.to_String === "function") {\n          return String(value.to_String());\n        }\n        if (value instanceof Error) {\n          return value.message || value.name || String(value);\n        }\n        return String(value);\n      }\n      function zuzuOperatorString(value) {\n        return operatorString(value);\n      }\n      function binaryFromLiteral(value) {\n        const text = String(value ?? "");\n        const bytes = [];\n        for (let i = 0; i < text.length; i++) {\n          bytes.push(text.charCodeAt(i) & 255);\n        }\n        return new BinaryString2(bytes);\n      }\n      function toBinaryValue(value) {\n        value = resolveWeakValue(value);\n        if (value instanceof ZuzuBinary) {\n          return new BinaryString2(value);\n        }\n        if (typeof value === "string") {\n          return new BinaryString2(textEncoder.encode(value));\n        }\n        throw new Error(`TypeException: expected String for to_binary, got ${zuzuTypeof(value)}`);\n      }\n      function toStringValue(value) {\n        value = resolveWeakValue(value);\n        if (typeof value === "string") {\n          return value;\n        }\n        if (value instanceof ZuzuBinary) {\n          try {\n            return utf8Decoder.decode(value.bytes);\n          } catch (err) {\n            return Array.from(value.bytes, (byte) => String.fromCharCode(byte)).join("");\n          }\n        }\n        throw new Error(`TypeException: expected BinaryString for to_string, got ${zuzuTypeof(value)}`);\n      }\n      function stringCompare(left, right, options = {}) {\n        const l = options.insensitive ? zuzuOperatorString(left).toLowerCase() : zuzuOperatorString(left);\n        const r = options.insensitive ? zuzuOperatorString(right).toLowerCase() : zuzuOperatorString(right);\n        return codePointStringCompare(l, r);\n      }\n      function parseNumericString(value) {\n        const text = String(value).trim();\n        const radix = text.match(/^([+-]?)0([xX][0-9a-fA-F]+|[bB][01]+|[oO][0-7]+)$/);\n        if (radix) {\n          const base = "xX".includes(radix[2][0]) ? 16 : "bB".includes(radix[2][0]) ? 2 : 8;\n          const magnitude = parseInt(radix[2].slice(1), base);\n          return radix[1] === "-" ? -magnitude : magnitude;\n        }\n        const match = text.match(/^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?$/);\n        if (!match) {\n          throw new Error(`TypeException: cannot coerce String to Number: ${JSON.stringify(String(value))}`);\n        }\n        const parsed = Number(text);\n        if (Number.isNaN(parsed)) {\n          throw new Error(`TypeException: cannot coerce String to Number: ${JSON.stringify(String(value))}`);\n        }\n        return parsed;\n      }\n      function zuzuToNumber(value) {\n        value = resolveWeakValue(value);\n        if (value == null) {\n          return 0;\n        }\n        if (typeof value === "number" || Object.prototype.toString.call(value) === "[object Number]") {\n          return Number(value);\n        }\n        if (typeof value === "boolean" || Object.prototype.toString.call(value) === "[object Boolean]") {\n          return value.valueOf() ? 1 : 0;\n        }\n        if (typeof value === "string" || Object.prototype.toString.call(value) === "[object String]") {\n          return parseNumericString(value);\n        }\n        if (typeof value === "function") {\n          throw new Error(`TypeException: cannot coerce ${zuzuTypeof(value)} to Number`);\n        }\n        if (value && typeof value.to_Number === "function") {\n          return zuzuToNumber(value.to_Number());\n        }\n        throw new Error(`TypeException: cannot coerce ${zuzuTypeof(value)} to Number`);\n      }\n      function zuzuTruthy(value) {\n        value = resolveWeakValue(value);\n        if (value == null) {\n          return false;\n        }\n        if (value && typeof value.to_Boolean === "function") {\n          return zuzuTruthy(value.to_Boolean());\n        }\n        if (value instanceof ZuzuBinary) {\n          return value.byteLength() > 0;\n        }\n        if (typeof value === "boolean" || Object.prototype.toString.call(value) === "[object Boolean]") {\n          return value.valueOf() === true;\n        }\n        if (typeof value === "number" || Object.prototype.toString.call(value) === "[object Number]") {\n          return Number(value) !== 0;\n        }\n        if (typeof value === "string" || Object.prototype.toString.call(value) === "[object String]") {\n          return String(value) !== "";\n        }\n        if (Array.isArray(value)) {\n          return value.length > 0;\n        }\n        if (isPairListLike(value)) {\n          return value.length() > 0;\n        }\n        if (value instanceof ZuzuBag) {\n          return value.length() > 0;\n        }\n        if (isSetLike(value)) {\n          return value.size > 0;\n        }\n        const ctorName = value && value.constructor && value.constructor.name;\n        if (value && typeof value === "object" && (ctorName === "Object" || ctorName == null)) {\n          return Object.keys(value).length > 0;\n        }\n        return Boolean(value);\n      }\n      function defaultOperator(leftInput, rightInput) {\n        const left = resolveWeakValue(leftInput);\n        const right = resolveWeakValue(rightInput);\n        const leftType = zuzuTypeof(left);\n        if (left != null && leftType !== "Dict" && !isPairListLike(left)) {\n          throw new Error(\n            `TypeException: default operator left operand expects Dict, PairList, or Null, got ${leftType}`\n          );\n        }\n        if (zuzuTypeof(right) !== "Dict" && !isPairListLike(right)) {\n          throw new Error(\n            `TypeException: default operator right operand expects Dict or PairList, got ${zuzuTypeof(right)}`\n          );\n        }\n        if (leftType === "Dict") {\n          const result = {};\n          for (const key of Object.keys(left)) {\n            result[key] = left[key];\n          }\n          if (isPairListLike(right)) {\n            for (const [key, value] of right.list) {\n              if (!Object.prototype.hasOwnProperty.call(result, key)) {\n                result[key] = value;\n              }\n            }\n          } else {\n            for (const key of Object.keys(right).sort()) {\n              if (!Object.prototype.hasOwnProperty.call(result, key)) {\n                result[key] = right[key];\n              }\n            }\n          }\n          return result;\n        }\n        const values = isPairListLike(left) ? left.list.map(([key, value]) => [key, value]) : [];\n        const originalKeys = new Set(values.map(([key]) => key));\n        if (isPairListLike(right)) {\n          for (const [key, value] of right.list) {\n            if (!originalKeys.has(key)) {\n              values.push([key, value]);\n            }\n          }\n        } else {\n          for (const key of Object.keys(right).sort()) {\n            if (!originalKeys.has(key)) {\n              values.push([key, right[key]]);\n            }\n          }\n        }\n        return makePairList(values);\n      }\n      function isNumericComparable(value) {\n        value = resolveWeakValue(value);\n        if (value == null) {\n          return true;\n        }\n        if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {\n          return true;\n        }\n        const tag = Object.prototype.toString.call(value);\n        if (tag === "[object Number]" || tag === "[object String]" || tag === "[object Boolean]") {\n          return true;\n        }\n        return Boolean(value && typeof value.to_Number === "function");\n      }\n      function numericEqual(left, right) {\n        const leftNum = zuzuToNumber(left);\n        const rightNum = zuzuToNumber(right);\n        if (Object.is(leftNum, rightNum)) {\n          return true;\n        }\n        if (Number.isInteger(leftNum) && Number.isInteger(rightNum)) {\n          return false;\n        }\n        const scale = Math.max(1, Math.abs(leftNum), Math.abs(rightNum));\n        return Math.abs(leftNum - rightNum) <= Number.EPSILON * 16 * scale;\n      }\n      function isExhaustedIteratorError(err) {\n        if (!err) {\n          return false;\n        }\n        const name2 = String(err.name || err.constructor && err.constructor.name || "");\n        if (name2 === "ExhaustedException") {\n          return true;\n        }\n        const message = String(err.message || "");\n        if (/\\bExhaustedException\\b/.test(message)) {\n          return true;\n        }\n        const stack = String(err.stack || "");\n        return /\\bExhaustedException\\b/.test(stack);\n      }\n      function formatRuntimeError(err) {\n        if (err && err.name === "SyntaxError" && typeof err.stack === "string" && err.stack.trim()) {\n          return `${err.stack}\n`;\n        }\n        if (err && err.name && err.message) {\n          return `${err.name}: ${err.message}\n`;\n        }\n        return `${String(err)}\n`;\n      }\n      async function runSwitchAsync(value, comparator, cases, defaultBody) {\n        const cmp = (left, right) => {\n          switch (comparator) {\n            case "eq":\n              return stringCompare(left, right) === 0;\n            case "eqi":\n              return stringCompare(left, right, { insensitive: true }) === 0;\n            case "ne":\n              return stringCompare(left, right) !== 0;\n            case "nei":\n              return stringCompare(left, right, { insensitive: true }) !== 0;\n            case "=":\n              return numericEqual(zuzuToNumber(left), zuzuToNumber(right));\n            case "==":\n            default:\n              return !!zuzuEqual(left, right);\n          }\n        };\n        let runNext = false;\n        for (const section of cases) {\n          let matched = false;\n          if (Array.isArray(section.tests)) {\n            for (const test of section.tests) {\n              if (zuzuTruthy(await taskRuntime2.awaitValue(test(value)))) {\n                matched = true;\n                break;\n              }\n            }\n          } else {\n            matched = section.values.some((item) => cmp(value, item));\n          }\n          if (matched || runNext) {\n            const result = await taskRuntime2.awaitValue(section.body());\n            runNext = result === true;\n            if (!runNext && result && typeof result === "object" && result.__zuzu_return) {\n              return result;\n            }\n            if (!runNext) {\n              return null;\n            }\n          }\n        }\n        if (defaultBody) {\n          const result = await taskRuntime2.awaitValue(defaultBody());\n          if (result && typeof result === "object" && result.__zuzu_return) {\n            return result;\n          }\n        }\n        return null;\n      }\n      function concatValue(left, right) {\n        left = resolveWeakValue(left);\n        right = resolveWeakValue(right);\n        if (left instanceof ZuzuBinary && right instanceof ZuzuBinary) {\n          const merged = new Uint8Array(left.length + right.length);\n          merged.set(left.bytes, 0);\n          merged.set(right.bytes, left.length);\n          return new BinaryString2(merged);\n        }\n        if (typeof left === "string" && typeof right === "string") {\n          return left + right;\n        }\n        if (left instanceof ZuzuBinary && typeof right === "string") {\n          if (!left.isAscii()) {\n            throw new Error("TypeException: Cannot implicitly concatenate non-ASCII BinaryString with String");\n          }\n          return left.to_String() + right;\n        }\n        if (typeof left === "string" && right instanceof ZuzuBinary) {\n          if (!right.isAscii()) {\n            throw new Error("TypeException: Cannot implicitly concatenate non-ASCII BinaryString with String");\n          }\n          return left + right.to_String();\n        }\n        return zuzuOperatorString(left) + zuzuOperatorString(right);\n      }\n      function operatorLength(value) {\n        value = resolveWeakValue(value);\n        if (value instanceof ZuzuBinary) {\n          return value.byteLength();\n        }\n        if (Array.isArray(value) || isPairListLike(value) || value instanceof ZuzuBag || isSetLike(value) || value && typeof value === "object" && value.constructor && value.constructor.name === "Object") {\n          return lengthOf(value);\n        }\n        return [...zuzuOperatorString(value)].length;\n      }\n      function regexReplaceValue(current, pattern, replacement) {\n        const source = zuzuOperatorString(current);\n        const regex = operatorRegexp(pattern);\n        return source.replace(regex, replacement);\n      }\n      function bitwiseBinaryPair(left, right, opName) {\n        if (left.length !== right.length) {\n          throw new Error("Exception: BinaryString bitwise operands must be equal length");\n        }\n        const out = new Uint8Array(left.length);\n        for (let i = 0; i < left.length; i++) {\n          const a = left.bytes[i];\n          const b = right.bytes[i];\n          if (opName === "and") {\n            out[i] = a & b;\n          } else if (opName === "or") {\n            out[i] = a | b;\n          } else {\n            out[i] = a ^ b;\n          }\n        }\n        return new BinaryString2(out);\n      }\n      function bitwiseAnd(left, right) {\n        if (left instanceof ZuzuBinary && right instanceof ZuzuBinary) {\n          return bitwiseBinaryPair(left, right, "and");\n        }\n        return (zuzuToNumber(left) >>> 0 & zuzuToNumber(right) >>> 0) >>> 0;\n      }\n      function bitwiseOr(left, right) {\n        if (left instanceof ZuzuBinary && right instanceof ZuzuBinary) {\n          return bitwiseBinaryPair(left, right, "or");\n        }\n        return (zuzuToNumber(left) >>> 0 | zuzuToNumber(right) >>> 0) >>> 0;\n      }\n      function bitwiseXor(left, right) {\n        if (left instanceof ZuzuBinary && right instanceof ZuzuBinary) {\n          return bitwiseBinaryPair(left, right, "xor");\n        }\n        return (zuzuToNumber(left) >>> 0 ^ zuzuToNumber(right) >>> 0) >>> 0;\n      }\n      function bitwiseNot(value) {\n        value = resolveWeakValue(value);\n        if (value instanceof ZuzuBinary) {\n          const out = new Uint8Array(value.length);\n          for (let i = 0; i < value.length; i++) {\n            out[i] = ~value.bytes[i] & 255;\n          }\n          return new BinaryString2(out);\n        }\n        return ~(zuzuToNumber(value) >>> 0) >>> 0;\n      }\n      function shiftBitstream(bytes, count, left) {\n        const len = bytes.length;\n        const out = new Uint8Array(len);\n        if (len === 0 || count >= len * 8) {\n          return out;\n        }\n        const byteShift = Math.floor(count / 8);\n        const bitShift = count % 8;\n        for (let i = 0; i < len; i++) {\n          let value;\n          if (left) {\n            const src = i + byteShift;\n            const hi = src < len ? bytes[src] : 0;\n            const lo = src + 1 < len ? bytes[src + 1] : 0;\n            value = (hi << 8 | lo) << bitShift >> 8;\n          } else {\n            if (i < byteShift) {\n              continue;\n            }\n            const lo = bytes[i - byteShift];\n            const hi = i > byteShift ? bytes[i - byteShift - 1] : 0;\n            value = (hi << 8 | lo) >> bitShift;\n          }\n          out[i] = value & 255;\n        }\n        return out;\n      }\n      function shiftValue(left, right, leftward) {\n        left = resolveWeakValue(left);\n        const count = Math.trunc(zuzuToNumber(right));\n        if (!(count >= 0) || !Number.isFinite(count)) {\n          throw new Error("Exception: shift count must be a non-negative integer");\n        }\n        if (left instanceof ZuzuBinary) {\n          return new BinaryString2(shiftBitstream(left.bytes, count, leftward));\n        }\n        const value = Math.trunc(zuzuToNumber(left));\n        const factor = Math.pow(2, count);\n        return leftward ? value * factor : Math.floor(value / factor);\n      }\n      function zuzuComparableValue(value) {\n        value = resolveWeakValue(value);\n        if (typeof value === "function" && value.length === 0) {\n          try {\n            return value();\n          } catch (_err) {\n            return value;\n          }\n        }\n        return value;\n      }\n      function zuzuEqual(left, right) {\n        const a = zuzuComparableValue(left);\n        const b = zuzuComparableValue(right);\n        if (a === b) {\n          return 1;\n        }\n        if (a == null || b == null) {\n          return 0;\n        }\n        if (a instanceof ZuzuBinary && b instanceof ZuzuBinary) {\n          if (a.bytes.length !== b.bytes.length) {\n            return 0;\n          }\n          for (let i = 0; i < a.bytes.length; i++) {\n            if (a.bytes[i] !== b.bytes[i]) {\n              return 0;\n            }\n          }\n          return 1;\n        }\n        if (Array.isArray(a) && Array.isArray(b)) {\n          if (a.length !== b.length) {\n            return 0;\n          }\n          for (let i = 0; i < a.length; i++) {\n            if (!zuzuEqual(a[i], b[i])) {\n              return 0;\n            }\n          }\n          return 1;\n        }\n        if (isSetLike(a) && isSetLike(b)) {\n          return collectionEquivalentOf(a, b) ? 1 : 0;\n        }\n        if (isBagLike(a) && isBagLike(b)) {\n          return zuzuEqual(a.to_Array(), b.to_Array());\n        }\n        if (isPairListLike(a) && isPairListLike(b)) {\n          if (a.list.length !== b.list.length) {\n            return 0;\n          }\n          for (let i = 0; i < a.list.length; i++) {\n            if (a.list[i][0] !== b.list[i][0]) {\n              return 0;\n            }\n            if (!zuzuEqual(a.list[i][1], b.list[i][1])) {\n              return 0;\n            }\n          }\n          return 1;\n        }\n        if (isPlainObjectLike(a) && isPlainObjectLike(b)) {\n          const keysA = Object.keys(a).sort();\n          const keysB = Object.keys(b).sort();\n          if (!zuzuEqual(keysA, keysB)) {\n            return 0;\n          }\n          for (const key of keysA) {\n            if (!zuzuEqual(a[key], b[key])) {\n              return 0;\n            }\n          }\n          return 1;\n        }\n        return 0;\n      }\n      function isSetLike(value) {\n        return Object.prototype.toString.call(value) === "[object Set]";\n      }\n      function isBagLike(value) {\n        return value instanceof ZuzuBag || value && value.constructor && value.constructor.name === "ZuzuBag";\n      }\n      function isPlainObjectLike(value) {\n        return Object.prototype.toString.call(value) === "[object Object]" && !(value.constructor && value.constructor.__zuzu_class_name);\n      }\n      function isDictMethodReceiver(value) {\n        return isPlainObjectLike(value) && !isPairListLike(value) && !isSetLike(value) && !isBagLike(value);\n      }\n      function normalizeDictKey(key) {\n        key = resolveWeakValue(key);\n        if (key == null) {\n          return "";\n        }\n        if (typeof key === "string") {\n          return key;\n        }\n        if (key instanceof ZuzuBinary) {\n          return key.to_String();\n        }\n        if (key && typeof key.to_String === "function") {\n          return String(key.to_String());\n        }\n        return String(key);\n      }\n      function arraySliceBounds(length, start, end = length) {\n        let from = Number(start ?? 0);\n        let to = Number(end ?? length);\n        from = Number.isFinite(from) ? Math.trunc(from) : 0;\n        to = Number.isFinite(to) ? Math.trunc(to) : length;\n        if (from < 0) {\n          from += length;\n        }\n        if (to < 0) {\n          to += length;\n        }\n        from = Math.max(0, Math.min(length, from));\n        to = Math.max(0, Math.min(length, to));\n        return [Math.min(from, to), Math.max(from, to)];\n      }\n      function arrayMethodArity(name2, actual, min, max = min) {\n        const count = actual - 1;\n        if (count < min || count > max) {\n          throw new Error(\n            min === max ? `${name2} expects ${min} argument${min === 1 ? "" : "s"}` : `${name2} expects between ${min} and ${max} arguments`\n          );\n        }\n      }\n      function arrayIndex(length, idx) {\n        let index = Number(idx);\n        index = Number.isFinite(index) ? Math.trunc(index) : 0;\n        if (index < 0) {\n          index += length;\n        }\n        return index;\n      }\n      function shuffledArrayValues(self) {\n        const out = self.slice();\n        for (let idx = out.length - 1; idx > 0; idx--) {\n          const swapIdx = Math.floor(Math.random() * (idx + 1));\n          [out[idx], out[swapIdx]] = [out[swapIdx], out[idx]];\n        }\n        return out;\n      }\n      function arrayJoin(self, separator, fallback, hasFallback) {\n        const sep = operatorString(separator);\n        let fallbackString;\n        const out = [];\n        for (const value of self) {\n          try {\n            out.push(operatorString(value));\n          } catch (err) {\n            if (!hasFallback) {\n              throw err;\n            }\n            if (typeof fallback === "function") {\n              out.push(operatorString(fallback(value)));\n            } else {\n              if (fallbackString === void 0) {\n                fallbackString = operatorString(fallback);\n              }\n              out.push(fallbackString);\n            }\n          }\n        }\n        return out.join(sep);\n      }\n      var ARRAY_METHODS = Object.freeze({\n        append(self, ...values) {\n          self.push(...values.map((value) => retainCollectionValue(self, value)));\n          return self;\n        },\n        push(self, ...values) {\n          return ARRAY_METHODS.append(self, ...values);\n        },\n        add(self, ...values) {\n          return ARRAY_METHODS.append(self, ...values);\n        },\n        push_weak(self, ...values) {\n          self.push(...values.map(makeWeakValue));\n          return self;\n        },\n        pop(self) {\n          return self.length ? self.pop() : null;\n        },\n        prepend(self, ...values) {\n          self.unshift(...values.map((value) => retainCollectionValue(self, value)));\n          return self;\n        },\n        unshift(self, ...values) {\n          return ARRAY_METHODS.prepend(self, ...values);\n        },\n        unshift_weak(self, ...values) {\n          self.unshift(...values.map(makeWeakValue));\n          return self;\n        },\n        shift(self) {\n          return self.length ? self.shift() : null;\n        },\n        length(self) {\n          return self.length;\n        },\n        count(self) {\n          return self.length;\n        },\n        empty(self) {\n          return self.length === 0 ? 1 : 0;\n        },\n        is_empty(self) {\n          return ARRAY_METHODS.empty(self);\n        },\n        copy(self) {\n          return makeArray(self);\n        },\n        to_Array(self) {\n          return makeArray(self);\n        },\n        get(self, idx, fallback = null) {\n          arrayMethodArity("Array.get", arguments.length, 1, 2);\n          const index = arrayIndex(self.length, idx);\n          return index >= 0 && index < self.length ? self[index] : fallback;\n        },\n        set(self, idx, value) {\n          arrayMethodArity("Array.set", arguments.length, 2);\n          const index = arrayIndex(self.length, idx);\n          if (index < 0) {\n            throw new Error("Array index is out of range");\n          }\n          releaseCollectionValue(self, self[index]);\n          self[index] = retainCollectionValue(self, value);\n          return self;\n        },\n        set_weak(self, idx, value) {\n          arrayMethodArity("Array.set_weak", arguments.length, 2);\n          const index = arrayIndex(self.length, idx);\n          if (index < 0) {\n            throw new Error("Array index is out of range");\n          }\n          releaseCollectionValue(self, self[index]);\n          self[index] = makeWeakValue(value);\n          return self;\n        },\n        clear(self) {\n          releaseCollectionValues(self);\n          self.splice(0, self.length);\n          return self;\n        },\n        join(self, separator, fallback) {\n          return arrayJoin(self, separator, fallback, arguments.length > 2);\n        },\n        slice(self, start, end) {\n          const [from, to] = arraySliceBounds(self.length, start, end);\n          return makeArray(self.slice(from, to));\n        },\n        head(self, n = 1) {\n          arrayMethodArity("Array.head", arguments.length, 0, 1);\n          return makeArray(self.slice(0, Math.max(0, Number(n) || 0)));\n        },\n        tail(self, n = 1) {\n          arrayMethodArity("Array.tail", arguments.length, 0, 1);\n          const count = Math.max(0, Number(n) || 0);\n          return makeArray(count === 0 ? [] : self.slice(-count));\n        },\n        to_Set(self) {\n          return makeSet(self);\n        },\n        to_Bag(self) {\n          return makeBag(self);\n        },\n        to_Iterator(self) {\n          return self[Symbol.iterator]();\n        },\n        sort(self, fn2) {\n          const out = self.slice();\n          out.sort((left, right) => Number(fn2(left, right)) || 0);\n          return makeArray(out);\n        },\n        sortstr(self) {\n          return makeArray(self.slice().sort(stringSortComparator));\n        },\n        sortnum(self) {\n          return makeArray(\n            self.map((item) => Number(item)).sort((a, b) => a - b)\n          );\n        },\n        reverse(self) {\n          return makeArray(self.slice().reverse());\n        },\n        sum(self) {\n          return self.reduce((a, b) => Number(a) + Number(b), 0);\n        },\n        product(self) {\n          return self.reduce((a, b) => Number(a) * Number(b), 1);\n        },\n        shuffle(self) {\n          arrayMethodArity("Array.shuffle", arguments.length, 0);\n          return makeArray(shuffledArrayValues(self));\n        },\n        sample(self, n = 1) {\n          arrayMethodArity("Array.sample", arguments.length, 0, 1);\n          return makeArray(\n            shuffledArrayValues(self).slice(0, Math.max(0, Number(n) || 0))\n          );\n        },\n        contains(self, value) {\n          return self.includes(value) ? 1 : 0;\n        },\n        map(self, fn2) {\n          arrayMethodArity("Array.map", arguments.length, 1);\n          return makeArray(self.map((value) => fn2(value)));\n        },\n        grep(self, fn2) {\n          arrayMethodArity("Array.grep", arguments.length, 1);\n          return makeArray(self.filter((value) => fn2(value)));\n        },\n        any(self, fn2) {\n          arrayMethodArity("Array.any", arguments.length, 1);\n          return self.some((value) => fn2(value)) ? 1 : 0;\n        },\n        all(self, fn2) {\n          arrayMethodArity("Array.all", arguments.length, 1);\n          return self.every((value) => fn2(value)) ? 1 : 0;\n        },\n        first(self, fn2) {\n          arrayMethodArity("Array.first", arguments.length, 1);\n          for (const value of self) {\n            if (fn2(value)) {\n              return value;\n            }\n          }\n          return null;\n        },\n        remove(self, fn2) {\n          for (let idx = self.length - 1; idx >= 0; idx--) {\n            if (fn2(self[idx])) {\n              releaseCollectionValue(self, self[idx]);\n              self.splice(idx, 1);\n            }\n          }\n          return self;\n        },\n        first_index(self, fn2) {\n          for (let idx = 0; idx < self.length; idx++) {\n            if (fn2(self[idx])) {\n              return idx;\n            }\n          }\n          return -1;\n        },\n        for_each_value(self, fn2) {\n          for (const value of self) {\n            fn2(value);\n          }\n          return self;\n        },\n        reduce(self, fn2) {\n          if (self.length === 0) {\n            return null;\n          }\n          let acc = self[0];\n          for (let idx = 1; idx < self.length; idx++) {\n            acc = fn2(acc, self[idx]);\n          }\n          return acc;\n        },\n        reductions(self, fn2) {\n          if (self.length === 0) {\n            return makeArray([]);\n          }\n          const out = [self[0]];\n          for (let idx = 1; idx < self.length; idx++) {\n            out.push(fn2(out[out.length - 1], self[idx]));\n          }\n          return makeArray(out);\n        }\n      });\n      var ARRAY_ZERO_ARG_METHODS = /* @__PURE__ */ new Set([\n        "copy",\n        "count",\n        "empty",\n        "is_empty",\n        "length",\n        "pop",\n        "reverse",\n        "shift",\n        "shuffle",\n        "sortnum",\n        "sortstr",\n        "to_Array",\n        "to_Bag",\n        "to_Iterator",\n        "to_Set"\n      ]);\n      function getArrayMethod(object, property) {\n        if (typeof property === "symbol") {\n          return null;\n        }\n        const name2 = String(property);\n        if (!Array.isArray(object) || !Object.prototype.hasOwnProperty.call(ARRAY_METHODS, name2)) {\n          return null;\n        }\n        return function zuzuArrayMethod(...args) {\n          return ARRAY_METHODS[name2](object, ...args);\n        };\n      }\n      var SET_METHODS = Object.freeze({\n        add_weak(self, ...values) {\n          for (const value of values) {\n            self.add(makeWeakValue(value));\n          }\n          return self;\n        },\n        push_weak(self, ...values) {\n          return SET_METHODS.add_weak(self, ...values);\n        },\n        clear(self) {\n          releaseCollectionValues(self);\n          Set.prototype.clear.call(self);\n          return self;\n        }\n      });\n      var SET_ZERO_ARG_METHODS = /* @__PURE__ */ new Set(["clear"]);\n      function getSetMethod(object, property) {\n        if (typeof property === "symbol") {\n          return null;\n        }\n        const name2 = String(property);\n        if (!isSetLike(object) || !Object.prototype.hasOwnProperty.call(SET_METHODS, name2)) {\n          return null;\n        }\n        return function zuzuSetMethod(...args) {\n          return SET_METHODS[name2](object, ...args);\n        };\n      }\n      function dictSortedKeys(self) {\n        return isDictMethodReceiver(self) ? Object.keys(self).sort() : [];\n      }\n      var DICT_METHODS = Object.freeze({\n        length(self) {\n          return isDictMethodReceiver(self) ? Object.keys(self).length : 0;\n        },\n        keys(self) {\n          return makeSet(dictSortedKeys(self));\n        },\n        values(self) {\n          if (!isDictMethodReceiver(self)) {\n            return makeBag([]);\n          }\n          return makeBag(dictSortedKeys(self).map((key) => resolveWeakValue(self[key])));\n        },\n        copy(self) {\n          if (!isDictMethodReceiver(self)) {\n            return {};\n          }\n          const out = {};\n          for (const key of Object.keys(self)) {\n            out[key] = retainCollectionValue(out, self[key]);\n          }\n          return out;\n        },\n        enumerate(self) {\n          if (!isDictMethodReceiver(self)) {\n            return makeBag([]);\n          }\n          return makeBag(dictSortedKeys(self).map(\n            (key) => new Pair({ pair: [key, resolveWeakValue(self[key])] })\n          ));\n        },\n        has(self, key) {\n          return isDictMethodReceiver(self) && Object.prototype.hasOwnProperty.call(self, normalizeDictKey(key)) ? 1 : 0;\n        },\n        contains(self, key) {\n          return DICT_METHODS.has(self, key);\n        },\n        exists(self, key) {\n          return DICT_METHODS.has(self, key);\n        },\n        defined(self, key) {\n          const normalized = normalizeDictKey(key);\n          return isDictMethodReceiver(self) && resolveWeakValue(self[normalized]) != null ? 1 : 0;\n        },\n        get(self, key, fallback = null) {\n          const normalized = normalizeDictKey(key);\n          return DICT_METHODS.has(self, normalized) ? resolveWeakValue(self[normalized]) : fallback;\n        },\n        add(self, key, value) {\n          if (!isDictMethodReceiver(self) || key instanceof Pair) {\n            return self;\n          }\n          const normalized = normalizeDictKey(key);\n          releaseCollectionValue(self, self[normalized]);\n          self[normalized] = retainCollectionValue(self, value);\n          return self;\n        },\n        set(self, key, value) {\n          return DICT_METHODS.add(self, key, value);\n        },\n        add_weak(self, key, value) {\n          if (!isDictMethodReceiver(self) || key instanceof Pair) {\n            return self;\n          }\n          const normalized = normalizeDictKey(key);\n          releaseCollectionValue(self, self[normalized]);\n          self[normalized] = makeWeakValue(value);\n          return self;\n        },\n        set_weak(self, key, value) {\n          return DICT_METHODS.add_weak(self, key, value);\n        },\n        kv(self) {\n          if (!isDictMethodReceiver(self)) {\n            return [];\n          }\n          const out = [];\n          for (const key of dictSortedKeys(self)) {\n            out.push(key, resolveWeakValue(self[key]));\n          }\n          return out;\n        },\n        sorted_keys(self) {\n          return dictSortedKeys(self);\n        },\n        remove(self, key) {\n          if (!isDictMethodReceiver(self)) {\n            return self;\n          }\n          if (typeof key === "function") {\n            for (const [k, v] of Object.entries(self)) {\n              if (key(new Pair({ pair: [k, v] }))) {\n                releaseCollectionValue(self, self[k]);\n                delete self[k];\n              }\n            }\n            return self;\n          }\n          if (key instanceof Pair) {\n            return self;\n          }\n          const normalized = normalizeDictKey(key);\n          releaseCollectionValue(self, self[normalized]);\n          delete self[normalized];\n          return self;\n        },\n        count(self) {\n          return DICT_METHODS.length(self);\n        },\n        empty(self) {\n          return DICT_METHODS.length(self) === 0 ? 1 : 0;\n        },\n        is_empty(self) {\n          return DICT_METHODS.empty(self);\n        },\n        to_Array(self) {\n          if (!isDictMethodReceiver(self)) {\n            return [];\n          }\n          return makeArray(dictSortedKeys(self).map(\n            (key) => new Pair({ pair: [key, resolveWeakValue(self[key])] })\n          ));\n        },\n        to_Iterator(self) {\n          return dictSortedKeys(self)[Symbol.iterator]();\n        },\n        for_each_key(self, fn2) {\n          for (const key of dictSortedKeys(self)) {\n            fn2(key);\n          }\n          return self;\n        },\n        for_each_value(self, fn2) {\n          for (const key of dictSortedKeys(self)) {\n            fn2(resolveWeakValue(self[key]));\n          }\n          return self;\n        },\n        for_each_pair(self, fn2) {\n          for (const key of dictSortedKeys(self)) {\n            fn2(new Pair({ pair: [key, resolveWeakValue(self[key])] }));\n          }\n          return self;\n        },\n        clear(self) {\n          if (isDictMethodReceiver(self)) {\n            for (const key of Object.keys(self)) {\n              releaseCollectionValue(self, self[key]);\n              delete self[key];\n            }\n          }\n          return self;\n        }\n      });\n      var DICT_ZERO_ARG_METHODS = /* @__PURE__ */ new Set([\n        "clear",\n        "copy",\n        "count",\n        "empty",\n        "enumerate",\n        "is_empty",\n        "keys",\n        "kv",\n        "length",\n        "sorted_keys",\n        "to_Array",\n        "to_Iterator",\n        "values"\n      ]);\n      function getDictMethod(object, property) {\n        if (typeof property === "symbol") {\n          return null;\n        }\n        const name2 = String(property);\n        for (let proto = Object.getPrototypeOf(object); proto; proto = Object.getPrototypeOf(proto)) {\n          const descriptor = Object.getOwnPropertyDescriptor(proto, name2);\n          if (descriptor && typeof descriptor.value === "function") {\n            return null;\n          }\n        }\n        if (!isDictMethodReceiver(object) || Object.prototype.hasOwnProperty.call(object, name2) || !Object.prototype.hasOwnProperty.call(DICT_METHODS, name2)) {\n          return null;\n        }\n        return function zuzuDictMethod(...args) {\n          return DICT_METHODS[name2](object, ...args);\n        };\n      }\n      var ZuzuMethod = class {\n        constructor(name2, fn2) {\n          this.name = String(name2 || "");\n          this.fn = fn2;\n        }\n        invoke(self, args = []) {\n          return this.fn.apply(self, args);\n        }\n        to_String() {\n          return this.name;\n        }\n      };\n      function zuzuBoundMethod(receiver, name2, fn2) {\n        const methodName = String(name2 || "");\n        const bound = function __zuzu_bound_method(...args) {\n          return fn2.apply(receiver, args);\n        };\n        Object.defineProperty(bound, "__zuzu_method", {\n          value: true,\n          enumerable: false,\n          configurable: true\n        });\n        Object.defineProperty(bound, "__zuzu_bound_receiver", {\n          value: receiver,\n          enumerable: false,\n          configurable: true\n        });\n        Object.defineProperty(bound, "__zuzu_bound_method_name", {\n          value: methodName,\n          enumerable: false,\n          configurable: true\n        });\n        bound.invoke = function invoke(self, args = []) {\n          return fn2.apply(self, args);\n        };\n        bound.to_String = function to_String() {\n          return methodName;\n        };\n        return bound;\n      }\n      function zuzuTypeof(value) {\n        value = resolveWeakValue(value);\n        if (value == null) {\n          return "Null";\n        }\n        if (value && value.__zuzu_method) {\n          return "Method";\n        }\n        if (value instanceof ZuzuMethod) {\n          return "Method";\n        }\n        if (isPairListLike(value)) {\n          return "PairList";\n        }\n        if (value && (typeof value === "object" || typeof value === "function") && typeof value.__zuzu_type_name === "string") {\n          return value.__zuzu_type_name;\n        }\n        if (isBagLike(value)) {\n          return "Bag";\n        }\n        if (isSetLike(value)) {\n          return "Set";\n        }\n        if (Array.isArray(value)) {\n          return "Array";\n        }\n        if (value instanceof Pair) {\n          return "Pair";\n        }\n        if (value instanceof RegExp) {\n          return "Regexp";\n        }\n        if (Object.prototype.toString.call(value) === "[object RegExp]") {\n          return "Regexp";\n        }\n        if (typeof value === "boolean") {\n          return "Boolean";\n        }\n        if (typeof value === "number") {\n          return "Number";\n        }\n        if (typeof value === "string") {\n          return "String";\n        }\n        if (value instanceof ZuzuBinary) {\n          return "BinaryString";\n        }\n        if (typeof value === "function") {\n          const source = Function.prototype.toString.call(value);\n          if (/^\\s*class\\b/.test(source)) {\n            return "Class";\n          }\n          return "Function";\n        }\n        if (value && value.constructor) {\n          const ctorName = value.constructor.name || "Object";\n          if (ctorName === "Object") {\n            return "Dict";\n          }\n          if (ctorName === "Error") {\n            return "Exception";\n          }\n          return ctorName;\n        }\n        return "Object";\n      }\n      function zuzuInstanceof(value, klass) {\n        value = resolveWeakValue(value);\n        klass = resolveWeakValue(klass);\n        if (klass == null) {\n          return value == null ? 1 : 0;\n        }\n        const klassName = typeof klass === "function" && klass.name ? klass.name : "";\n        if (klassName === "Any") {\n          return 1;\n        }\n        if (klassName === "Null") {\n          return value == null ? 1 : 0;\n        }\n        if (klassName === "Boolean" || klass === Boolean) {\n          return typeof value === "boolean" || Object.prototype.toString.call(value) === "[object Boolean]" ? 1 : 0;\n        }\n        if (klassName === "Number" || klass === Number) {\n          return typeof value === "number" || Object.prototype.toString.call(value) === "[object Number]" ? 1 : 0;\n        }\n        if (klassName === "String" || klass === String) {\n          return typeof value === "string" || Object.prototype.toString.call(value) === "[object String]" ? 1 : 0;\n        }\n        if (klassName === "Array" || klass === Array) {\n          return Array.isArray(value) ? 1 : 0;\n        }\n        if (klassName === "BinaryString") {\n          return value instanceof ZuzuBinary ? 1 : 0;\n        }\n        if (klassName === "Function" || klass === Function) {\n          return typeof value === "function" ? 1 : 0;\n        }\n        if (klassName === "Exception") {\n          if (value == null) {\n            return 0;\n          }\n          if (value instanceof Error) {\n            return 1;\n          }\n          const valueName = String(\n            value.name || value.constructor && value.constructor.name || ""\n          );\n          return [\n            "Exception",\n            "TypeException",\n            "ExhaustedException",\n            "CancelledException",\n            "TimeoutException",\n            "ChannelClosedException"\n          ].includes(valueName) ? 1 : 0;\n        }\n        if (klassName === "TypeException") {\n          if (value == null) {\n            return 0;\n          }\n          const valueName = String(\n            value.name || value.constructor && value.constructor.name || ""\n          );\n          return valueName === "TypeException" ? 1 : 0;\n        }\n        if (klassName === "ExhaustedException") {\n          if (value == null) {\n            return 0;\n          }\n          const valueName = String(\n            value.name || value.constructor && value.constructor.name || ""\n          );\n          return valueName === "ExhaustedException" ? 1 : 0;\n        }\n        if ([\n          "CancelledException",\n          "TimeoutException",\n          "ChannelClosedException"\n        ].includes(klassName)) {\n          if (value == null) {\n            return 0;\n          }\n          const valueName = String(\n            value.name || value.constructor && value.constructor.name || ""\n          );\n          return valueName === klassName ? 1 : 0;\n        }\n        if (klassName === "Collection") {\n          return Array.isArray(value) || isSetLike(value) || isBagLike(value) || zuzuTypeof(value) === "Dict" ? 1 : 0;\n        }\n        if (klassName === "Dict") {\n          return zuzuTypeof(value) === "Dict" ? 1 : 0;\n        }\n        if (klassName === "Set") {\n          return isSetLike(value) ? 1 : 0;\n        }\n        if (klassName === "Bag") {\n          return isBagLike(value) ? 1 : 0;\n        }\n        if (klassName === "Class") {\n          return typeof value === "function" ? 1 : 0;\n        }\n        if (klassName === "Object" || klass === Object) {\n          return value !== null && typeof value === "object" ? 1 : 0;\n        }\n        try {\n          return value instanceof klass ? 1 : 0;\n        } catch (_err) {\n          return 0;\n        }\n      }\n      function isNativeErrorConstructorName(name2) {\n        return [\n          "Error",\n          "EvalError",\n          "RangeError",\n          "ReferenceError",\n          "SyntaxError",\n          "TypeError",\n          "URIError"\n        ].includes(String(name2 || ""));\n      }\n      function zuzuTrait(name2, methods, source = null, captures = {}) {\n        const trait = {\n          __zuzu_trait_name: String(name2 || ""),\n          __zuzu_trait_methods: methods || {}\n        };\n        if (source != null) {\n          Object.defineProperty(trait, "__zuzu_marshal_meta", {\n            value: {\n              kind: "trait",\n              name: String(name2 || ""),\n              source: String(source),\n              captures: captures || {}\n            },\n            enumerable: false,\n            configurable: true,\n            writable: true\n          });\n        }\n        return trait;\n      }\n      var perObjectTraitClassCache = /* @__PURE__ */ new WeakMap();\n      function isZuzuIdentifierName(name2) {\n        return /^[A-Za-z_][A-Za-z0-9_]*$/u.test(String(name2 || ""));\n      }\n      function zuzuClassWithTraits(base, traits) {\n        if (typeof base !== "function") {\n          throw new Error(`TypeException: new with traits expects Class, got ${zuzuTypeof(base)}`);\n        }\n        const traitList = Array.isArray(traits) ? traits : [];\n        let node = perObjectTraitClassCache.get(base);\n        if (!node) {\n          node = /* @__PURE__ */ new WeakMap();\n          perObjectTraitClassCache.set(base, node);\n        }\n        for (const trait of traitList) {\n          if (!trait || !trait.__zuzu_trait_methods) {\n            throw new Error(`TypeException: new with traits expects Trait, got ${zuzuTypeof(trait)}`);\n          }\n          let next = node.get(trait);\n          if (!next) {\n            next = /* @__PURE__ */ new WeakMap();\n            node.set(trait, next);\n          }\n          node = next;\n        }\n        if (node.__zuzu_class) {\n          return node.__zuzu_class;\n        }\n        const rawName = base.__zuzu_class_name || base.name || "Object";\n        const name2 = isZuzuIdentifierName(rawName) ? rawName : "__zuzu_per_object_class";\n        const captures = { __zuzu_per_object_base: base };\n        const traitNames = traitList.map((trait, index) => {\n          const captureName = `__zuzu_per_object_trait_${index}`;\n          captures[captureName] = trait;\n          return captureName;\n        });\n        const source = `class ${name2} extends __zuzu_per_object_base with ${traitNames.join(", ")};`;\n        const klass = defineZuzuClass(rawName, base, {\n          marshalSource: source,\n          marshalCaptures: captures,\n          traits: traitList,\n          fields: [],\n          methods: {},\n          statics: {},\n          nested: {}\n        });\n        Object.defineProperty(node, "__zuzu_class", {\n          value: klass,\n          enumerable: false,\n          configurable: true,\n          writable: true\n        });\n        return klass;\n      }\n      function zuzuApplyTraits(klass, traits) {\n        if (!klass || !klass.prototype || !Array.isArray(traits)) {\n          return klass;\n        }\n        if (!Object.prototype.hasOwnProperty.call(klass, "__zuzu_traits")) {\n          const desc = /* @__PURE__ */ Object.create(null);\n          desc.value = /* @__PURE__ */ new Set();\n          desc.enumerable = false;\n          desc.configurable = true;\n          desc.writable = true;\n          Object.defineProperty(klass, "__zuzu_traits", desc);\n        }\n        for (const trait of traits) {\n          if (!trait || !trait.__zuzu_trait_methods) {\n            continue;\n          }\n          klass.__zuzu_traits.add(trait.__zuzu_trait_name || "");\n          for (const [name2, fn2] of Object.entries(trait.__zuzu_trait_methods)) {\n            if (typeof fn2 !== "function") {\n              continue;\n            }\n            if (Object.prototype.hasOwnProperty.call(klass.prototype, name2) && typeof klass.prototype[name2] === "function") {\n              klass.prototype[`__zuzu_trait_super__${name2}`] = fn2;\n            } else {\n              klass.prototype[name2] = fn2;\n            }\n          }\n        }\n        return klass;\n      }\n      function zuzuDoes(value, trait) {\n        value = resolveWeakValue(value);\n        if (value == null || !trait) {\n          return 0;\n        }\n        const name2 = trait.__zuzu_trait_name || trait.name || String(trait);\n        let ctor = value.constructor;\n        while (ctor) {\n          if (ctor.__zuzu_traits instanceof Set && ctor.__zuzu_traits.has(name2)) {\n            return 1;\n          }\n          ctor = Object.getPrototypeOf(ctor);\n        }\n        return 0;\n      }\n      function zuzuStoreField(object, field, value) {\n        const stored = field.isWeakStorage ? makeWeakValue(value) : retainValue(value);\n        releaseValue(object[field.name]);\n        object[field.name] = stored;\n        return stored;\n      }\n      function defineZuzuClass(name2, base, spec = {}) {\n        const parent = typeof base === "function" ? base : Object;\n        const fields = Array.isArray(spec.fields) ? spec.fields : [];\n        const traits = Array.isArray(spec.traits) ? spec.traits : [];\n        const methods = spec.methods && typeof spec.methods === "object" ? spec.methods : {};\n        const statics = spec.statics && typeof spec.statics === "object" ? spec.statics : {};\n        const nested = spec.nested && typeof spec.nested === "object" ? spec.nested : {};\n        const ctor = {\n          [name2]: class extends parent {\n            constructor(...args) {\n              const skipBuild = args[0] === ZUZU_SKIP_BUILD;\n              const ctorArgs = skipBuild ? args.slice(1) : args;\n              const superArgs = parent.__zuzu_class_name ? skipBuild ? args : [ZUZU_SKIP_BUILD, ...ctorArgs] : ctorArgs;\n              super(...superArgs);\n              if (this instanceof Error) {\n                this.name = name2;\n              }\n              for (const field of fields) {\n                let value = null;\n                if (field.defaultValue && typeof field.defaultValue === "function") {\n                  value = field.defaultValue.call(this);\n                }\n                zuzuStoreField(this, field, value);\n              }\n              let named = null;\n              const lastArg = ctorArgs[ctorArgs.length - 1];\n              if (ctorArgs.length === 1 && isPairListLike(ctorArgs[0])) {\n                named = ctorArgs[0];\n              } else if (ctorArgs.length === 1 && ctorArgs[0] && typeof ctorArgs[0] === "object" && !Array.isArray(ctorArgs[0])) {\n                named = ctorArgs[0];\n              } else if (ctorArgs.length > 1 && isPairListLike(lastArg)) {\n                named = lastArg;\n              } else if (ctorArgs.length > 1 && lastArg && typeof lastArg === "object" && !Array.isArray(lastArg)) {\n                named = lastArg;\n              }\n              const releaseTemporaryNamed = !skipBuild && isPairListLike(named) && named.__zuzu_temporary_call_args === true;\n              try {\n                if (named) {\n                  for (const field of fields) {\n                    const incoming = isPairListLike(named) ? named.get(field.name, resolveWeakValue(this[field.name])) : Object.prototype.hasOwnProperty.call(named, field.name) ? named[field.name] : resolveWeakValue(this[field.name]);\n                    if (field.typeName && incoming != null && !zuzuTypeMatches(incoming, field.typeName)) {\n                      throw new Error(`TypeException: field \'${field.name}\' must be ${field.typeName}, got ${zuzuTypeof(incoming)}`);\n                    }\n                    zuzuStoreField(this, field, incoming);\n                  }\n                }\n                for (const [nestedName, nestedClass] of Object.entries(nested)) {\n                  this[nestedName] = nestedClass;\n                }\n                if (!skipBuild && typeof this.__build__ === "function") {\n                  this.__build__();\n                }\n              } finally {\n                if (releaseTemporaryNamed) {\n                  releaseCollectionValues(named);\n                }\n              }\n            }\n          }\n        }[name2];\n        for (const field of fields) {\n          if (Array.isArray(field.accessors)) {\n            if (field.accessors.includes("get") && typeof ctor.prototype[`get_${field.name}`] !== "function") {\n              ctor.prototype[`get_${field.name}`] = function _get_field() {\n                return resolveWeakValue(this[field.name]);\n              };\n            }\n            if (field.accessors.includes("set") && typeof ctor.prototype[`set_${field.name}`] !== "function") {\n              ctor.prototype[`set_${field.name}`] = function _set_field(value) {\n                if (field.typeName && value != null && !zuzuTypeMatches(value, field.typeName)) {\n                  throw new Error(`TypeException: field \'${field.name}\' must be ${field.typeName}, got ${zuzuTypeof(value)}`);\n                }\n                zuzuStoreField(this, field, value);\n                return this;\n              };\n            }\n            if (field.accessors.includes("clear") && typeof ctor.prototype[`clear_${field.name}`] !== "function") {\n              ctor.prototype[`clear_${field.name}`] = function _clear_field() {\n                zuzuStoreField(this, field, null);\n                return this;\n              };\n            }\n            if (field.accessors.includes("has") && typeof ctor.prototype[`has_${field.name}`] !== "function") {\n              ctor.prototype[`has_${field.name}`] = function _has_field() {\n                return resolveWeakValue(this[field.name]) != null ? 1 : 0;\n              };\n            }\n          }\n        }\n        for (const [methodName, fn2] of Object.entries(methods)) {\n          ctor.prototype[methodName] = fn2;\n        }\n        for (const [methodName, fn2] of Object.entries(statics)) {\n          ctor[methodName] = fn2;\n        }\n        for (const [nestedName, nestedClass] of Object.entries(nested)) {\n          ctor[nestedName] = nestedClass;\n        }\n        zuzuApplyTraits(ctor, traits);\n        Object.defineProperty(ctor, "__zuzu_class_name", {\n          value: name2,\n          enumerable: false,\n          configurable: true,\n          writable: true\n        });\n        Object.defineProperty(ctor, "__zuzu_class_spec", {\n          value: {\n            fields: fields.map((field) => ({ ...field })),\n            traits: traits.slice(),\n            methods: { ...methods },\n            statics: { ...statics },\n            nested: { ...nested }\n          },\n          enumerable: false,\n          configurable: true,\n          writable: true\n        });\n        if (typeof spec.marshalSource === "string") {\n          Object.defineProperty(ctor, "__zuzu_marshal_meta", {\n            value: {\n              kind: "class",\n              name: name2,\n              source: spec.marshalSource,\n              captures: spec.marshalCaptures || {}\n            },\n            enumerable: false,\n            configurable: true,\n            writable: true\n          });\n        }\n        return ctor;\n      }\n      function zuzuGetMember(object, property) {\n        object = resolveWeakValue(object);\n        if (object == null) {\n          return null;\n        }\n        if (property !== "length") {\n          const arrayMethod = getArrayMethod(object, property);\n          if (arrayMethod && ARRAY_ZERO_ARG_METHODS.has(String(property))) {\n            return arrayMethod();\n          }\n          if (arrayMethod) {\n            return arrayMethod;\n          }\n        }\n        const setMethod = getSetMethod(object, property);\n        if (setMethod && SET_ZERO_ARG_METHODS.has(String(property))) {\n          return setMethod();\n        }\n        if (setMethod) {\n          return setMethod;\n        }\n        const value = resolveWeakValue(object[property]);\n        if (typeof value === "function" && value.length === 0 && !value.__zuzu_marshal_meta) {\n          return value.call(object);\n        }\n        const dictMethod = getDictMethod(object, property);\n        if (dictMethod && DICT_ZERO_ARG_METHODS.has(String(property))) {\n          return dictMethod();\n        }\n        if (dictMethod) {\n          return dictMethod;\n        }\n        return resolveWeakValue(value);\n      }\n      function zuzuResolveBraceKey(_object, literalProperty, _getDynamicProperty) {\n        const literal = String(literalProperty || "");\n        return literal;\n      }\n      function zuzuGetBraceMember(object, literalProperty, getDynamicProperty) {\n        object = resolveWeakValue(object);\n        if (object == null) {\n          return null;\n        }\n        return zuzuGetIndex(object, zuzuResolveBraceKey(object, literalProperty, getDynamicProperty));\n      }\n      function zuzuCallMember(object, property, ...args) {\n        object = resolveWeakValue(object);\n        if (object == null) {\n          throw new TypeError(`Cannot call member ${String(property)} of null`);\n        }\n        if (property instanceof ZuzuMethod || property && property.__zuzu_method) {\n          return property.invoke(object, args);\n        }\n        const arrayMethod = getArrayMethod(object, property);\n        if (arrayMethod) {\n          return arrayMethod(...args);\n        }\n        const setMethod = getSetMethod(object, property);\n        if (setMethod) {\n          return setMethod(...args);\n        }\n        const dictMethod = getDictMethod(object, property);\n        if (dictMethod) {\n          return dictMethod(...args);\n        }\n        const value = resolveWeakValue(object[property]);\n        if (typeof value === "function") {\n          return value.apply(object, args);\n        }\n        let proto = Object.getPrototypeOf(object);\n        while (proto) {\n          const descriptor = Object.getOwnPropertyDescriptor(proto, property);\n          if (descriptor && typeof descriptor.value === "function") {\n            return descriptor.value.apply(object, args);\n          }\n          proto = Object.getPrototypeOf(proto);\n        }\n        throw new TypeError(`${String(property)} is not a function`);\n      }\n      function zuzuMaybeDemolish(value, preserved = null) {\n        const original = value;\n        value = resolveWeakValue(value);\n        const shouldDemolish = value && value !== resolveWeakValue(preserved) && typeof value.__demolish__ === "function";\n        releaseValue(original, {\n          preserveCollectionValues: value === resolveWeakValue(preserved),\n          suppressDemolish: true\n        });\n        if (shouldDemolish && strongReferenceCount(value) === 0) {\n          return value.__demolish__();\n        }\n        return null;\n      }\n      function zuzuCan(value, methodName) {\n        value = resolveWeakValue(value);\n        if (value == null) {\n          return 0;\n        }\n        const key = String(methodName || "");\n        if (getArrayMethod(value, key)) {\n          return 1;\n        }\n        if (getSetMethod(value, key)) {\n          return 1;\n        }\n        if (getDictMethod(value, key)) {\n          return 1;\n        }\n        if (typeof value[key] === "function") {\n          return 1;\n        }\n        let proto = Object.getPrototypeOf(value);\n        while (proto) {\n          const descriptor = Object.getOwnPropertyDescriptor(proto, key);\n          if (descriptor && typeof descriptor.value === "function") {\n            return 1;\n          }\n          proto = Object.getPrototypeOf(proto);\n        }\n        return 0;\n      }\n      function zuzuSuperCall(self, klass, methodName, args = []) {\n        const method = String(methodName || "");\n        const argv = Array.isArray(args) ? args : [];\n        if (klass && self && typeof self[`__zuzu_trait_super__${method}`] === "function") {\n          return self[`__zuzu_trait_super__${method}`].apply(self, argv);\n        }\n        if (!klass && self && self.constructor) {\n          klass = self.constructor;\n        }\n        if (klass && klass.prototype) {\n          const parentProto = Object.getPrototypeOf(klass.prototype);\n          if (parentProto && typeof parentProto[method] === "function") {\n            return parentProto[method].apply(self, argv);\n          }\n        }\n        return null;\n      }\n      function zuzuSuperStaticCall(klass, methodName, args = []) {\n        const method = String(methodName || "");\n        const argv = Array.isArray(args) ? args : [];\n        if (!klass) {\n          return null;\n        }\n        const parentClass = Object.getPrototypeOf(klass);\n        if (parentClass && typeof parentClass[method] === "function") {\n          return parentClass[method].apply(klass, argv);\n        }\n        return null;\n      }\n      function zuzuSuperDispatch(isStatic, self, klass, methodName, args = []) {\n        return isStatic ? zuzuSuperStaticCall(klass, methodName, args) : zuzuSuperCall(self, klass, methodName, args);\n      }\n      function refIndex(target, index) {\n        target = resolveWeakValue(target);\n        return function refValue(maybeValue) {\n          if (arguments.length === 0) {\n            if (target instanceof ZuzuBinary) {\n              return target.at(index);\n            }\n            return resolveWeakValue(target[index]);\n          }\n          if (target instanceof ZuzuBinary) {\n            throw new Error("Exception: BinaryString index assignment is not supported");\n          }\n          target[index] = maybeValue;\n          return maybeValue;\n        };\n      }\n      function zuzuGetIndex(target, index) {\n        target = resolveWeakValue(target);\n        if (target == null) {\n          return null;\n        }\n        const key = String(index);\n        if (typeof target === "function" && target.prototype) {\n          if (typeof target.prototype[key] === "function") {\n            return new ZuzuMethod(key, target.prototype[key]);\n          }\n        }\n        if (target instanceof ZuzuBinary) {\n          return target.at(index);\n        }\n        if (isPairListLike(target)) {\n          return resolveWeakValue(target.get(index, null));\n        }\n        if (typeof target === "string" || Array.isArray(target)) {\n          let resolved = Number(index);\n          if (Number.isFinite(resolved)) {\n            const indexed = typeof target === "string" ? [...target] : target;\n            if (resolved < 0) {\n              resolved = indexed.length + resolved;\n            }\n            return resolveWeakValue(indexed[resolved] ?? null);\n          }\n        }\n        if (target && typeof target === "object" && target.constructor && typeof target.constructor.__zuzu_class_name === "string" && !Object.prototype.hasOwnProperty.call(target, key) && typeof target[key] === "function") {\n          return zuzuBoundMethod(target, key, target[key]);\n        }\n        return resolveWeakValue(target[index]);\n      }\n      function zuzuSliceBounds(size, from, length) {\n        let start = Number(from ?? 0);\n        if (!Number.isFinite(start)) {\n          start = 0;\n        }\n        if (start < 0) {\n          start = size + start;\n        }\n        start = Math.max(0, Math.min(size, start));\n        if (length == null) {\n          return [start, size];\n        }\n        const span = Number(length);\n        if (!Number.isFinite(span)) {\n          return [start, start];\n        }\n        const end = span < 0 ? Math.max(0, Math.min(size, size + span)) : Math.max(0, Math.min(size, start + span));\n        return [Math.min(start, end), Math.max(start, end)];\n      }\n      function zuzuGetSlice(target, from, length) {\n        target = resolveWeakValue(target);\n        if (target == null) {\n          return null;\n        }\n        if (typeof target === "string") {\n          const chars = [...target];\n          const [start, end] = zuzuSliceBounds(chars.length, from, length);\n          return chars.slice(start, end).join("");\n        }\n        if (target instanceof ZuzuBinary) {\n          const [start, end] = zuzuSliceBounds(target.length, from, length);\n          return target.slice(start, end);\n        }\n        if (Array.isArray(target)) {\n          const [start, end] = zuzuSliceBounds(target.length, from, length);\n          return target.slice(start, end);\n        }\n        return target.slice(from, length == null ? void 0 : Number(from) + Number(length));\n      }\n      function zuzuAssignSlice(target, from, length, value) {\n        const hasLength = length != null;\n        const replacement = value == null ? "" : value;\n        if (typeof target === "string") {\n          const chars = [...target];\n          const [start2, end] = zuzuSliceBounds(chars.length, from, length);\n          chars.splice(start2, end - start2, ...[...String(replacement)]);\n          return chars.join("");\n        }\n        const start = Number(from);\n        if (Array.isArray(target)) {\n          const items = Array.isArray(replacement) ? replacement : [replacement];\n          const span = hasLength ? Number(length) : null;\n          if (hasLength) {\n            target.splice(start, span, ...items);\n          } else {\n            target.splice(start, target.length - start, ...items);\n          }\n          return target;\n        }\n        if (target instanceof ZuzuBinary) {\n          if (!(value instanceof ZuzuBinary)) {\n            throw new Error(`TypeException: BinaryString slice assignment expects BinaryString, got ${zuzuTypeof(value)}`);\n          }\n          const [byteStart, byteEnd] = zuzuSliceBounds(target.length, from, length);\n          const next = new Uint8Array(target.length - (byteEnd - byteStart) + value.bytes.length);\n          next.set(target.bytes.slice(0, byteStart), 0);\n          next.set(value.bytes, byteStart);\n          next.set(target.bytes.slice(byteEnd), byteStart + value.bytes.length);\n          target.bytes = next;\n          return target;\n        }\n        throw new Error(`TypeException: slice assignment expects String or Array, got ${zuzuTypeof(target)}`);\n      }\n      function refKey(target, key) {\n        target = resolveWeakValue(target);\n        return function refValue(maybeValue) {\n          if (arguments.length === 0) {\n            return resolveWeakValue(target[key]);\n          }\n          target[key] = maybeValue;\n          return maybeValue;\n        };\n      }\n      function assignIndexedValue(target, index, value, isWeakWrite = false, assignTarget = null) {\n        target = resolveWeakValue(target);\n        if (target == null) {\n          throw new Error("TypeException: cannot assign to null");\n        }\n        if (target instanceof ZuzuBinary) {\n          if (!(value instanceof ZuzuBinary)) {\n            throw new Error(`TypeException: BinaryString index assignment expects BinaryString, got ${zuzuTypeof(value)}`);\n          }\n          zuzuAssignSlice(target, index, 1, value);\n          if (typeof assignTarget === "function") {\n            assignTarget(target);\n          }\n          return target;\n        }\n        if (typeof target === "string") {\n          let resolved = Number(index);\n          if (!Number.isFinite(resolved)) {\n            throw new Error("TypeException: String index assignment expects numeric index");\n          }\n          const chars = [...target];\n          if (resolved < 0) {\n            resolved = chars.length + resolved;\n          }\n          resolved = Math.max(0, Math.min(chars.length, resolved));\n          chars.splice(resolved, resolved < chars.length ? 1 : 0, ...[...String(value ?? "")]);\n          const updated = chars.join("");\n          return typeof assignTarget === "function" ? assignTarget(updated) : updated;\n        }\n        if (isPairListLike(target)) {\n          const stored2 = isWeakWrite ? makeWeakValue(value) : retainCollectionValue(target, value);\n          target.list.push([String(index), stored2]);\n          return stored2;\n        }\n        const stored = isWeakWrite ? makeWeakValue(value) : retainCollectionValue(target, value);\n        releaseCollectionValue(target, target[index]);\n        target[index] = stored;\n        return stored;\n      }\n      function refSlice(target, from, length) {\n        target = resolveWeakValue(target);\n        return function refSliceValue(maybeValue) {\n          const start = Number(from);\n          const hasLength = length != null;\n          const span = hasLength ? Number(length) : null;\n          if (arguments.length === 0) {\n            return zuzuGetSlice(target, start, hasLength ? span : null);\n          }\n          if (target instanceof ZuzuBinary || typeof target === "string") {\n            return zuzuAssignSlice(target, start, hasLength ? span : null, maybeValue);\n          }\n          if (!hasLength) {\n            target.splice(start, target.length - start, ...maybeValue);\n            return maybeValue;\n          }\n          target.splice(start, span, ...maybeValue);\n          return maybeValue;\n        };\n      }\n      function makePathOperator(runtime, filename) {\n        return function zuzuPathOp(haystack, pathSpec, mode = "first") {\n          const pathObj = resolvePathObject(runtime, filename, pathSpec);\n          if (mode === "all") {\n            return pathObj.query(haystack);\n          }\n          if (mode === "exists") {\n            return pathObj.exists(haystack);\n          }\n          return pathObj.first(haystack, null);\n        };\n      }\n      function resolveActivePathClass(runtime, filename) {\n        const internals = runtime.loadModule("std/internals", filename);\n        if (!internals || typeof internals.getupperprop !== "function") {\n          return null;\n        }\n        return internals.getupperprop(0, "paths");\n      }\n      function resolvePathObject(runtime, filename, pathSpec) {\n        let PathClass = resolveActivePathClass(runtime, filename);\n        const pathText = String(pathSpec ?? "");\n        if (!PathClass) {\n          const zzpath = runtime.loadModule("std/path/zz", filename);\n          PathClass = zzpath && zzpath.ZZPath ? zzpath.ZZPath : null;\n        }\n        if (!PathClass) {\n          throw new Error("Exception: no path implementation available");\n        }\n        return pathSpec && typeof pathSpec === "object" && typeof pathSpec.query === "function" ? pathSpec : new PathClass({ path: pathText });\n      }\n      function makePathAssignmentOperator(runtime, filename) {\n        return function zuzuPathAssign(haystack, pathSpec, value, mode = "first", op = ":=", isWeakWrite = false) {\n          const pathObj = resolvePathObject(runtime, filename, pathSpec);\n          const storedValue = isWeakWrite ? makeWeakValue(value) : value;\n          if (mode === "all") {\n            return pathObj.assign_all(haystack, storedValue, op);\n          }\n          if (mode === "maybe") {\n            return pathObj.assign_maybe(haystack, storedValue, op);\n          }\n          return pathObj.assign_first(haystack, storedValue, op);\n        };\n      }\n      function makePathReferenceOperator(runtime, filename) {\n        return function zuzuPathRef(haystack, pathSpec, mode = "first") {\n          const pathObj = resolvePathObject(runtime, filename, pathSpec);\n          if (mode === "all") {\n            return pathObj.ref_all(haystack);\n          }\n          if (mode === "maybe") {\n            return pathObj.ref_maybe(haystack);\n          }\n          return pathObj.ref_first(haystack);\n        };\n      }\n      function callPathRef(refFn) {\n        if (typeof refFn !== "function") {\n          throw new Error("Exception: path reference target is not assignable");\n        }\n        return refFn();\n      }\n      function setPathRef(refFn, value) {\n        if (typeof refFn !== "function") {\n          throw new Error("Exception: path reference target is not assignable");\n        }\n        return refFn(value);\n      }\n      function makePathUpdateOperator(runtime, filename) {\n        return function zuzuPathUpdate(haystack, pathSpec, mode, operator, prefix) {\n          const pathObj = resolvePathObject(runtime, filename, pathSpec);\n          if (mode === "all") {\n            const refs = pathObj.ref_all(haystack);\n            const oldValues = [];\n            const newValues = [];\n            for (const refFn2 of refs) {\n              const oldValue2 = zuzuToNumber(callPathRef(refFn2));\n              const newValue2 = operator === "++" ? oldValue2 + 1 : oldValue2 - 1;\n              setPathRef(refFn2, newValue2);\n              oldValues.push(oldValue2);\n              newValues.push(newValue2);\n            }\n            return prefix ? newValues : oldValues;\n          }\n          if (mode === "maybe") {\n            const refFn2 = pathObj.ref_maybe(haystack);\n            if (refFn2 == null) {\n              return false;\n            }\n            const oldValue2 = zuzuToNumber(callPathRef(refFn2));\n            const newValue2 = operator === "++" ? oldValue2 + 1 : oldValue2 - 1;\n            setPathRef(refFn2, newValue2);\n            return true;\n          }\n          const refFn = pathObj.ref_first(haystack);\n          const oldValue = zuzuToNumber(callPathRef(refFn));\n          const newValue = operator === "++" ? oldValue + 1 : oldValue - 1;\n          setPathRef(refFn, newValue);\n          return prefix ? newValue : oldValue;\n        };\n      }\n      function zuzuTypeMatches(value, typeName2) {\n        value = resolveWeakValue(value);\n        if (typeName2 === "Any") {\n          return 1;\n        }\n        if (value == null) {\n          return 0;\n        }\n        if (typeName2 === "Number" || typeName2 === "String" || typeName2 === "Array" || typeName2 === "Dict" || typeName2 === "Set" || typeName2 === "Bag" || typeName2 === "PairList" || typeName2 === "Collection" || typeName2 === "Class" || typeName2 === "Function" || typeName2 === "Object" || typeName2 === "Exception" || typeName2 === "Regexp") {\n          if (typeName2 === "Collection") {\n            return Array.isArray(value) || isSetLike(value) || isBagLike(value) || isPairListLike(value) || zuzuTypeof(value) === "Dict" ? 1 : 0;\n          }\n          if (typeName2 === "Object") {\n            return value !== null && typeof value === "object" ? 1 : 0;\n          }\n          if (typeName2 === "PairList") {\n            return isPairListLike(value) ? 1 : 0;\n          }\n          if (typeName2 === "Exception") {\n            const globalType2 = globalThis.Exception;\n            if (globalType2 != null && zuzuInstanceof(value, globalType2)) {\n              return 1;\n            }\n            return value instanceof Error ? 1 : 0;\n          }\n          return zuzuTypeof(value) === typeName2 ? 1 : 0;\n        }\n        if (typeName2 === "BinaryString") {\n          return value instanceof ZuzuBinary ? 1 : 0;\n        }\n        if (typeName2 === "Boolean") {\n          if (typeof value === "boolean" || Object.prototype.toString.call(value) === "[object Boolean]") {\n            return 1;\n          }\n          if (typeof value === "number") {\n            return value === 0 || value === 1 ? 1 : 0;\n          }\n        }\n        if (typeName2 === "Regexp") {\n          return Object.prototype.toString.call(value) === "[object RegExp]" ? 1 : 0;\n        }\n        if (zuzuTypeof(value) === typeName2) {\n          return 1;\n        }\n        if (Array.isArray(value.__zuzu_type_names) && value.__zuzu_type_names.includes(typeName2)) {\n          return 1;\n        }\n        let proto = Object.getPrototypeOf(value);\n        while (proto) {\n          const ctor = proto.constructor;\n          if (ctor && ctor.name === typeName2) {\n            return 1;\n          }\n          proto = Object.getPrototypeOf(proto);\n        }\n        const globalType = globalThis[typeName2];\n        if (globalType == null) {\n          return 0;\n        }\n        return zuzuInstanceof(value, globalType) ? 1 : 0;\n      }\n      var ZuzuScript = class {\n        constructor(options = {}) {\n          if (options.host) {\n            this.host = options.host;\n          } else {\n            const { createNodeHost } = __require("./host/node-host");\n            this.host = createNodeHost(options);\n          }\n          this.repoRoot = this.host.repoRoot;\n          this.includePaths = this.host.includePaths;\n          this.moduleSearchRoots = defaultModuleSearchRoots(\n            this.host,\n            this.repoRoot,\n            this.includePaths\n          );\n          const allowCapabilities = new Set(Array.isArray(options.allowCapabilities) ? options.allowCapabilities.map((item) => String(item)) : []);\n          this.denyCapabilities = new Set(Array.isArray(options.denyCapabilities) ? options.denyCapabilities.map((item) => String(item)) : []);\n          for (const capability of ["gui"]) {\n            if (!allowCapabilities.has(capability) && !this.host.capabilities.has(capability)) {\n              this.denyCapabilities.add(capability);\n            }\n          }\n          this.denyModules = new Set(Array.isArray(options.denyModules) ? options.denyModules.map((item) => String(item)) : []);\n          this.debugLevel = Number.isFinite(Number(options.debugLevel)) ? Number(options.debugLevel) : 0;\n          this.moduleCache = /* @__PURE__ */ new Map();\n          this.moduleLoading = /* @__PURE__ */ new Set();\n          this.evalCapabilityOverrides = null;\n          this.outputLines = null;\n          this.stdoutHandler = null;\n          this.stderrHandler = null;\n          this.executionTimeoutMs = Number.isFinite(Number(options.executionTimeoutMs)) ? Number(options.executionTimeoutMs) : null;\n          this.transpiler = normalizeTranspilerName(\n            options.transpiler || DEFAULT_TRANSPILER\n          );\n          this.asyncImports = options.asyncImports === true;\n          if (typeof this.host.loadJsModule !== "function") {\n            this.host.loadJsModule = (filename) => __require(filename);\n          }\n        }\n        usesAsyncImports() {\n          return this.asyncImports || typeof this.host.hasAsyncModules === "function" && this.host.hasAsyncModules();\n        }\n        transpile(source, options = {}) {\n          return transpile(source, {\n            ...options,\n            transpiler: options.transpiler || this.transpiler,\n            asyncImports: options.asyncImports ?? this.usesAsyncImports()\n          });\n        }\n        getModuleSearchRoots() {\n          return this.moduleSearchRoots.slice();\n        }\n        isDeniedByCapability(moduleName) {\n          const required = capabilitiesForModule(moduleName);\n          for (const capability of required) {\n            if (this.isCapabilityDenied(capability)) {\n              return capability;\n            }\n            if (!this.host.capabilities.has(capability)) {\n              return capability;\n            }\n          }\n          return null;\n        }\n        isCapabilityDenied(capability) {\n          if (this.denyCapabilities.has(capability)) {\n            return true;\n          }\n          if (this.evalCapabilityOverrides) {\n            const flagName = `deny_${capability}`;\n            if (this.evalCapabilityOverrides[flagName]) {\n              return true;\n            }\n          }\n          return false;\n        }\n        enforceModulePolicy(moduleName) {\n          if (this.denyModules.has(moduleName)) {\n            throw new Error(`Denied module: ${moduleName}`);\n          }\n          const capability = this.isDeniedByCapability(moduleName);\n          if (capability) {\n            if (this.denyCapabilities.has(capability)) {\n              throw new Error(`Denied capability \'${capability}\' blocks module \'${moduleName}\'`);\n            }\n            throw new Error(`Module \'${moduleName}\' requires unsupported capability \'${capability}\' on host \'${this.host.name}\'`);\n          }\n        }\n        fileValueForFilename(filename) {\n          if (this.isCapabilityDenied("fs") || !this.host.capabilities.has("fs") || !filename || String(filename).startsWith("<") || String(filename).startsWith("(")) {\n            return null;\n          }\n          const { Path } = require_io();\n          return new Path(filename);\n        }\n        resolveModulePath(moduleName, fromFile) {\n          const fromDir = fromFile ? this.host.dirname(fromFile) : this.repoRoot;\n          if (!moduleName.startsWith(".") && !moduleName.startsWith("/")) {\n            const runtimeSupported = this.host.resolve(\n              this.repoRoot,\n              "modules",\n              `${moduleName}.js`\n            );\n            if (this.host.fileExists(runtimeSupported)) {\n              return runtimeSupported;\n            }\n          }\n          const candidates = [];\n          if (moduleName.startsWith(".") || moduleName.startsWith("/")) {\n            candidates.push(this.host.resolve(fromDir, moduleName));\n          } else {\n            for (const base of this.getModuleSearchRoots()) {\n              candidates.push(this.host.resolve(base, moduleName));\n            }\n          }\n          const withExt = [];\n          for (const candidate of candidates) {\n            withExt.push(candidate, `${candidate}.zzs`, `${candidate}.zzm`, `${candidate}.js`);\n          }\n          for (const candidate of withExt) {\n            if (this.host.fileExists(candidate)) {\n              return candidate;\n            }\n          }\n          throw new Error(`Unable to resolve module: ${moduleName}`);\n        }\n        buildContext(options = {}) {\n          const filename = options.filename;\n          const runtime = this;\n          taskRuntime2.setDebugLevel(this.debugLevel);\n          let context;\n          const capabilityFlags = /* @__PURE__ */ Object.create(null);\n          for (const name2 of this.host.capabilities) {\n            if (!this.denyCapabilities.has(name2)) {\n              capabilityFlags[name2] = 1;\n            }\n          }\n          if (this.evalCapabilityOverrides) {\n            for (const [flagName, denied] of Object.entries(this.evalCapabilityOverrides)) {\n              const capability = flagName.replace(/^deny_/, "");\n              if (denied) {\n                delete capabilityFlags[capability];\n              } else if (this.host.capabilities.has(capability) && !this.denyCapabilities.has(capability)) {\n                capabilityFlags[capability] = 1;\n              }\n            }\n          }\n          const moduleSearchRoots = this.getModuleSearchRoots();\n          const emit = (value) => {\n            let line = String(value);\n            if (line === "Infinity") {\n              line = "Inf";\n            } else if (line === "-Infinity") {\n              line = "-Inf";\n            }\n            if (this.outputLines) {\n              this.outputLines.push(line);\n            }\n            if (typeof this.stdoutHandler === "function") {\n              this.stdoutHandler(`${line}\n`);\n            } else if (!this.outputLines) {\n              this.host.consoleLog(line);\n            }\n          };\n          const emitStderr = (value) => {\n            const line = String(value);\n            if (typeof this.stderrHandler === "function") {\n              this.stderrHandler(`${line}\n`);\n            } else if (typeof console !== "undefined" && typeof console.warn === "function") {\n              console.warn(line);\n            }\n          };\n          installHostCollectionMethods();\n          const ZuzuException = class Exception extends Error {\n            constructor(value = "") {\n              if (isPairListLike(value)) {\n                super(value.get("message", ""));\n                this.name = "Exception";\n                this.file = value.get("file", null);\n                this.line = value.get("line", null);\n                this.code = value.get("code", null);\n                return;\n              }\n              if (value && typeof value === "object" && !Array.isArray(value) && Object.prototype.hasOwnProperty.call(value, "message")) {\n                super(value.message);\n                this.name = "Exception";\n                this.file = Object.prototype.hasOwnProperty.call(value, "file") ? value.file : null;\n                this.line = Object.prototype.hasOwnProperty.call(value, "line") ? value.line : null;\n                this.code = Object.prototype.hasOwnProperty.call(value, "code") ? value.code : null;\n                return;\n              }\n              super(value);\n              this.name = "Exception";\n              this.file = null;\n              this.line = null;\n              this.code = null;\n            }\n            to_String() {\n              const name2 = this.name || this.constructor.name || "Exception";\n              const message = String(this.message ?? "");\n              if (message === name2 || message.startsWith(`${name2}:`)) {\n                return message;\n              }\n              return message === "" ? name2 : `${name2}: ${message}`;\n            }\n            message() {\n              return String(this.message ?? "");\n            }\n          };\n          const ZuzuTypeException = class TypeException extends ZuzuException {\n            constructor(value = "") {\n              super(value);\n              this.name = "TypeException";\n            }\n          };\n          const snapshotSpreadArg = (input) => {\n            const value = resolveWeakValue(input);\n            if (Array.isArray(value)) {\n              return {\n                type: "spread_positional",\n                values: value.slice()\n              };\n            }\n            if (isPairListLike(value)) {\n              return {\n                type: "spread_named",\n                entries: value.list.map((pair) => [pair[0], pair[1]])\n              };\n            }\n            if (zuzuTypeof(value) === "Dict") {\n              return {\n                type: "spread_named",\n                entries: Object.keys(value).sort().map((key) => [key, value[key]])\n              };\n            }\n            throw new ZuzuTypeException(\n              `argument spread expects Array, Dict, or PairList, got ${zuzuTypeof(value)}`\n            );\n          };\n          const unpackDeclarationSource = (input) => {\n            const value = resolveWeakValue(input);\n            if (isPairListLike(value) || zuzuTypeof(value) === "Dict") {\n              return value;\n            }\n            throw new ZuzuTypeException(\n              `Declaration unpacking expects Dict or PairList, got ${zuzuTypeof(value)}`\n            );\n          };\n          const unpackDeclarationValue = (source, key, defaultThunk, name2, typeName2, isWeakStorage) => {\n            const valueSource = unpackDeclarationSource(source);\n            const normalized = normalizeDictKey(key);\n            let value;\n            let found = false;\n            if (isPairListLike(valueSource)) {\n              const pair = valueSource.list.find(\n                (entry) => entry[0] === normalized\n              );\n              if (pair) {\n                value = pair[1];\n                found = true;\n              }\n            } else if (Object.prototype.hasOwnProperty.call(valueSource, normalized)) {\n              value = valueSource[normalized];\n              found = true;\n            }\n            if (!found) {\n              value = typeof defaultThunk === "function" ? defaultThunk() : null;\n            }\n            if (typeName2 && typeName2 !== "Any" && !zuzuTypeMatches(value, typeName2)) {\n              throw new ZuzuTypeException(\n                `\'${name2}\' must be ${typeName2}, got ${zuzuTypeof(value)}`\n              );\n            }\n            return isWeakStorage ? makeWeakValue(value) : retainValue(value);\n          };\n          const spreadCallArgs = (parts) => {\n            const positional = [];\n            const named = [];\n            for (const part of parts) {\n              if (part.type === "positional") {\n                positional.push(part.value);\n                continue;\n              }\n              if (part.type === "named") {\n                named.push(part.value);\n                continue;\n              }\n              if (part.type === "spread_positional") {\n                positional.push(...part.values);\n                continue;\n              }\n              if (part.type === "spread_named") {\n                for (const entry of part.entries) {\n                  named.push(entry);\n                }\n                continue;\n              }\n              throw new ZuzuTypeException("invalid call argument descriptor");\n            }\n            if (named.length > 0) {\n              positional.push(makeTemporaryPairList(named));\n            }\n            return positional;\n          };\n          const normalizeZuzuException = (err) => {\n            if (err instanceof ZuzuException) {\n              return err;\n            }\n            if (err && err.__zuzu_nonlocal_return) {\n              return err;\n            }\n            if (err instanceof Error && [\n              "CancelledException",\n              "TimeoutException",\n              "ChannelClosedException"\n            ].includes(err.name)) {\n              return err;\n            }\n            if (err && typeof err === "object") {\n              const ctorName = err.constructor && err.constructor.name;\n              if (!isNativeErrorConstructorName(ctorName)) {\n                return err;\n              }\n            }\n            const message = err && err.message != null ? String(err.message) : String(err);\n            if (message.startsWith("TypeException:")) {\n              return new ZuzuTypeException({\n                message,\n                file: err && err.file != null ? err.file : null,\n                line: err && err.line != null ? err.line : null,\n                code: err && err.code != null ? err.code : null\n              });\n            }\n            return new ZuzuException({\n              message: message.startsWith("Exception: ") ? message.slice("Exception: ".length) : message,\n              file: err && err.file != null ? err.file : null,\n              line: err && err.line != null ? err.line : null,\n              code: err && err.code != null ? err.code : null\n            });\n          };\n          const ZuzuExhaustedException = class ExhaustedException extends Error {\n            constructor(message = "") {\n              super(message);\n              this.name = "ExhaustedException";\n            }\n            to_String() {\n              const message = String(this.message ?? "");\n              if (message === this.name || message.startsWith(`${this.name}:`)) {\n                return message;\n              }\n              return message === "" ? this.name : `${this.name}: ${message}`;\n            }\n          };\n          const defineRuntimeMethod = (proto, name2, fn2) => {\n            const desc = /* @__PURE__ */ Object.create(null);\n            desc.value = fn2;\n            desc.enumerable = false;\n            Object.defineProperty(proto, name2, desc);\n          };\n          if (!Number.prototype.contains) {\n            defineRuntimeMethod(Number.prototype, "contains", function _containsNumber(value) {\n              return Number(this.valueOf()) === Number(value) ? 1 : 0;\n            });\n          }\n          if (!Set.prototype.push) {\n            defineRuntimeMethod(Set.prototype, "length", function _lengthSet() {\n              return this.size;\n            });\n            defineRuntimeMethod(Set.prototype, "count", function _countSet() {\n              return this.size;\n            });\n            defineRuntimeMethod(Set.prototype, "empty", function _emptySet() {\n              return this.size === 0 ? 1 : 0;\n            });\n            defineRuntimeMethod(Set.prototype, "is_empty", function _isEmptySet() {\n              return this.empty();\n            });\n            defineRuntimeMethod(Set.prototype, "push", function _pushSet(...values) {\n              for (const v of values) {\n                addSetValue(this, v);\n              }\n              return this;\n            });\n            defineRuntimeMethod(Set.prototype, "push_weak", function _pushWeakSet(...values) {\n              for (const v of values) {\n                this.add(makeWeakValue(v));\n              }\n              return this;\n            });\n            defineRuntimeMethod(Set.prototype, "contains", function _containsSet(value) {\n              return contains(this, value);\n            });\n            defineRuntimeMethod(Set.prototype, "remove", function _removeSet(value) {\n              const resolved = resolveWeakValue(value);\n              if (this.delete(resolved)) {\n                releaseCollectionValue(this, resolved);\n              }\n              return this;\n            });\n            defineRuntimeMethod(Set.prototype, "to_Array", function _setToArray() {\n              return makeArray(this);\n            });\n            defineRuntimeMethod(Set.prototype, "to_Bag", function _setToBag() {\n              return makeBag([...this]);\n            });\n            defineRuntimeMethod(Set.prototype, "copy", function _setCopy() {\n              return makeSet(this);\n            });\n            defineRuntimeMethod(Set.prototype, "union", function _setUnion(other) {\n              return collectionUnion(this, other);\n            });\n            defineRuntimeMethod(Set.prototype, "intersection", function _setIntersection(other) {\n              return collectionIntersection(this, other);\n            });\n            defineRuntimeMethod(Set.prototype, "difference", function _setDifference(other) {\n              return collectionDifference(this, other);\n            });\n            defineRuntimeMethod(Set.prototype, "symmetric_difference", function _setSymmetricDifference(other) {\n              return collectionDifference(this.union(other), this.intersection(other));\n            });\n            defineRuntimeMethod(Set.prototype, "is_subset", function _setIsSubset(other) {\n              return collectionSubsetOf(this, other);\n            });\n            defineRuntimeMethod(Set.prototype, "is_superset", function _setIsSuperset(other) {\n              return collectionSupersetOf(this, other);\n            });\n            defineRuntimeMethod(Set.prototype, "is_disjoint", function _setIsDisjoint(other) {\n              return this.intersection(other).size === 0 ? 1 : 0;\n            });\n            defineRuntimeMethod(Set.prototype, "equals", function _setEquals(other) {\n              return collectionEquivalentOf(this, other);\n            });\n            defineRuntimeMethod(Set.prototype, "sort", function _setSort(fn2) {\n              return [...this].sort(fn2);\n            });\n            defineRuntimeMethod(Set.prototype, "sortstr", function _setSortstr() {\n              return [...this].sort(stringSortComparator);\n            });\n            defineRuntimeMethod(Set.prototype, "sortnum", function _setSortnum() {\n              return [...this].map((item) => Number(item)).sort((a, b) => a - b);\n            });\n            defineRuntimeMethod(Set.prototype, "map", function _setMap(fn2) {\n              return new Set([...this].map(fn2));\n            });\n            defineRuntimeMethod(Set.prototype, "grep", function _setGrep(fn2) {\n              return new Set([...this].filter(fn2));\n            });\n            defineRuntimeMethod(Set.prototype, "any", function _setAny(fn2) {\n              return [...this].some(fn2) ? 1 : 0;\n            });\n            defineRuntimeMethod(Set.prototype, "all", function _setAll(fn2) {\n              return [...this].every(fn2) ? 1 : 0;\n            });\n            defineRuntimeMethod(Set.prototype, "first", function _setFirst(fn2) {\n              for (const v of this) {\n                if (fn2(v)) {\n                  return v;\n                }\n              }\n              return null;\n            });\n            defineRuntimeMethod(Set.prototype, "remove_if", function _setRemoveIf(fn2) {\n              for (const v of [...this]) {\n                if (fn2(v)) {\n                  releaseCollectionValue(this, v);\n                  this.delete(v);\n                }\n              }\n              return this;\n            });\n            defineRuntimeMethod(Set.prototype, "for_each_value", function _setForEachValue(fn2) {\n              for (const v of this) {\n                fn2(v);\n              }\n              return this;\n            });\n          }\n          const fallbackDoneTesting = function done_testing(n = null) {\n            if (typeof globalThis._LEVEL === "number" && globalThis._LEVEL > 0) {\n              throw new Error("Unexpected done_testing() in subtest");\n            }\n            let seen = 0;\n            if (Array.isArray(runtime.outputLines)) {\n              for (const line of runtime.outputLines) {\n                if (/^ok\\b/.test(line) || /^not ok\\b/.test(line)) {\n                  seen++;\n                }\n              }\n            }\n            if (n != null && Number(n) !== Number(seen)) {\n              throw new Error(`Expected ${n} tests, but ran ${seen}`);\n            }\n            emit(`1..${seen}`);\n            if (typeof globalThis._FAILED === "number" && globalThis._FAILED > 0) {\n              throw new Error(`Failed ${globalThis._FAILED} tests`);\n            }\n            return true;\n          };\n          const systemGlobalSeed = {\n            language_version: 0,\n            runtime: "zuzu-js",\n            runtime_version: runtimeVersion,\n            platform: this.host.name,\n            inc: Object.freeze(moduleSearchRoots.slice()),\n            deny_fs: capabilityFlags.fs ? false : true,\n            deny_net: capabilityFlags.net ? false : true,\n            deny_perl: true,\n            deny_js: capabilityFlags.js ? false : true,\n            deny_proc: capabilityFlags.proc ? false : true,\n            deny_db: capabilityFlags.db ? false : true,\n            deny_clib: capabilityFlags.clib ? false : true,\n            deny_gui: capabilityFlags.gui ? false : true,\n            deny_worker: capabilityFlags.worker ? false : true\n          };\n          if (this.host.name === "node" && typeof process !== "undefined" && process.versions) {\n            systemGlobalSeed.nodejs_version = String(process.versions.node || "");\n          }\n          Object.freeze(systemGlobalSeed);\n          const currentSystem = () => {\n            const current = {\n              ...systemGlobalSeed,\n              deny_fs: this.isCapabilityDenied("fs") || !this.host.capabilities.has("fs"),\n              deny_net: this.isCapabilityDenied("net") || !this.host.capabilities.has("net"),\n              deny_perl: true,\n              deny_js: this.isCapabilityDenied("js") || !this.host.capabilities.has("js"),\n              deny_proc: this.isCapabilityDenied("proc") || !this.host.capabilities.has("proc"),\n              deny_db: this.isCapabilityDenied("db") || !this.host.capabilities.has("db"),\n              deny_clib: this.isCapabilityDenied("clib") || !this.host.capabilities.has("clib"),\n              deny_gui: this.isCapabilityDenied("gui") || !this.host.capabilities.has("gui"),\n              deny_worker: this.isCapabilityDenied("worker") || !this.host.capabilities.has("worker")\n            };\n            return Object.freeze(current);\n          };\n          context = {\n            ...options.globals || {},\n            __file__: this.fileValueForFilename(filename),\n            __zuzu_system_seed: systemGlobalSeed,\n            __zuzu_current_system: currentSystem,\n            __zuzu_operator_string: zuzuOperatorString,\n            DEBUG: this.debugLevel,\n            __zuzu_host_capabilities: capabilityFlags,\n            has_capability(name2) {\n              const key = String(name2);\n              return capabilityFlags[key] ? 1 : 0;\n            },\n            outputLines: this.outputLines,\n            done_testing: options.globals && typeof options.globals.done_testing === "function" ? options.globals.done_testing : fallbackDoneTesting,\n            exports: options.exports,\n            module: options.module,\n            console: {\n              log: (value) => this.host.consoleLog(value),\n              warn: (value) => emitStderr(value),\n              error: (value) => emitStderr(value)\n            },\n            Bag: ZuzuBag,\n            PairList,\n            Exception: ZuzuException,\n            TypeException: ZuzuTypeException,\n            ExhaustedException: ZuzuExhaustedException,\n            __zuzu_normalize_exception: normalizeZuzuException,\n            Task: taskRuntime2.Task,\n            CancelledException: taskRuntime2.CancelledException,\n            TimeoutException: taskRuntime2.TimeoutException,\n            ChannelClosedException: taskRuntime2.ChannelClosedException,\n            Null: null,\n            Any: function Any() {\n            },\n            Collection: function Collection() {\n            },\n            Class: function Class() {\n            },\n            BinaryString: BinaryString2,\n            say(value, ...parts) {\n              if (Array.isArray(value) && Object.prototype.hasOwnProperty.call(value, "raw")) {\n                let out = "";\n                for (let i = 0; i < value.length; i++) {\n                  out += value[i];\n                  if (i < parts.length) {\n                    out += String(parts[i]);\n                  }\n                }\n                emit(out);\n                return;\n              }\n              emit(value);\n            },\n            __zuzu_switch: runSwitch,\n            __zuzu_switch_async: runSwitchAsync,\n            __zuzu_match: runMatch,\n            __zuzu_to_regexp: operatorRegexp,\n            __zuzu_regex_replace: regexReplaceValue,\n            __zuzu_contains: contains,\n            __zuzu_union: collectionUnion,\n            __zuzu_intersection: collectionIntersection,\n            __zuzu_difference: collectionDifference,\n            __zuzu_default: defaultOperator,\n            __zuzu_subsetof: collectionSubsetOf,\n            __zuzu_supersetof: collectionSupersetOf,\n            __zuzu_equivalentof: collectionEquivalentOf,\n            __zuzu_array: makeArray,\n            __zuzu_set: makeSet,\n            __zuzu_bag: makeBag,\n            __zuzu_pairlist_literal: makePairList,\n            __zuzu_temp_pairlist: makeTemporaryPairList,\n            __zuzu_snapshot_spread_arg: snapshotSpreadArg,\n            __zuzu_spread_call_args: spreadCallArgs,\n            __zuzu_unpack_source: unpackDeclarationSource,\n            __zuzu_unpack_value: unpackDeclarationValue,\n            __zuzu_release_collection_values: releaseCollectionValues,\n            __zuzu_path_op: makePathOperator(runtime, filename),\n            __zuzu_path_assign: makePathAssignmentOperator(runtime, filename),\n            __zuzu_path_ref: makePathReferenceOperator(runtime, filename),\n            __zuzu_path_update: makePathUpdateOperator(runtime, filename),\n            __zuzu_call_member: zuzuCallMember,\n            __zuzu_is_weakable_value: isWeakableValue,\n            __zuzu_is_pairlist: isPairListLike,\n            __zuzu_make_weak_value: makeWeakValue,\n            __zuzu_resolve_weak_value: resolveWeakValue,\n            __zuzu_retain_value: retainValue,\n            __zuzu_release_value: releaseValue,\n            __zuzu_retain_collection_value: retainCollectionValue,\n            __zuzu_release_collection_value: releaseCollectionValue,\n            __zuzu_add_set_value: addSetValue,\n            __zuzu_assign_strong: assignStrongValue,\n            __zuzu_assign_weak: assignWeakValue,\n            __zuzu_assign_index: assignIndexedValue,\n            __zuzu_bodyless_function(name2) {\n              let target = null;\n              const fn2 = function __zuzu_bodyless_function_wrapper(...args) {\n                if (typeof target === "function") {\n                  return target.apply(this, args);\n                }\n                throw new Error(`Exception: Function \'${name2}\' has no body`);\n              };\n              Object.defineProperty(fn2, "__zuzu_complete_body", {\n                value(completed) {\n                  target = completed;\n                  return fn2;\n                },\n                enumerable: false,\n                configurable: true\n              });\n              return fn2;\n            },\n            __zuzu_complete_function(current, completed, meta) {\n              const value = completed;\n              if (value && (typeof value === "function" || typeof value === "object")) {\n                Object.defineProperty(value, "__zuzu_marshal_meta", {\n                  value: meta || {},\n                  enumerable: false,\n                  configurable: true,\n                  writable: true\n                });\n              }\n              if (current && typeof current.__zuzu_complete_body === "function") {\n                return current.__zuzu_complete_body(value);\n              }\n              throw new Error("Exception: function predeclaration target is not bodyless");\n            },\n            __zuzu_with_marshal_meta(value, meta) {\n              if (value && (typeof value === "function" || typeof value === "object")) {\n                Object.defineProperty(value, "__zuzu_marshal_meta", {\n                  value: meta || {},\n                  enumerable: false,\n                  configurable: true,\n                  writable: true\n                });\n              }\n              return value;\n            },\n            __zuzu_await_value(value) {\n              return taskRuntime2.awaitValue(value);\n            },\n            __zuzu_await_block(value) {\n              return taskRuntime2.awaitBlock(value);\n            },\n            __zuzu_callsite(metadata, fn2) {\n              return taskRuntime2.withCallsite(\n                {\n                  file: filename,\n                  ...metadata || {}\n                },\n                fn2\n              );\n            },\n            __zuzu_task(fn2, metadata) {\n              return taskRuntime2.task(fn2, {\n                file: filename,\n                ...metadata || {}\n              });\n            },\n            __zuzu_task_sync(fn2, metadata) {\n              return taskRuntime2.taskSync(fn2, {\n                file: filename,\n                ...metadata || {}\n              });\n            },\n            __zuzu_spawn(fn2, metadata) {\n              return taskRuntime2.spawn(fn2, {\n                file: filename,\n                ...metadata || {}\n              });\n            },\n            async __zuzu_collection_map_async(collection, fn2) {\n              const out = [];\n              for (const item of collection || []) {\n                out.push(await taskRuntime2.awaitValue(fn2(item)));\n              }\n              return out;\n            },\n            async __zuzu_collection_grep_async(collection, fn2) {\n              const out = [];\n              for (const item of collection || []) {\n                if (zuzuTruthy(await taskRuntime2.awaitValue(fn2(item)))) {\n                  out.push(item);\n                }\n              }\n              return out;\n            },\n            async __zuzu_collection_reduce_async(collection, fn2) {\n              const items = Array.from(collection || []);\n              if (items.length === 0) {\n                return null;\n              }\n              let acc = items[0];\n              for (let i = 1; i < items.length; i++) {\n                acc = await taskRuntime2.awaitValue(fn2(acc, items[i]));\n              }\n              return acc;\n            },\n            __zuzu_prepare_eval(source, namedArgs = null) {\n              if (typeof source !== "string") {\n                throw new ZuzuTypeException(\n                  `TypeException: eval expects String, got ${zuzuTypeof(source)}`\n                );\n              }\n              if (namedArgs != null && !isPairListLike(namedArgs)) {\n                throw new ZuzuTypeException(\n                  `TypeException: eval named arguments must be PairList, got ${zuzuTypeof(namedArgs)}`\n                );\n              }\n              let compiled;\n              try {\n                compiled = runtime.transpile(source, { syncEval: true });\n              } catch (err) {\n                const line = err && err.token && err.token.line != null ? err.token.line : 1;\n                throw new ZuzuException({\n                  message: err && err.message ? String(err.message) : String(err),\n                  file: "<std/eval>",\n                  line,\n                  code: "E_COMPILE_SYNTAX"\n                });\n              }\n              if (namedArgs == null) {\n                return compiled;\n              }\n              const overrides = /* @__PURE__ */ Object.create(null);\n              const accepted = /* @__PURE__ */ new Set([\n                "deny_fs",\n                "deny_net",\n                "deny_perl",\n                "deny_js",\n                "deny_proc",\n                "deny_db",\n                "deny_clib",\n                "deny_gui",\n                "deny_worker"\n              ]);\n              for (const optName of namedArgs.keys()) {\n                if (!accepted.has(optName)) {\n                  throw new ZuzuException(\n                    `Unknown named argument \'${optName}\' for eval`\n                  );\n                }\n              }\n              for (const [optName, flagName] of [\n                ["deny_fs", "deny_fs"],\n                ["deny_net", "deny_net"],\n                ["deny_perl", "deny_perl"],\n                ["deny_js", "deny_js"],\n                ["deny_proc", "deny_proc"],\n                ["deny_db", "deny_db"],\n                ["deny_clib", "deny_clib"],\n                ["deny_gui", "deny_gui"],\n                ["deny_worker", "deny_worker"]\n              ]) {\n                if (namedArgs.has(optName) && zuzuTruthy(namedArgs.get(optName))) {\n                  overrides[flagName] = true;\n                }\n              }\n              if (Object.keys(overrides).length === 0) {\n                return compiled;\n              }\n              return [\n                "( () => {",\n                `const __zuzu_eval_prev_caps = __zuzu_push_eval_capability_overrides( ${JSON.stringify(overrides)} );`,\n                "try {",\n                "return ( () => {",\n                "const __system__ = __zuzu_current_system();",\n                `return ${compiled};`,\n                "} )();",\n                "} finally {",\n                "__zuzu_pop_eval_capability_overrides( __zuzu_eval_prev_caps );",\n                "}",\n                "} )()"\n              ].join("\\n");\n            },\n            __zuzu_prepare_eval_call_args(args) {\n              let source = "";\n              let namedArgs = null;\n              if (args.length > 0) {\n                if (isPairListLike(args[args.length - 1])) {\n                  namedArgs = args[args.length - 1];\n                  if (args.length > 1) {\n                    source = args[0];\n                  }\n                } else {\n                  source = args[0];\n                }\n              }\n              return context.__zuzu_prepare_eval(source, namedArgs);\n            },\n            __zuzu_await_block_sync(value) {\n              return taskRuntime2.awaitBlockSync(value);\n            },\n            __zuzu_iter(value) {\n              const asIterable = (input) => {\n                const hasMethodHere = (candidate, name2) => {\n                  if (candidate == null) {\n                    return false;\n                  }\n                  if (Object.prototype.hasOwnProperty.call(candidate, name2)) {\n                    return true;\n                  }\n                  const proto = Object.getPrototypeOf(candidate);\n                  if (!proto) {\n                    return false;\n                  }\n                  return Object.prototype.hasOwnProperty.call(proto, name2);\n                };\n                if (input == null) {\n                  return [];\n                }\n                if (input instanceof ZuzuBinary) {\n                  return Array.from(input.bytes, (byte) => new BinaryString2([byte]));\n                }\n                if (typeof input === "string" || input instanceof String) {\n                  return Array.from(String(input));\n                }\n                if (typeof input[Symbol.iterator] === "function") {\n                  return input;\n                }\n                if (typeof input === "function") {\n                  return {\n                    *[Symbol.iterator]() {\n                      while (true) {\n                        try {\n                          yield input();\n                        } catch (err) {\n                          if (isExhaustedIteratorError(err)) {\n                            return;\n                          }\n                          throw err;\n                        }\n                      }\n                    }\n                  };\n                }\n                if (input && typeof input.to_Iterator === "function" && hasMethodHere(input, "to_Iterator")) {\n                  const iterator = input.to_Iterator();\n                  if (typeof iterator === "function" && input && typeof input === "object") {\n                    return asIterable(iterator.bind(input));\n                  }\n                  return asIterable(iterator);\n                }\n                if (input && typeof input.to_Array === "function" && hasMethodHere(input, "to_Array")) {\n                  return asIterable(input.to_Array());\n                }\n                if (isPlainObjectLike(input) && typeof input.to_Iterator === "function") {\n                  return asIterable(input.to_Iterator());\n                }\n                if (isPlainObjectLike(input) && typeof input.to_Array === "function") {\n                  return asIterable(input.to_Array());\n                }\n                if (input && typeof input === "object") {\n                  return Object.keys(input).sort();\n                }\n                return [];\n              };\n              return asIterable(value);\n            },\n            __zuzu_length: operatorLength,\n            __zuzu_num(value) {\n              return zuzuToNumber(value);\n            },\n            __zuzu_truthy(value) {\n              return zuzuTruthy(value);\n            },\n            __zuzu_not(value) {\n              return !zuzuTruthy(value);\n            },\n            __zuzu_and(left, right) {\n              return zuzuTruthy(left) && zuzuTruthy(right);\n            },\n            __zuzu_or(left, right) {\n              return zuzuTruthy(left) || zuzuTruthy(right);\n            },\n            __zuzu_typeof(value) {\n              return zuzuTypeof(value);\n            },\n            __zuzu_instanceof(value, klass) {\n              return zuzuInstanceof(value, klass);\n            },\n            __zuzu_trait(name2, methods, source = null, captures = {}) {\n              return zuzuTrait(name2, methods, source, captures);\n            },\n            __zuzu_apply_traits(klass, traits) {\n              return zuzuApplyTraits(klass, traits);\n            },\n            __zuzu_class_with_traits(klass, traits) {\n              return zuzuClassWithTraits(klass, traits);\n            },\n            __zuzu_does(value, trait) {\n              return zuzuDoes(value, trait);\n            },\n            __zuzu_can(value, methodName) {\n              return zuzuCan(value, methodName);\n            },\n            __zuzu_super_call(self, klass, methodName, args) {\n              return zuzuSuperCall(self, klass, methodName, args);\n            },\n            __zuzu_super_static_call(klass, methodName, args) {\n              return zuzuSuperStaticCall(klass, methodName, args);\n            },\n            __zuzu_super_dispatch(isStatic, self, klass, methodName, args) {\n              return zuzuSuperDispatch(isStatic, self, klass, methodName, args);\n            },\n            __zuzu_type_matches(value, typeName2) {\n              return zuzuTypeMatches(value, typeName2);\n            },\n            __zuzu_require_type(argName, typeName2, value) {\n              if (!zuzuTypeMatches(value, typeName2)) {\n                throw new Error(`TypeException: argument \'${argName}\' must be ${typeName2}, got ${zuzuTypeof(value)}`);\n              }\n              return value;\n            },\n            __zuzu_checked_declaration(name2, typeName2, value) {\n              if (typeName2 !== "Any" && !zuzuTypeMatches(value, typeName2)) {\n                throw new Error(`TypeException: \'${name2}\' must be ${typeName2}, got ${zuzuTypeof(value)}`);\n              }\n              return value;\n            },\n            __zuzu_checked_return(fnName, typeName2, value) {\n              if (typeName2 !== "Any" && !zuzuTypeMatches(value, typeName2)) {\n                throw new Error(`TypeException: \'return value of \'${fnName}\'\' must be ${typeName2}, got ${zuzuTypeof(value)}`);\n              }\n              return value;\n            },\n            __zuzu_die(value) {\n              if (typeof value === "string") {\n                throw new ZuzuException(value);\n              }\n              throw value;\n            },\n            __zuzu_throw(value, line) {\n              const err = value instanceof Error || value && typeof value === "object" ? value : new ZuzuException(value);\n              if (err.file == null) {\n                err.file = filename;\n              }\n              if (err.line == null) {\n                err.line = Number(line || 0);\n              }\n              throw err;\n            },\n            __zuzu_add(left, right) {\n              return zuzuToNumber(left) + zuzuToNumber(right);\n            },\n            __zuzu_concat(left, right) {\n              return concatValue(left, right);\n            },\n            __zuzu_binary_literal(value) {\n              return binaryFromLiteral(value);\n            },\n            to_binary(value) {\n              return toBinaryValue(value);\n            },\n            to_string(value) {\n              return toStringValue(value);\n            },\n            is_ascii(value) {\n              if (!(value instanceof ZuzuBinary)) {\n                throw new Error(`TypeException: expected BinaryString for is_ascii, got ${zuzuTypeof(value)}`);\n              }\n              return value.isAscii();\n            },\n            __zuzu_bit_and(left, right) {\n              return bitwiseAnd(left, right);\n            },\n            __zuzu_shift_left(left, right) {\n              return shiftValue(left, right, true);\n            },\n            // The left operand is the divisor: a \u2223 b tests b mod a.\n            __zuzu_divides(left, right) {\n              return zuzuToNumber(right) % zuzuToNumber(left) === 0;\n            },\n            __zuzu_ndivides(left, right) {\n              return zuzuToNumber(right) % zuzuToNumber(left);\n            },\n            __zuzu_shift_right(left, right) {\n              return shiftValue(left, right, false);\n            },\n            __zuzu_bit_or(left, right) {\n              return bitwiseOr(left, right);\n            },\n            __zuzu_bit_xor(left, right) {\n              return bitwiseXor(left, right);\n            },\n            __zuzu_bit_not(value) {\n              return bitwiseNot(value);\n            },\n            __zuzu_sub(left, right) {\n              return zuzuToNumber(left) - zuzuToNumber(right);\n            },\n            __zuzu_mul(left, right) {\n              return zuzuToNumber(left) * zuzuToNumber(right);\n            },\n            __zuzu_div(left, right) {\n              return zuzuToNumber(left) / zuzuToNumber(right);\n            },\n            __zuzu_mod(left, right) {\n              return zuzuToNumber(left) % zuzuToNumber(right);\n            },\n            __zuzu_pow(left, right) {\n              return zuzuToNumber(left) ** zuzuToNumber(right);\n            },\n            __zuzu_cmp(left, right) {\n              const l = zuzuToNumber(left);\n              const r = zuzuToNumber(right);\n              return l < r ? -1 : l > r ? 1 : 0;\n            },\n            __zuzu_eq(left, right) {\n              if (arguments.length < 2) {\n                return 0;\n              }\n              return zuzuEqual(left, right);\n            },\n            __zuzu_ne(left, right) {\n              if (arguments.length < 2) {\n                return 0;\n              }\n              return zuzuEqual(left, right) ? 0 : 1;\n            },\n            __zuzu_str_eq(left, right) {\n              return stringCompare(left, right) === 0 ? 1 : 0;\n            },\n            __zuzu_str_ne(left, right) {\n              return stringCompare(left, right) !== 0 ? 1 : 0;\n            },\n            __zuzu_str_gt(left, right) {\n              return stringCompare(left, right) > 0 ? 1 : 0;\n            },\n            __zuzu_str_ge(left, right) {\n              return stringCompare(left, right) >= 0 ? 1 : 0;\n            },\n            __zuzu_str_lt(left, right) {\n              return stringCompare(left, right) < 0 ? 1 : 0;\n            },\n            __zuzu_str_le(left, right) {\n              return stringCompare(left, right) <= 0 ? 1 : 0;\n            },\n            __zuzu_str_cmp(left, right) {\n              return stringCompare(left, right);\n            },\n            __zuzu_str_eqi(left, right) {\n              return stringCompare(left, right, { insensitive: true }) === 0 ? 1 : 0;\n            },\n            __zuzu_str_nei(left, right) {\n              return stringCompare(left, right, { insensitive: true }) !== 0 ? 1 : 0;\n            },\n            __zuzu_str_gti(left, right) {\n              return stringCompare(left, right, { insensitive: true }) > 0 ? 1 : 0;\n            },\n            __zuzu_str_gei(left, right) {\n              return stringCompare(left, right, { insensitive: true }) >= 0 ? 1 : 0;\n            },\n            __zuzu_str_lti(left, right) {\n              return stringCompare(left, right, { insensitive: true }) < 0 ? 1 : 0;\n            },\n            __zuzu_str_lei(left, right) {\n              return stringCompare(left, right, { insensitive: true }) <= 0 ? 1 : 0;\n            },\n            __zuzu_str_cmpi(left, right) {\n              return stringCompare(left, right, { insensitive: true });\n            },\n            __zuzu_warn(...parts) {\n              emitStderr(parts.map((part) => zuzuStringify(part)).join(""));\n            },\n            __zuzu_debug(levelThunk, messageThunk) {\n              const level = typeof levelThunk === "function" ? levelThunk() : levelThunk;\n              if (Number(level || 0) > runtime.debugLevel) {\n                return null;\n              }\n              const message = typeof messageThunk === "function" ? messageThunk() : messageThunk;\n              emitStderr(zuzuStringify(message ?? ""));\n              return null;\n            },\n            __zuzu_assert(conditionThunk) {\n              if (runtime.debugLevel <= 0) {\n                return null;\n              }\n              const condition = typeof conditionThunk === "function" ? conditionThunk() : conditionThunk;\n              if (!condition) {\n                throw new Error("Assertion failed");\n              }\n              return condition;\n            },\n            __zuzu_make_class(name2, base) {\n              const parent = typeof base === "function" ? base : Object;\n              return {\n                [name2]: class extends parent {\n                  constructor(...args) {\n                    if (args.length === 1 && args[0] && typeof args[0] === "object" && !Array.isArray(args[0]) && Object.prototype.hasOwnProperty.call(args[0], "message")) {\n                      super(args[0].message);\n                      if (this instanceof Error) {\n                        this.name = name2;\n                      }\n                      return;\n                    }\n                    super(...args);\n                    if (this instanceof Error) {\n                      this.name = name2;\n                    }\n                  }\n                }\n              }[name2];\n            },\n            __zuzu_define_class(name2, base, spec) {\n              return defineZuzuClass(name2, base, spec);\n            },\n            __zuzu_get_member(object, property) {\n              return zuzuGetMember(object, property);\n            },\n            __zuzu_get_index(object, index) {\n              return zuzuGetIndex(object, index);\n            },\n            __zuzu_get_brace_member(object, literalProperty, getDynamicProperty) {\n              return zuzuGetBraceMember(object, literalProperty, getDynamicProperty);\n            },\n            __zuzu_resolve_brace_key(object, literalProperty, getDynamicProperty) {\n              return zuzuResolveBraceKey(object, literalProperty, getDynamicProperty);\n            },\n            __zuzu_maybe_demolish(value, preserved = null) {\n              return zuzuMaybeDemolish(value, preserved);\n            },\n            __zuzu_xor(left, right) {\n              return zuzuTruthy(left) !== zuzuTruthy(right);\n            },\n            __zuzu_nand(left, right) {\n              return !(zuzuTruthy(left) && zuzuTruthy(right));\n            },\n            __zuzu_num_eq(left, right) {\n              if (!isNumericComparable(left) || !isNumericComparable(right)) {\n                return zuzuEqual(left, right);\n              }\n              return numericEqual(left, right) ? 1 : 0;\n            },\n            __zuzu_num_ne(left, right) {\n              if (!isNumericComparable(left) || !isNumericComparable(right)) {\n                return zuzuEqual(left, right) ? 0 : 1;\n              }\n              return numericEqual(left, right) ? 0 : 1;\n            },\n            __zuzu_num_lt(left, right) {\n              return zuzuToNumber(left) < zuzuToNumber(right) ? 1 : 0;\n            },\n            __zuzu_num_lte(left, right) {\n              return zuzuToNumber(left) <= zuzuToNumber(right) ? 1 : 0;\n            },\n            __zuzu_num_gt(left, right) {\n              return zuzuToNumber(left) > zuzuToNumber(right) ? 1 : 0;\n            },\n            __zuzu_num_gte(left, right) {\n              return zuzuToNumber(left) >= zuzuToNumber(right) ? 1 : 0;\n            },\n            __zuzu_abs(value) {\n              return Math.abs(zuzuToNumber(value));\n            },\n            __zuzu_sqrt(value) {\n              return Math.sqrt(zuzuToNumber(value));\n            },\n            __zuzu_floor(value) {\n              return Math.floor(zuzuToNumber(value));\n            },\n            __zuzu_ceil(value) {\n              return Math.ceil(zuzuToNumber(value));\n            },\n            __zuzu_round(value) {\n              const n = zuzuToNumber(value);\n              return n >= 0 ? Math.floor(n + 0.5) : Math.ceil(n - 0.5);\n            },\n            __zuzu_int(value) {\n              const n = zuzuToNumber(value);\n              return n < 0 ? Math.ceil(n) : Math.floor(n);\n            },\n            __zuzu_uc(value) {\n              if (value instanceof ZuzuBinary) {\n                throw new Error("TypeException: uc expects String, got BinaryString");\n              }\n              return zuzuOperatorString(value).toUpperCase();\n            },\n            __zuzu_lc(value) {\n              if (value instanceof ZuzuBinary) {\n                throw new Error("TypeException: lc expects String, got BinaryString");\n              }\n              return zuzuOperatorString(value).toLowerCase();\n            },\n            __zuzu_range(start, end) {\n              const from = zuzuToNumber(start);\n              const to = zuzuToNumber(end);\n              const out = [];\n              const step = from <= to ? 1 : -1;\n              for (let n = from; step > 0 ? n <= to : n >= to; n += step) {\n                out.push(n);\n              }\n              return out;\n            },\n            __zuzu_ref_index(target, index) {\n              return refIndex(target, index);\n            },\n            __zuzu_ref_key(target, key) {\n              return refKey(target, key);\n            },\n            __zuzu_get_slice(target, from, length) {\n              return zuzuGetSlice(target, from, length);\n            },\n            __zuzu_ref_slice(target, from, length) {\n              return refSlice(target, from, length);\n            },\n            __zuzu_assign_slice(target, from, length, value) {\n              return zuzuAssignSlice(target, from, length, value);\n            },\n            Pair\n          };\n          if (this.host.name === "browser") {\n            context.Object = createObjectFacade();\n          }\n          context.__zuzu_push_eval_capability_overrides = (overrides = {}) => {\n            const previous = this.evalCapabilityOverrides;\n            const next = { ...previous || {} };\n            for (const [key, value] of Object.entries(overrides || {})) {\n              if (value) {\n                next[key] = true;\n              }\n            }\n            this.evalCapabilityOverrides = Object.keys(next).length > 0 ? next : null;\n            return previous;\n          };\n          context.__zuzu_pop_eval_capability_overrides = (previous) => {\n            this.evalCapabilityOverrides = previous || null;\n          };\n          context.__zuzu_import = (name2) => {\n            if (name2 === "std/eval") {\n              return { eval: context.__zuzu_native_eval };\n            }\n            if (this.usesAsyncImports()) {\n              return this.loadModuleAsync(name2, filename, context);\n            }\n            return this.loadModule(name2, filename, context);\n          };\n          return context;\n        }\n        installCollectionMethods(context) {\n          const bootstrap = `\n			(function () {\n				globalThis.__zuzu_native_eval = eval;\n				globalThis.__zuzu_builtin_Array = Array;\n				globalThis.__zuzu_builtin_Function = Function;\n				globalThis.__zuzu_builtin_Object = Object;\n				globalThis.__zuzu_builtin_RegExp = RegExp;\n				globalThis.__zuzu_builtin_Set = Set;\n				globalThis.Dict = function Dict( value ) {\n					if ( value && typeof value === \'object\' && !Array.isArray( value ) ) {\n						return Object.assign( {}, value );\n					}\n					return {};\n				};\n				if ( !globalThis.__zuzu_define_property_patched ) {\n					const __zuzu_native_define_property = Object.defineProperty;\n					const __zuzu_native_define_properties = Object.defineProperties;\n					const __zuzu_safe_descriptor = function ( descriptor ) {\n						if ( !descriptor || typeof descriptor !== \'object\' ) {\n							return descriptor;\n						}\n						const safe = Object.create( null );\n						for ( const key of [ \'value\', \'get\', \'set\', \'writable\', \'enumerable\', \'configurable\' ] ) {\n							if ( Object.prototype.hasOwnProperty.call( descriptor, key ) ) {\n								safe[key] = descriptor[key];\n							}\n						}\n						return safe;\n					};\n					Object.defineProperty = function __zuzu_define_property( obj, prop, descriptor ) {\n						return __zuzu_native_define_property(\n							obj,\n							prop,\n							__zuzu_safe_descriptor( descriptor )\n						);\n					};\n					Object.defineProperties = function __zuzu_define_properties( obj, descriptors ) {\n						const safeDescriptors = Object.create( null );\n						for ( const key of Object.keys( descriptors || {} ) ) {\n							safeDescriptors[key] = __zuzu_safe_descriptor( descriptors[key] );\n						}\n						return __zuzu_native_define_properties( obj, safeDescriptors );\n					};\n					globalThis.__zuzu_define_property_patched = true;\n				}\n				const __zuzu_seed = globalThis.__zuzu_system_seed || Object.create( null );\n				const __zuzu_system_desc = Object.create( null );\n				__zuzu_system_desc.get = function __zuzu_get_system() {\n					if ( typeof globalThis.__zuzu_current_system === \'function\' ) {\n						return globalThis.__zuzu_current_system();\n					}\n					return Object.freeze( Object.assign( {}, __zuzu_seed ) );\n				};\n				__zuzu_system_desc.enumerable = true;\n				__zuzu_system_desc.configurable = true;\n				Object.defineProperty(\n					globalThis,\n					\'__system__\',\n					__zuzu_system_desc\n				);\n				delete globalThis.__zuzu_system_seed;\n				const define = ( proto, name, fn ) => {\n					if ( !Object.prototype.hasOwnProperty.call( proto, name ) ) {\n						const desc = Object.create( null );\n						desc.value = fn;\n						desc.enumerable = false;\n						desc.configurable = true;\n						desc.writable = true;\n						Object.defineProperty( proto, name, desc );\n					}\n				};\n				if ( Array.prototype.join.__zuzu_array_join !== true ) {\n					const __zuzu_native_array_join = Array.prototype.join;\n					const joinDesc = Object.create( null );\n					joinDesc.value = function _join( separator, fallback ) {\n						const hasFallback = arguments.length > 1;\n						let fallbackString;\n						const sep = __zuzu_operator_string( separator );\n						const out = [];\n						for ( const value of this ) {\n							try {\n								out.push( __zuzu_operator_string( value ) );\n							}\n							catch ( err ) {\n								if ( !hasFallback ) {\n									throw err;\n								}\n								if ( typeof fallback === \'function\' ) {\n									out.push( __zuzu_operator_string( fallback( value ) ) );\n								}\n								else {\n									if ( fallbackString === undefined ) {\n										fallbackString = __zuzu_operator_string( fallback );\n									}\n									out.push( fallbackString );\n								}\n							}\n						}\n						return __zuzu_native_array_join.call( out, sep );\n					};\n					joinDesc.value.__zuzu_array_join = true;\n					joinDesc.enumerable = false;\n					joinDesc.configurable = true;\n					joinDesc.writable = true;\n					Object.defineProperty( Array.prototype, \'join\', joinDesc );\n				}\n				define( Array.prototype, \'length\', function _length() { return this.length; } );\n				define( Array.prototype, \'count\', function _count() { return this.length; } );\n				define( Array.prototype, \'empty\', function _empty() { return this.length === 0 ? 1 : 0; } );\n				define( Array.prototype, \'is_empty\', function _is_empty() { return this.empty(); } );\n				define( Array.prototype, \'append\', function _append( ...values ) { this.push( ...values.map( ( value ) => __zuzu_retain_collection_value( this, value ) ) ); return this; } );\n				define( Array.prototype, \'add\', function _add( ...values ) { this.push( ...values.map( ( value ) => __zuzu_retain_collection_value( this, value ) ) ); return this; } );\n				define( Array.prototype, \'prepend\', function _prepend( ...values ) { this.unshift( ...values.map( ( value ) => __zuzu_retain_collection_value( this, value ) ) ); return this; } );\n				define( Array.prototype, \'push_weak\', function _push_weak( ...values ) { this.push( ...values.map( __zuzu_make_weak_value ) ); return this; } );\n				define( Array.prototype, \'unshift_weak\', function _unshift_weak( ...values ) { this.unshift( ...values.map( __zuzu_make_weak_value ) ); return this; } );\n				define( Array.prototype, \'get\', function _get( idx, fallback = null ) { return idx >= 0 && idx < this.length ? this[idx] : fallback; } );\n				define( Array.prototype, \'set\', function _set( idx, value ) { __zuzu_release_collection_value( this, this[idx] ); this[idx] = __zuzu_retain_collection_value( this, value ); return this; } );\n				define( Array.prototype, \'set_weak\', function _set_weak( idx, value ) { __zuzu_release_collection_value( this, this[idx] ); this[idx] = __zuzu_make_weak_value( value ); return this; } );\n				define( Array.prototype, \'grep\', function _grep( fn ) { return this.filter( fn ); } );\n				define( Array.prototype, \'any\', function _any( fn ) { return this.some( fn ) ? 1 : 0; } );\n				define( Array.prototype, \'all\', function _all( fn ) { return this.every( fn ) ? 1 : 0; } );\n				define( Array.prototype, \'first\', function _first( fn ) { return this.find( fn ) ?? null; } );\n				define( Array.prototype, \'remove\', function _remove( fn ) { for ( let i = this.length - 1; i >= 0; i-- ) { if ( fn( this[i] ) ) { __zuzu_release_collection_value( this, this[i] ); this.splice( i, 1 ); } } return this; } );\n				define( Array.prototype, \'contains\', function _contains( value ) { return this.includes( value ) ? 1 : 0; } );\n				define( Array.prototype, \'first_index\', function _first_index( fn ) { return this.findIndex( fn ); } );\n				define( Array.prototype, \'reductions\', function _reductions( fn ) { const out = []; for ( const item of this ) { out.push( out.length === 0 ? item : fn( out[out.length - 1], item ) ); } return out; } );\n				define( Array.prototype, \'head\', function _head( n ) { return this.slice( 0, n ); } );\n				define( Array.prototype, \'tail\', function _tail( n ) { return this.slice( n - 1 ); } );\n				define( Array.prototype, \'sum\', function _sum() { return this.reduce( (a, b) => Number( a ) + Number( b ), 0 ); } );\n				define( Array.prototype, \'product\', function _product() { return this.reduce( (a, b) => Number( a ) * Number( b ), 1 ); } );\n				define( Array.prototype, \'shuffle\', function _shuffle() { return this.slice(); } );\n				define( Array.prototype, \'sample\', function _sample( n ) { return this.slice( 0, n ); } );\n				define( Array.prototype, \'for_each_value\', function _for_each_value( fn ) { this.forEach( fn ); return this; } );\n				define( Array.prototype, \'sortstr\', function _sortstr() { return this.slice().sort( stringSortComparator ); } );\n				define( Array.prototype, \'sortnum\', function _sortnum() { return this.map( (item) => Number( item ) ).sort( (a, b) => a - b ); } );\n				define( Array.prototype, \'to_Array\', function _to_array() { return __zuzu_array( this ); } );\n				define( Array.prototype, \'to_Set\', function _to_set() { return __zuzu_set( this ); } );\n				define( Array.prototype, \'to_Bag\', function _to_bag() { return new Bag( this ); } );\n				define( Array.prototype, \'to_Iterator\', function _to_iterator() { return this[Symbol.iterator](); } );\n				define( Array.prototype, \'copy\', function _copy() { return __zuzu_array( this ); } );\n				define( Array.prototype, \'clear\', function _clear() { __zuzu_release_collection_values( this ); this.splice( 0, this.length ); return this; } );\n\n				define( Set.prototype, \'length\', function _length() { return this.size; } );\n				define( Set.prototype, \'count\', function _count() { return this.size; } );\n				define( Set.prototype, \'empty\', function _empty() { return this.size === 0 ? 1 : 0; } );\n				define( Set.prototype, \'is_empty\', function _is_empty() { return this.empty(); } );\n				define( Set.prototype, \'push\', function _push( ...values ) { for ( const v of values ) { __zuzu_add_set_value( this, v ); } return this; } );\n				define( Set.prototype, \'add_weak\', function _add_weak( value ) { this.add( __zuzu_make_weak_value( value ) ); return this; } );\n				define( Set.prototype, \'push_weak\', function _push_weak( ...values ) { for ( const v of values ) { this.add( __zuzu_make_weak_value( v ) ); } return this; } );\n				define( Set.prototype, \'contains\', function _contains( value ) { return __zuzu_contains( this, value ); } );\n				define( Set.prototype, \'remove\', function _remove( value ) { const resolved = __zuzu_resolve_weak_value( value ); if ( this.delete( resolved ) ) { __zuzu_release_collection_value( this, resolved ); } return this; } );\n				define( Set.prototype, \'to_Array\', function _to_array() { return __zuzu_array( this ); } );\n				define( Set.prototype, \'to_Bag\', function _to_bag() { return __zuzu_bag( [ ...this ] ); } );\n				define( Set.prototype, \'to_Iterator\', function _to_iterator() { return this.values(); } );\n				define( Set.prototype, \'copy\', function _copy() { return __zuzu_set( this ); } );\n				define( Set.prototype, \'union\', function _union( other ) { return __zuzu_union( this, other ); } );\n				define( Set.prototype, \'intersection\', function _intersection( other ) { return __zuzu_intersection( this, other ); } );\n				define( Set.prototype, \'difference\', function _difference( other ) { return __zuzu_difference( this, other ); } );\n				define( Set.prototype, \'symmetric_difference\', function _symmetric_difference( other ) { return __zuzu_difference( this.union( other ), this.intersection( other ) ); } );\n				define( Set.prototype, \'is_subset\', function _is_subset( other ) { return __zuzu_subsetof( this, other ); } );\n				define( Set.prototype, \'is_superset\', function _is_superset( other ) { return __zuzu_supersetof( this, other ); } );\n				define( Set.prototype, \'is_disjoint\', function _is_disjoint( other ) { return this.intersection( other ).size === 0 ? 1 : 0; } );\n				define( Set.prototype, \'equals\', function _equals( other ) { return __zuzu_equivalentof( this, other ); } );\n				define( Set.prototype, \'sort\', function _sort( fn ) { return [ ...this ].sort( fn ); } );\n				define( Set.prototype, \'sortstr\', function _sortstr() { return [ ...this ].sort( stringSortComparator ); } );\n				define( Set.prototype, \'sortnum\', function _sortnum() { return [ ...this ].map( (item) => Number( item ) ).sort( (a, b) => a - b ); } );\n				define( Set.prototype, \'map\', function _map( fn ) { return new Set( [ ...this ].map( fn ) ); } );\n				define( Set.prototype, \'grep\', function _grep( fn ) { return new Set( [ ...this ].filter( fn ) ); } );\n				define( Set.prototype, \'any\', function _any( fn ) { return [ ...this ].some( fn ) ? 1 : 0; } );\n				define( Set.prototype, \'all\', function _all( fn ) { return [ ...this ].every( fn ) ? 1 : 0; } );\n				define( Set.prototype, \'first\', function _first( fn ) { for ( const v of this ) { if ( fn( v ) ) { return v; } } return null; } );\n				define( Set.prototype, \'remove_if\', function _remove_if( fn ) { for ( const v of [ ...this ] ) { if ( fn( v ) ) { __zuzu_release_collection_value( this, v ); this.delete( v ); } } return this; } );\n				define( Set.prototype, \'for_each_value\', function _for_each_value( fn ) { for ( const v of this ) { fn( v ); } return this; } );\n				const clearSet = Set.prototype.clear;\n				define( Set.prototype, \'clear\', function _clear() { __zuzu_release_collection_values( this ); clearSet.call( this ); return this; } );\n				define( RegExp.prototype, \'to_String\', function _to_string() { return this.source; } );\n				if ( !Object.prototype.hasOwnProperty.call( RegExp.prototype, Symbol.toPrimitive ) ) {\n					const regDesc = Object.create( null );\n					regDesc.value = function _regexp_to_primitive( hint ) {\n						if ( hint === \'string\' || hint === \'default\' ) {\n							return this.to_String();\n						}\n						return NaN;\n					};\n					regDesc.enumerable = false;\n					regDesc.configurable = true;\n					regDesc.writable = true;\n					Object.defineProperty( RegExp.prototype, Symbol.toPrimitive, regDesc );\n				}\n				if ( !Object.prototype.hasOwnProperty.call( Object.prototype, Symbol.toPrimitive ) ) {\n					const objectDesc = Object.create( null );\n					objectDesc.value = function _object_to_primitive( hint ) {\n						if ( ( hint === \'string\' || hint === \'default\' ) && typeof this.to_String === \'function\' ) {\n							return this.to_String();\n						}\n						const methods = hint === \'number\'\n							? [ \'valueOf\', \'toString\' ]\n							: [ \'toString\', \'valueOf\' ];\n						for ( const methodName of methods ) {\n							const method = this[methodName];\n							if ( typeof method !== \'function\' ) {\n								continue;\n							}\n							if ( methodName === \'toString\' && method === Object.prototype.toString ) {\n								continue;\n							}\n							if ( methodName === \'valueOf\' && method === Object.prototype.valueOf ) {\n								continue;\n							}\n							const value = method.call( this );\n							if ( value == null || typeof value !== \'object\' ) {\n								return value;\n							}\n						}\n						return Object.prototype.toString.call( this );\n					};\n					objectDesc.enumerable = false;\n					objectDesc.configurable = true;\n					objectDesc.writable = true;\n					Object.defineProperty( Object.prototype, Symbol.toPrimitive, objectDesc );\n				}\n\n			})();\n		`;\n          const bootstrapRunOptions = {};\n          if (this.executionTimeoutMs != null) {\n            bootstrapRunOptions.timeout = this.executionTimeoutMs;\n          }\n          this.host.runInContext(bootstrap, context, bootstrapRunOptions);\n        }\n        loadModule(moduleName, fromFile, contextForPolicy = null) {\n          if (/(^|\\/)\\.\\.(\\/|$)/.test(moduleName)) {\n            throw new Error("Import module path cannot contain \'..\' segments");\n          }\n          this.enforceModulePolicy(moduleName);\n          const resolved = this.resolveModulePath(moduleName, fromFile);\n          const cacheable = moduleName !== "test/more" && this.evalCapabilityOverrides == null;\n          if (cacheable && this.moduleCache.has(resolved)) {\n            return this.moduleCache.get(resolved);\n          }\n          if (this.moduleLoading.has(resolved)) {\n            throw new Error("Circular module loading detected");\n          }\n          if (resolved.endsWith(".js")) {\n            const hiddenObjectPrototypeMethods = [];\n            for (const name2 of ["get", "set"]) {\n              const desc = Object.prototype.hasOwnProperty.call(Object.prototype, name2) ? Object.getOwnPropertyDescriptor(Object.prototype, name2) : null;\n              if (desc && desc.configurable) {\n                hiddenObjectPrototypeMethods.push([name2, desc]);\n                delete Object.prototype[name2];\n              }\n            }\n            let loaded;\n            try {\n              loaded = this.host.loadJsModule(resolved, moduleName, fromFile);\n            } finally {\n              for (const [name2, desc] of hiddenObjectPrototypeMethods) {\n                Object.defineProperty(Object.prototype, name2, desc);\n              }\n            }\n            if (loaded && typeof loaded.__zuzu_set_runtime_policy === "function") {\n              const policy = {\n                gui: this.host.gui || null,\n                host_name: this.host.name,\n                repo_root: this.repoRoot,\n                include_paths: this.includePaths.slice(),\n                deny_modules: [...this.denyModules],\n                debug_level: this.debugLevel,\n                transpiler: this.transpiler,\n                load_module: (name2, requestFromFile = fromFile) => this.loadModule(\n                  name2,\n                  requestFromFile || fromFile,\n                  contextForPolicy\n                ),\n                builtin_class: (name2) => {\n                  if (!contextForPolicy) {\n                    return null;\n                  }\n                  const builtins = {\n                    Array: contextForPolicy.__zuzu_builtin_Array,\n                    Bag: contextForPolicy.Bag,\n                    Class: contextForPolicy.Class,\n                    Dict: contextForPolicy.Dict || contextForPolicy.__zuzu_builtin_Object,\n                    Function: contextForPolicy.__zuzu_builtin_Function,\n                    Object: contextForPolicy.__zuzu_builtin_Object,\n                    Pair: contextForPolicy.Pair,\n                    PairList: contextForPolicy.PairList,\n                    Regexp: contextForPolicy.__zuzu_builtin_RegExp,\n                    Set: contextForPolicy.__zuzu_builtin_Set\n                  };\n                  return builtins[name2] || null;\n                },\n                to_String: (value) => zuzuOperatorString(value),\n                to_Number: (value) => zuzuToNumber(value),\n                to_Boolean: (value) => zuzuTruthy(value),\n                to_Regexp: (value) => operatorRegexp(value),\n                to_Regexp_with_flags: (value, flags) => {\n                  const pattern = value instanceof RegExp ? value.source : zuzuOperatorString(value);\n                  return new RegExp(pattern, zuzuOperatorString(flags));\n                },\n                stdout_write: (text) => {\n                  if (typeof this.stdoutHandler === "function") {\n                    this.stdoutHandler(String(text));\n                  } else if (typeof process !== "undefined" && process.stdout) {\n                    process.stdout.write(String(text));\n                  } else {\n                    this.host.consoleLog(String(text));\n                  }\n                },\n                stderr_write: (text) => {\n                  if (typeof this.stderrHandler === "function") {\n                    this.stderrHandler(String(text));\n                  } else if (typeof process !== "undefined" && process.stderr) {\n                    process.stderr.write(String(text));\n                  } else if (typeof console !== "undefined" && typeof console.warn === "function") {\n                    console.warn(String(text));\n                  }\n                },\n                browser_worker_source: this.host.workerSource || null,\n                browser_worker_url: this.host.workerUrl || null,\n                browser_worker_factory: this.host.workerFactory || null\n              };\n              for (const capability of [\n                "fs",\n                "net",\n                "perl",\n                "js",\n                "proc",\n                "db",\n                "clib",\n                "gui",\n                "worker"\n              ]) {\n                policy[`deny_${capability}`] = this.isCapabilityDenied(capability) || !this.host.capabilities.has(capability);\n              }\n              loaded.__zuzu_set_runtime_policy(policy);\n            }\n            if (cacheable) {\n              this.moduleCache.set(resolved, loaded);\n            }\n            return loaded;\n          }\n          const source = this.host.readFileText(resolved);\n          let js = this.transpile(source);\n          setCompiledSource(resolved, js);\n          const exportNames = resolved.endsWith(".zzm") ? collectTopLevelDeclarations(source, stripPod) : [];\n          if (exportNames.length > 0) {\n            const exportBridge = exportNames.map((name2) => {\n              if (name2.startsWith("_")) {\n                return `if ( typeof ${name2} !== "undefined" ) { const __zuzu_desc = Object.create( null ); __zuzu_desc.get = function() { return ${name2}; }; __zuzu_desc.set = function( value ) { ${name2} = value; }; __zuzu_desc.enumerable = false; __zuzu_desc.configurable = true; Object.defineProperty( module.exports, ${JSON.stringify(name2)}, __zuzu_desc ); }`;\n              }\n              return `if ( typeof ${name2} !== "undefined" ) { const __zuzu_desc = Object.create( null ); __zuzu_desc.get = function() { return ${name2}; }; __zuzu_desc.set = function( value ) { ${name2} = value; }; __zuzu_desc.enumerable = true; __zuzu_desc.configurable = true; Object.defineProperty( module.exports, ${JSON.stringify(name2)}, __zuzu_desc ); }`;\n            }).join("\\n");\n            js += `\n${exportBridge}\n`;\n          }\n          const moduleObj = { exports: {} };\n          const context = this.buildContext({\n            exports: moduleObj.exports,\n            module: moduleObj,\n            filename: resolved\n          });\n          context.__global__ = /* @__PURE__ */ Object.create(null);\n          this.installCollectionMethods(context);\n          const moduleRunOptions = { filename: resolved };\n          if (this.executionTimeoutMs != null) {\n            moduleRunOptions.timeout = this.executionTimeoutMs;\n          }\n          this.moduleLoading.add(resolved);\n          try {\n            this.host.runInContext(js, context, moduleRunOptions);\n            if (cacheable) {\n              this.moduleCache.set(resolved, moduleObj.exports);\n            }\n          } finally {\n            this.moduleLoading.delete(resolved);\n          }\n          return moduleObj.exports;\n        }\n        async loadModuleAsync(moduleName, fromFile, contextForPolicy = null) {\n          if (/(^|\\/)\\.\\.(\\/|$)/.test(moduleName)) {\n            throw new Error("Import module path cannot contain \'..\' segments");\n          }\n          this.enforceModulePolicy(moduleName);\n          const resolved = this.resolveModulePath(moduleName, fromFile);\n          const cacheable = moduleName !== "test/more" && this.evalCapabilityOverrides == null;\n          if (cacheable && this.moduleCache.has(resolved)) {\n            return this.moduleCache.get(resolved);\n          }\n          if (resolved.endsWith(".js")) {\n            return this.loadModule(moduleName, fromFile, contextForPolicy);\n          }\n          if (this.moduleLoading.has(resolved)) {\n            throw new Error("Circular module loading detected");\n          }\n          this.moduleLoading.add(resolved);\n          try {\n            const source = typeof this.host.readFileTextAsync === "function" ? await this.host.readFileTextAsync(resolved) : this.host.readFileText(resolved);\n            let js = this.transpile(source, {\n              asyncImports: true,\n              deferAsyncWrapper: true\n            });\n            const exportNames = resolved.endsWith(".zzm") ? collectTopLevelDeclarations(source, stripPod) : [];\n            let exportBridge = "";\n            if (exportNames.length > 0) {\n              exportBridge = exportNames.map((name2) => {\n                if (name2.startsWith("_")) {\n                  return `if ( typeof ${name2} !== "undefined" ) { const __zuzu_desc = Object.create( null ); __zuzu_desc.get = function() { return ${name2}; }; __zuzu_desc.set = function( value ) { ${name2} = value; }; __zuzu_desc.enumerable = false; __zuzu_desc.configurable = true; Object.defineProperty( module.exports, ${JSON.stringify(name2)}, __zuzu_desc ); }`;\n                }\n                return `if ( typeof ${name2} !== "undefined" ) { const __zuzu_desc = Object.create( null ); __zuzu_desc.get = function() { return ${name2}; }; __zuzu_desc.set = function( value ) { ${name2} = value; }; __zuzu_desc.enumerable = true; __zuzu_desc.configurable = true; Object.defineProperty( module.exports, ${JSON.stringify(name2)}, __zuzu_desc ); }`;\n              }).join("\\n");\n            }\n            js = `( async () => {\n${js}\n${exportBridge}\n} )()`;\n            setCompiledSource(resolved, js);\n            const moduleObj = { exports: {} };\n            const context = this.buildContext({\n              exports: moduleObj.exports,\n              module: moduleObj,\n              filename: resolved\n            });\n            context.__global__ = /* @__PURE__ */ Object.create(null);\n            this.installCollectionMethods(context);\n            const moduleRunOptions = { filename: resolved };\n            if (this.executionTimeoutMs != null) {\n              moduleRunOptions.timeout = this.executionTimeoutMs;\n            }\n            const result = this.host.runInContext(js, context, moduleRunOptions);\n            if (result && typeof result.then === "function") {\n              await result;\n            }\n            if (cacheable) {\n              this.moduleCache.set(resolved, moduleObj.exports);\n            }\n            return moduleObj.exports;\n          } finally {\n            this.moduleLoading.delete(resolved);\n          }\n        }\n        runSource(source, options = {}) {\n          const filename = options.filename || this.host.join(this.repoRoot, "<inline>.zzs");\n          let js;\n          try {\n            js = this.transpile(source);\n          } catch (err) {\n            const stderr = formatRuntimeError(err);\n            if (typeof options.onStderr === "function") {\n              options.onStderr(stderr);\n            }\n            return {\n              status: 3,\n              stdout: "",\n              stderr\n            };\n          }\n          return this.runCompiled(js, options);\n        }\n        runCompiled(js, options = {}) {\n          const filename = options.filename || this.host.join(this.repoRoot, "<inline>.zzs");\n          taskRuntime2.resetForRun(this.debugLevel);\n          setCompiledSource(filename, js);\n          const preloadGlobals = /* @__PURE__ */ Object.create(null);\n          if (Array.isArray(options.preloadModules)) {\n            for (const moduleName of options.preloadModules) {\n              Object.assign(preloadGlobals, this.loadModule(moduleName, filename));\n            }\n          }\n          this.outputLines = [];\n          const previousStdoutHandler = this.stdoutHandler;\n          const previousStderrHandler = this.stderrHandler;\n          this.stdoutHandler = typeof options.onStdout === "function" ? options.onStdout : null;\n          this.stderrHandler = typeof options.onStderr === "function" ? options.onStderr : null;\n          const context = this.buildContext({\n            filename,\n            globals: preloadGlobals\n          });\n          context.__global__ = /* @__PURE__ */ Object.create(null);\n          this.installCollectionMethods(context);\n          const finishRun = () => {\n            let topLevelTests = 0;\n            let hasTopLevelPlan = false;\n            for (const line of this.outputLines) {\n              if (/^\\d+\\.\\.\\d+\\s*$/.test(line)) {\n                hasTopLevelPlan = true;\n              }\n              if (/^ok\\b/.test(line) || /^not ok\\b/.test(line)) {\n                topLevelTests++;\n              }\n            }\n            if (topLevelTests > 0 && !hasTopLevelPlan) {\n              const stdout2 = this.outputLines.length > 0 ? `${this.outputLines.join("\\n")}\n` : "";\n              const stderr = "Error: TAP plan missing (expected 1..N)\\n";\n              if (typeof this.stderrHandler === "function") {\n                this.stderrHandler(stderr);\n              }\n              return {\n                status: 1,\n                stdout: stdout2,\n                stderr\n              };\n            }\n            const stdout = this.outputLines.length > 0 ? `${this.outputLines.join("\\n")}\n` : "";\n            return {\n              status: 0,\n              stdout,\n              stderr: ""\n            };\n          };\n          const failRun = (err) => {\n            const stdout = this.outputLines.length > 0 ? `${this.outputLines.join("\\n")}\n` : "";\n            const isParse = err && err.name === "SyntaxError";\n            const stderr = formatRuntimeError(err);\n            if (typeof this.stderrHandler === "function") {\n              this.stderrHandler(stderr);\n            }\n            return {\n              status: isParse ? 3 : 1,\n              stdout,\n              stderr\n            };\n          };\n          const cleanupRun = (result) => {\n            taskRuntime2.shutdown("Task cancelled");\n            this.outputLines = null;\n            this.stdoutHandler = previousStdoutHandler;\n            this.stderrHandler = previousStderrHandler;\n            return result;\n          };\n          const invokeMain = () => {\n            if (typeof context.__main__ !== "function") {\n              return null;\n            }\n            const argv = Array.isArray(options.scriptArgs) ? options.scriptArgs.map((value) => String(value)) : [];\n            const mainResult = context.__main__(argv);\n            if (mainResult instanceof taskRuntime2.Task || mainResult && typeof mainResult.then === "function") {\n              return taskRuntime2.awaitValue(mainResult);\n            }\n            return null;\n          };\n          try {\n            const scriptRunOptions = { filename };\n            if (this.executionTimeoutMs != null) {\n              scriptRunOptions.timeout = this.executionTimeoutMs;\n            }\n            const topLevelResult = this.host.runInContext(js, context, scriptRunOptions);\n            if (topLevelResult && typeof topLevelResult.then === "function") {\n              return Promise.resolve(topLevelResult).then(invokeMain).then(finishRun, failRun).then(cleanupRun);\n            }\n            const mainResult = invokeMain();\n            if (mainResult && typeof mainResult.then === "function") {\n              return Promise.resolve(mainResult).then(finishRun, failRun).then(cleanupRun);\n            }\n            return cleanupRun(finishRun());\n          } catch (err) {\n            return cleanupRun(failRun(err));\n          }\n        }\n        runFile(scriptPath) {\n          const source = this.host.readFileText(scriptPath);\n          return this.runSource(source, {\n            filename: scriptPath,\n            scriptArgs: []\n          });\n        }\n      };\n      module2.exports = {\n        ZuzuScript,\n        isWeakableValue,\n        makeWeakValue,\n        resolveWeakValue\n      };\n    }\n  });\n\n  // lib/browser-runtime.js\n  var require_browser_runtime = __commonJS({\n    "lib/browser-runtime.js"(exports2, module2) {\n      "use strict";\n      var { createBrowserHost } = require_browser_host();\n      var { transpile } = require_transpiler();\n      var { ZuzuScript } = require_runtime();\n      function _extractLineColumn(errorText) {\n        const match = String(errorText || "").match(/:(\\d+):(\\d+)\\)?(?:\\n|$)/u);\n        if (!match) {\n          return null;\n        }\n        return {\n          line: Number(match[1]),\n          column: Number(match[2])\n        };\n      }\n      function _makeSnippet(source, line, column) {\n        const lines = String(source || "").split(/\\r?\\n/u);\n        if (!Number.isInteger(line) || line < 1 || line > lines.length) {\n          return null;\n        }\n        const content = lines[line - 1];\n        const caretColumn = Number.isInteger(column) && column > 0 ? column : 1;\n        return `${content}\n${" ".repeat(Math.max(0, caretColumn - 1))}^`;\n      }\n      function _toJsError(source, filename, result) {\n        const stderr = String(result && result.stderr || "").trim();\n        const message = stderr || `Zuzu evaluation failed (${filename})`;\n        const err = new Error(message);\n        err.name = result && result.status === 3 ? "ZuzuParseError" : "ZuzuRuntimeError";\n        err.filename = filename;\n        err.source = String(source || "");\n        err.zuzu = {\n          status: result ? result.status : 1,\n          stdout: result ? result.stdout : "",\n          stderr: result ? result.stderr : ""\n        };\n        const where = _extractLineColumn(stderr);\n        if (where) {\n          err.line = where.line;\n          err.column = where.column;\n          err.snippet = _makeSnippet(source, where.line, where.column);\n        }\n        return err;\n      }\n      function _coerceScalarOutput(stdout) {\n        const lines = String(stdout || "").trimEnd().split(/\\r?\\n/u);\n        if (lines.length !== 1) {\n          return void 0;\n        }\n        const raw = lines[0];\n        if (/^-?\\d+(?:\\.\\d+)?$/u.test(raw)) {\n          return Number(raw);\n        }\n        if (raw === "true" || raw === "1") {\n          return true;\n        }\n        if (raw === "false" || raw === "0") {\n          return false;\n        }\n        if (raw === "null") {\n          return null;\n        }\n        return raw;\n      }\n      function createBrowserRuntime(options = {}) {\n        const host = options.host || createBrowserHost(options);\n        const runtime = options.runtime || new ZuzuScript({\n          host,\n          repoRoot: options.repoRoot || host.repoRoot || "/",\n          includePaths: options.includePaths,\n          denyCapabilities: options.denyCapabilities,\n          allowCapabilities: options.allowCapabilities,\n          denyModules: options.denyModules,\n          debugLevel: options.debugLevel,\n          executionTimeoutMs: options.executionTimeoutMs,\n          transpiler: options.transpiler\n        });\n        function _runSource(source, evalOptions = {}) {\n          const filename = evalOptions.filename || "/<browser>.zzs";\n          return runtime.runSource(String(source ?? ""), {\n            filename,\n            preloadModules: evalOptions.preloadModules || []\n          });\n        }\n        function zuzu_run(source, evalOptions = {}) {\n          const result = _runSource(source, evalOptions);\n          if (result && typeof result.then === "function") {\n            return result.then((resolved) => {\n              if (evalOptions.throwOnError !== false && resolved.status !== 0) {\n                throw _toJsError(source, evalOptions.filename || "/<browser>.zzs", resolved);\n              }\n              return resolved;\n            });\n          }\n          if (evalOptions.throwOnError !== false && result.status !== 0) {\n            throw _toJsError(source, evalOptions.filename || "/<browser>.zzs", result);\n          }\n          return result;\n        }\n        function zuzu_eval(source, evalOptions = {}) {\n          const sourceText = String(source ?? "");\n          const filename = evalOptions.filename || "/<browser>.zzs";\n          const run = () => {\n            if (evalOptions.result === true) {\n              return zuzu_run(sourceText, evalOptions);\n            }\n            const expressionResult = _runSource(`say( ${sourceText} );`, {\n              ...evalOptions,\n              filename\n            });\n            if (expressionResult && typeof expressionResult.then === "function") {\n              return expressionResult.then((resolvedExpression) => {\n                if (resolvedExpression.status === 0) {\n                  return _coerceScalarOutput(resolvedExpression.stdout);\n                }\n                return Promise.resolve(zuzu_run(sourceText, evalOptions)).then((result2) => {\n                  if (result2.stdout && evalOptions.returnStdout === true) {\n                    return result2.stdout;\n                  }\n                  return void 0;\n                });\n              });\n            }\n            if (expressionResult.status === 0) {\n              return _coerceScalarOutput(expressionResult.stdout);\n            }\n            const result = zuzu_run(sourceText, evalOptions);\n            if (result.stdout && evalOptions.returnStdout === true) {\n              return result.stdout;\n            }\n            return void 0;\n          };\n          if (evalOptions.async === true) {\n            return Promise.resolve().then(run);\n          }\n          return run();\n        }\n        function zuzu_compile(source, _compileOptions = {}) {\n          return transpile(String(source ?? ""), {\n            transpiler: runtime.transpiler\n          });\n        }\n        return {\n          host,\n          runtime,\n          zuzu_eval,\n          zuzu_run,\n          zuzu_compile\n        };\n      }\n      module2.exports = {\n        createBrowserRuntime\n      };\n    }\n  });\n\n  // modules/std/marshal/graph.js\n  var require_graph = __commonJS({\n    "modules/std/marshal/graph.js"(exports2, module2) {\n      "use strict";\n      var {\n        BinaryString: BinaryString2,\n        ZuzuBinary,\n        ZuzuBag,\n        Pair,\n        PairList,\n        isPairListLike,\n        isWeakCell,\n        makeWeakValue,\n        retainCollectionValue,\n        retainValue,\n        resolveWeakValue\n      } = require_runtime_helpers();\n      var cbor = require_cbor();\n      var KIND_PAIR = 1;\n      var KIND_ARRAY = 2;\n      var KIND_DICT = 3;\n      var KIND_PAIRLIST = 4;\n      var KIND_SET = 5;\n      var KIND_BAG = 6;\n      var KIND_OBJECT = 7;\n      var KIND_FUNCTION = 8;\n      var KIND_CLASS = 9;\n      var KIND_TRAIT = 10;\n      var KIND_BOUND_METHOD = 11;\n      var KIND_TIME = 12;\n      var KIND_PATH = 13;\n      var CODE_FUNCTION = 1;\n      var CODE_CLASS = 2;\n      var CODE_TRAIT = 3;\n      var MAX_SAFE_INTEGER = 9007199254740991;\n      var classRegistry = /* @__PURE__ */ new Map();\n      var codeRegistry = /* @__PURE__ */ new Map();\n      var runtimePolicy2 = {\n        host_name: "node",\n        repo_root: null,\n        include_paths: [],\n        deny_modules: [],\n        debug_level: 0,\n        transpiler: null\n      };\n      function setRuntimePolicy2(policy = {}) {\n        runtimePolicy2 = {\n          ...runtimePolicy2,\n          ...policy,\n          include_paths: Array.isArray(policy.include_paths) ? policy.include_paths.slice() : runtimePolicy2.include_paths,\n          deny_modules: Array.isArray(policy.deny_modules) ? policy.deny_modules.slice() : runtimePolicy2.deny_modules\n        };\n      }\n      function dumpGraph(value) {\n        const state = {\n          objects: [],\n          ids: /* @__PURE__ */ new WeakMap(),\n          code: [],\n          codeIds: /* @__PURE__ */ new WeakMap(),\n          onDump: /* @__PURE__ */ new WeakSet()\n        };\n        const root = encodeValue(value, state);\n        return cbor.encodeOne(\n          cbor.tag(cbor.SELF_DESCRIBED_TAG, [\n            cbor.textString("ZUZU-MARSHAL"),\n            1,\n            /* @__PURE__ */ new Map(),\n            root,\n            state.objects,\n            state.code\n          ])\n        );\n      }\n      function loadGraph(blob) {\n        if (!(blob instanceof BinaryString2)) {\n          throw new Error(\n            `TypeException: std/marshal.load expects BinaryString, got ${typeName2(blob)}`\n          );\n        }\n        const decoded = cbor.decodeOne(blob);\n        const envelope = decodeEnvelope(decoded);\n        const codeValues = loadCodeTable(envelope.code);\n        const placeholders = allocatePlaceholders(envelope.objects, codeValues);\n        fillPlaceholders(envelope.objects, placeholders);\n        const value = decodeValue(envelope.root, placeholders, {\n          allowWeak: false,\n          context: "Envelope root"\n        });\n        runOnLoadHooks(envelope.objects, placeholders);\n        return value;\n      }\n      function safeToDumpGraph(value) {\n        try {\n          dumpGraph(value);\n          return true;\n        } catch (_err) {\n          return false;\n        }\n      }\n      function encodeValue(value, state) {\n        if (isWeakCell(value)) {\n          return [1, encodeValue(resolveWeakValue(value), state)];\n        }\n        if (value == null) {\n          return null;\n        }\n        if (typeof value === "boolean") {\n          return value;\n        }\n        if (typeof value === "number") {\n          return encodeNumber(value);\n        }\n        if (typeof value === "string") {\n          return cbor.textString(value);\n        }\n        if (value instanceof ZuzuBinary) {\n          return cbor.byteString(value.bytes);\n        }\n        if (isBoundMethodValue(value)) {\n          return encodeBoundMethod(value, state);\n        }\n        if (isUserClassValue(value)) {\n          return encodeClassReference(value, state);\n        }\n        if (isTraitValue(value)) {\n          return encodeTraitReference(value, state);\n        }\n        if (isFunctionValue(value)) {\n          return encodeFunctionReference(value, state);\n        }\n        if (value instanceof Pair) {\n          return encodeObjectTableValue(value, KIND_PAIR, state, encodePairPayload);\n        }\n        if (Array.isArray(value)) {\n          return encodeObjectTableValue(value, KIND_ARRAY, state, encodeArrayPayload);\n        }\n        if (isPairListLike(value)) {\n          return encodeObjectTableValue(\n            value,\n            KIND_PAIRLIST,\n            state,\n            encodePairListPayload\n          );\n        }\n        if (value instanceof Set) {\n          return encodeObjectTableValue(value, KIND_SET, state, encodeSetPayload);\n        }\n        if (value instanceof ZuzuBag) {\n          return encodeObjectTableValue(value, KIND_BAG, state, encodeBagPayload);\n        }\n        if (isTimeValue(value)) {\n          return encodeObjectTableValue(value, KIND_TIME, state, encodeTimePayload);\n        }\n        if (isPathValue(value)) {\n          return encodeObjectTableValue(value, KIND_PATH, state, encodePathPayload);\n        }\n        if (isPlainDict(value)) {\n          return encodeObjectTableValue(value, KIND_DICT, state, encodeDictPayload);\n        }\n        if (isUserObjectValue(value)) {\n          return encodeUserObject(value, state);\n        }\n        throw new Error(`Value of type ${typeName2(value)} is not marshalable in this phase`);\n      }\n      function encodeNumber(value) {\n        if (!Number.isFinite(value)) {\n          throw new Error("Number values must be finite");\n        }\n        if (!Object.is(value, -0) && Number.isInteger(value) && Math.abs(value) <= MAX_SAFE_INTEGER) {\n          return value;\n        }\n        return Number(value);\n      }\n      function encodeObjectTableValue(value, kind, state, payloadEncoder) {\n        if (state.ids.has(value)) {\n          return [0, state.ids.get(value)];\n        }\n        const id = state.objects.length;\n        state.ids.set(value, id);\n        state.objects.push(null);\n        state.objects[id] = [kind, payloadEncoder(value, state)];\n        return [0, id];\n      }\n      function encodeArrayPayload(value, state) {\n        return value.map((item) => encodeValue(item, state));\n      }\n      function encodeDictPayload(value, state) {\n        return Object.keys(value).sort().map((key) => [\n          cbor.textString(key),\n          encodeValue(value[key], state)\n        ]);\n      }\n      function encodePairListPayload(value, state) {\n        return value.list.map((pair) => [\n          cbor.textString(pair[0]),\n          encodeValue(pair[1], state)\n        ]);\n      }\n      function encodeSetPayload(value, state) {\n        return [...value].map((item) => encodeValue(item, state));\n      }\n      function encodeBagPayload(value, state) {\n        return value.items.map((item) => encodeValue(item, state));\n      }\n      function encodePairPayload(value, state) {\n        return [\n          cbor.textString(value.key()),\n          encodeValue(value.value(), state)\n        ];\n      }\n      function encodeTimePayload(value, _state) {\n        const epoch = typeof value.epoch === "function" ? value.epoch() : value._epoch;\n        if (typeof epoch !== "number" || !Number.isFinite(epoch)) {\n          throw new Error("Time value has invalid internal epoch");\n        }\n        const zone = typeof value.timezone === "function" ? value.timezone().to_String() : value._timezone;\n        if (zone == null) {\n          return [encodeNumber(epoch)];\n        }\n        return [encodeNumber(epoch), cbor.textString(String(zone))];\n      }\n      function encodePathPayload(value, _state) {\n        const pathText = typeof value.to_String === "function" ? value.to_String() : value.value;\n        if (pathText == null) {\n          throw new Error("Path value has invalid internal path");\n        }\n        return [cbor.textString(pathText)];\n      }\n      function encodeUserObject(value, state) {\n        if (state.ids.has(value)) {\n          return [0, state.ids.get(value)];\n        }\n        if (!state.onDump.has(value)) {\n          state.onDump.add(value);\n          if (typeof value.__on_dump__ === "function") {\n            try {\n              value.__on_dump__();\n            } catch (err) {\n              throw new Error(\n                `__on_dump__ for ${typeName2(value)} failed: ${err.message || err}`\n              );\n            }\n          }\n        }\n        const id = state.objects.length;\n        state.ids.set(value, id);\n        state.objects.push(null);\n        const slots = Object.keys(value).filter((key) => isMarshalableObjectSlot(value[key])).sort().map((key) => [\n          cbor.textString(key),\n          encodeValue(value[key], state)\n        ]);\n        state.objects[id] = [\n          KIND_OBJECT,\n          [\n            encodeClassReference(value.constructor, state),\n            slots\n          ]\n        ];\n        return [0, id];\n      }\n      function encodeBoundMethod(value, state) {\n        if (state.ids.has(value)) {\n          return [0, state.ids.get(value)];\n        }\n        const receiver = value.__zuzu_bound_receiver || value.receiver || null;\n        const methodName = value.__zuzu_bound_method_name || value.name;\n        if (!receiver || !methodName) {\n          throw new Error("Bound method values are not marshalable in this phase");\n        }\n        const id = state.objects.length;\n        state.ids.set(value, id);\n        state.objects.push(null);\n        state.objects[id] = [\n          KIND_BOUND_METHOD,\n          [\n            encodeValue(receiver, state),\n            cbor.textString(methodName)\n          ]\n        ];\n        return [0, id];\n      }\n      function encodeFunctionReference(fn2, state) {\n        return encodeCodeBackedObject(fn2, KIND_FUNCTION, state, encodeFunctionCode);\n      }\n      function encodeTraitReference(trait, state) {\n        return encodeCodeBackedObject(trait, KIND_TRAIT, state, encodeTraitCode);\n      }\n      function encodeCodeBackedObject(value, kind, state, codeEncoder) {\n        if (state.ids.has(value)) {\n          return [0, state.ids.get(value)];\n        }\n        const id = state.objects.length;\n        state.ids.set(value, id);\n        state.objects.push(null);\n        const codeId = codeEncoder(value, state);\n        state.objects[id] = [kind, [codeId]];\n        return [0, id];\n      }\n      function encodeClassReference(klass, state) {\n        if (!isUserClassValue(klass)) {\n          throw new Error("Object class is not marshalable in this phase");\n        }\n        return encodeCodeBackedObject(klass, KIND_CLASS, state, encodeClassCode);\n      }\n      function encodeClassCode(klass, state) {\n        if (!klass.__zuzu_marshal_meta) {\n          Object.defineProperty(klass, "__zuzu_marshal_meta", {\n            value: {\n              kind: "class",\n              name: klass.__zuzu_class_name || klass.name,\n              source: marshalClassSource(klass, klass.__zuzu_class_name || klass.name),\n              captures: {}\n            },\n            enumerable: false,\n            configurable: true,\n            writable: true\n          });\n        }\n        return encodeCodeRecord(klass, state, CODE_CLASS);\n      }\n      function encodeFunctionCode(fn2, state, preferredName = null) {\n        return encodeCodeRecord(fn2, state, CODE_FUNCTION, preferredName);\n      }\n      function encodeTraitCode(trait, state, preferredName = null) {\n        return encodeCodeRecord(trait, state, CODE_TRAIT, preferredName);\n      }\n      function encodeCodeRecord(value, state, kind, preferredName = null) {\n        if (state.codeIds.has(value)) {\n          return state.codeIds.get(value);\n        }\n        const meta = value.__zuzu_marshal_meta || {};\n        if (!meta.source) {\n          throw new Error(`Value of type ${typeName2(value)} is not marshalable in this phase`);\n        }\n        const id = state.code.length;\n        state.codeIds.set(value, id);\n        state.code.push(null);\n        const bindingName = marshalBindingName(preferredName || meta.name, id);\n        const captures = [];\n        const dependencies = [];\n        for (const [name2, captured] of Object.entries(meta.captures || {}).sort(\n          (left, right) => left[0].localeCompare(right[0])\n        )) {\n          if (isFunctionValue(captured)) {\n            dependencies.push([0, encodeFunctionCode(captured, state, name2)]);\n          } else if (isUserClassValue(captured)) {\n            dependencies.push([0, encodeClassCode(captured, state, name2)]);\n          } else if (isTraitValue(captured)) {\n            dependencies.push([0, encodeTraitCode(captured, state, name2)]);\n          } else if (isScalarForCapture(captured)) {\n            captures.push([cbor.textString(name2), encodeValue(captured, state)]);\n          }\n        }\n        registerCodeValue(kind, bindingName, meta.source, value);\n        state.code[id] = [\n          kind,\n          cbor.textString(bindingName),\n          cbor.textString(meta.source),\n          captures,\n          dependencies\n        ];\n        return id;\n      }\n      function decodeEnvelope(decoded) {\n        if (!cbor.isTagged(decoded) || cbor.tagNumber(decoded) !== cbor.SELF_DESCRIBED_TAG) {\n          throw new Error("Top-level item is not tag 55799");\n        }\n        const envelope = cbor.tagValue(decoded);\n        if (!Array.isArray(envelope)) {\n          throw new Error("Envelope must be an array");\n        }\n        if (envelope.length !== 6) {\n          throw new Error("Envelope must contain exactly 6 fields");\n        }\n        const [magic, version, options, root, objects, code] = envelope;\n        if (!cbor.isTextString(magic) || cbor.textValue(magic) !== "ZUZU-MARSHAL") {\n          throw new Error("Envelope magic is invalid");\n        }\n        if (typeof version !== "number" || version !== 1) {\n          throw new Error("Unsupported Zuzu Marshal version");\n        }\n        if (!(options instanceof Map)) {\n          throw new Error("Envelope options must be a map");\n        }\n        if (!Array.isArray(objects)) {\n          throw new Error("Envelope object table must be an array");\n        }\n        if (!Array.isArray(code)) {\n          throw new Error("Envelope code table must be an array");\n        }\n        return { root, objects, code };\n      }\n      function loadCodeTable(code) {\n        const records = code.map(validateCodeRecord);\n        const values = [];\n        const loading = /* @__PURE__ */ new Set();\n        function loadById(id) {\n          if (values[id]) {\n            return values[id];\n          }\n          if (loading.has(id)) {\n            throw new Error(`Cyclic code dependency involving record ${id}`);\n          }\n          loading.add(id);\n          const value = loadCodeRecord(records[id], id, loadById);\n          values[id] = value;\n          loading.delete(id);\n          return value;\n        }\n        for (let id = 0; id < records.length; id++) {\n          loadById(id);\n        }\n        return values;\n      }\n      function validateCodeRecord(record, id) {\n        assertRecordArray(record, `Code table entry ${id}`, 5);\n        const [kind, bindingNameValue, sourceValue, captures, dependencies] = record;\n        assertInteger(kind, `Code table entry ${id} kind`);\n        if (![CODE_FUNCTION, CODE_CLASS, CODE_TRAIT].includes(kind)) {\n          throw new Error(`Unsupported code kind ${kind} in current loader`);\n        }\n        if (!cbor.isTextString(bindingNameValue)) {\n          throw new Error(`Code table entry ${id} binding name must be a text string`);\n        }\n        if (!cbor.isTextString(sourceValue)) {\n          throw new Error(`Code table entry ${id} source must be a text string`);\n        }\n        if (!Array.isArray(captures)) {\n          throw new Error(`Code table entry ${id} captures must be an array`);\n        }\n        if (!Array.isArray(dependencies)) {\n          throw new Error(`Code table entry ${id} dependencies must be an array`);\n        }\n        return {\n          kind,\n          bindingName: cbor.textValue(bindingNameValue),\n          source: cbor.textValue(sourceValue),\n          captures,\n          dependencies\n        };\n      }\n      function loadCodeRecord(record, id, loadById) {\n        const registered = codeRegistry.get(\n          codeRegistryKey(record.kind, record.bindingName, record.source)\n        );\n        if (registered) {\n          return registered;\n        }\n        const env = /* @__PURE__ */ Object.create(null);\n        for (const capture of record.captures) {\n          assertRecordArray(capture, `Capture in code record ${id}`, 2);\n          const [nameValue, encodedValue] = capture;\n          if (!cbor.isTextString(nameValue)) {\n            throw new Error(`Capture name in code record ${id} must be a text string`);\n          }\n          const name2 = cbor.textValue(nameValue);\n          if (isWeakStorageRecord(encodedValue)) {\n            throw new Error(\n              `Capture \'${name2}\' in code record ${id} weak storage record is not allowed here`\n            );\n          }\n          env[name2] = decodeScalar(encodedValue);\n        }\n        for (const dependency of record.dependencies) {\n          assertRecordArray(dependency, `Code dependency in record ${id}`, 2);\n          const [depKind, depId] = dependency;\n          assertInteger(depKind, `Code dependency in record ${id} kind`);\n          if (depKind !== 0) {\n            throw new Error(`Unsupported code dependency kind ${depKind} in record ${id}`);\n          }\n          assertInteger(depId, `Internal dependency in record ${id}`);\n          const value = loadById(depId);\n          const name2 = value.__zuzu_class_name || value.__zuzu_trait_name || value.__zuzu_marshal_meta && value.__zuzu_marshal_meta.name;\n          if (name2) {\n            env[name2] = value;\n          }\n        }\n        if (record.kind === CODE_FUNCTION) {\n          return buildFunctionFromSource(record.bindingName, record.source, env);\n        }\n        if (record.kind === CODE_CLASS) {\n          return buildClassFromSource(record.bindingName, record.source, env);\n        }\n        return buildTraitFromSource(record.bindingName, record.source, env);\n      }\n      function allocatePlaceholders(objects, codeValues) {\n        const placeholders = [];\n        for (let id = 0; id < objects.length; id++) {\n          const entry = objects[id];\n          assertRecordArray(entry, `Object table entry ${id}`, 2);\n          const kind = entry[0];\n          assertInteger(kind, `Object table entry ${id} kind`);\n          switch (kind) {\n            case KIND_PAIR:\n              placeholders[id] = new Pair({ pair: [] });\n              break;\n            case KIND_ARRAY:\n              placeholders[id] = [];\n              break;\n            case KIND_DICT:\n              placeholders[id] = {};\n              break;\n            case KIND_PAIRLIST:\n              placeholders[id] = new PairList([]);\n              break;\n            case KIND_SET:\n              placeholders[id] = /* @__PURE__ */ new Set();\n              break;\n            case KIND_BAG:\n              placeholders[id] = new ZuzuBag([]);\n              break;\n            case KIND_OBJECT:\n              placeholders[id] = {};\n              break;\n            case KIND_FUNCTION:\n              placeholders[id] = decodeFunctionPayload(id, entry[1], codeValues);\n              break;\n            case KIND_CLASS:\n              placeholders[id] = decodeClassPayload(id, entry[1], codeValues);\n              break;\n            case KIND_TRAIT:\n              placeholders[id] = decodeTraitPayload(id, entry[1], codeValues);\n              break;\n            case KIND_BOUND_METHOD:\n              placeholders[id] = createBoundMethodPlaceholder(id);\n              break;\n            case KIND_TIME:\n              placeholders[id] = new (timeClass())(0);\n              break;\n            case KIND_PATH:\n              placeholders[id] = new (pathClass())(".");\n              break;\n            default:\n              throw new Error(`Unsupported object kind ${kind} in current loader`);\n          }\n        }\n        return placeholders;\n      }\n      function fillPlaceholders(objects, placeholders) {\n        for (let id = 0; id < objects.length; id++) {\n          const [kind, payload] = objects[id];\n          switch (kind) {\n            case KIND_PAIR:\n              fillPair(id, payload, placeholders);\n              break;\n            case KIND_ARRAY:\n              fillArray(id, payload, placeholders);\n              break;\n            case KIND_DICT:\n              fillDict(id, payload, placeholders);\n              break;\n            case KIND_PAIRLIST:\n              fillPairList(id, payload, placeholders);\n              break;\n            case KIND_SET:\n              fillSet(id, payload, placeholders);\n              break;\n            case KIND_BAG:\n              fillBag(id, payload, placeholders);\n              break;\n            case KIND_OBJECT:\n              fillObject(id, payload, placeholders);\n              break;\n            case KIND_FUNCTION:\n              break;\n            case KIND_CLASS:\n              break;\n            case KIND_TRAIT:\n              break;\n            case KIND_BOUND_METHOD:\n              break;\n            case KIND_TIME:\n              fillTime(id, payload, placeholders);\n              break;\n            case KIND_PATH:\n              fillPath(id, payload, placeholders);\n              break;\n            default:\n              throw new Error(`Unsupported object kind ${kind} in current loader`);\n          }\n        }\n        for (let id = 0; id < objects.length; id++) {\n          const [kind, payload] = objects[id];\n          if (kind === KIND_BOUND_METHOD) {\n            fillBoundMethodPayload(id, payload, placeholders);\n          }\n        }\n      }\n      function fillPair(id, payload, placeholders) {\n        assertRecordArray(payload, `Pair object payload ${id}`, 2);\n        const [key, value] = payload;\n        if (!cbor.isTextString(key)) {\n          throw new Error(`Pair object payload ${id} key must be a text string`);\n        }\n        placeholders[id].pair = [\n          cbor.textValue(key),\n          storeStrongLoadedValue(decodeValue(value, placeholders, {\n            context: `Pair object payload ${id} value`\n          }))\n        ];\n      }\n      function fillArray(id, payload, placeholders) {\n        if (!Array.isArray(payload)) {\n          throw new Error(`Array object payload ${id} must be an array`);\n        }\n        placeholders[id].splice(\n          0,\n          placeholders[id].length,\n          ...payload.map((item) => storeCollectionLoadedValue(\n            placeholders[id],\n            decodeValue(\n              item,\n              placeholders,\n              { context: `Array object payload ${id} item` }\n            )\n          ))\n        );\n      }\n      function fillDict(id, payload, placeholders) {\n        if (!Array.isArray(payload)) {\n          throw new Error(`Dict object payload ${id} must be an array`);\n        }\n        const target = placeholders[id];\n        for (const pair of payload) {\n          const [key, value] = decodeKeyValueRecord(\n            `Dict object payload ${id}`,\n            pair,\n            placeholders\n          );\n          if (Object.prototype.hasOwnProperty.call(target, key)) {\n            throw new Error(`Dict object payload ${id} contains duplicate key \'${key}\'`);\n          }\n          target[key] = storeCollectionLoadedValue(target, value);\n        }\n      }\n      function fillPairList(id, payload, placeholders) {\n        if (!Array.isArray(payload)) {\n          throw new Error(`PairList object payload ${id} must be an array`);\n        }\n        placeholders[id].list = payload.map((pair) => {\n          const [key, value] = decodeKeyValueRecord(\n            `PairList object payload ${id}`,\n            pair,\n            placeholders\n          );\n          return [key, storeCollectionLoadedValue(placeholders[id], value)];\n        });\n      }\n      function fillSet(id, payload, placeholders) {\n        for (const item of decodeItemPayload(\n          `Set object payload ${id}`,\n          payload,\n          placeholders\n        )) {\n          placeholders[id].add(storeCollectionLoadedValue(placeholders[id], item));\n        }\n      }\n      function fillBag(id, payload, placeholders) {\n        placeholders[id].items = decodeItemPayload(\n          `Bag object payload ${id}`,\n          payload,\n          placeholders\n        ).map((item) => storeCollectionLoadedValue(placeholders[id], item));\n      }\n      function fillTime(id, payload, placeholders) {\n        if (!Array.isArray(payload) || payload.length !== 1 && payload.length !== 2) {\n          throw new Error(`Time object payload ${id} must contain epoch and optional timezone`);\n        }\n        const epoch = payload[0];\n        if (typeof epoch !== "number") {\n          throw new Error(`Time object payload ${id} epoch must be a number`);\n        }\n        placeholders[id]._epoch = epoch;\n        placeholders[id]._timezone = payload.length > 1 && cbor.isTextString(payload[1]) ? cbor.textValue(payload[1]) : "UTC";\n      }\n      function fillPath(id, payload, placeholders) {\n        assertRecordArray(payload, `Path object payload ${id}`, 1);\n        const pathValue = payload[0];\n        if (!cbor.isTextString(pathValue)) {\n          throw new Error(`Path object payload ${id} path must be a text string`);\n        }\n        placeholders[id].value = cbor.textValue(pathValue);\n      }\n      function decodeFunctionPayload(id, payload, codeValues) {\n        return decodeCodeBackedPayload("Function", id, payload, codeValues);\n      }\n      function decodeClassPayload(id, payload, codeValues) {\n        return decodeCodeBackedPayload("Class", id, payload, codeValues);\n      }\n      function decodeTraitPayload(id, payload, codeValues) {\n        return decodeCodeBackedPayload("Trait", id, payload, codeValues);\n      }\n      function decodeCodeBackedPayload(label, id, payload, codeValues) {\n        assertRecordArray(payload, `${label} object payload ${id}`, 1);\n        const codeId = payload[0];\n        if (isWeakStorageRecord(codeId)) {\n          throw new Error(`${label} object payload ${id} code id weak storage record is not allowed here`);\n        }\n        assertInteger(codeId, `${label} object payload ${id} code id`);\n        if (codeId < 0 || codeId >= codeValues.length) {\n          throw new Error(`${label} object payload ${id} code id is outside the code table`);\n        }\n        return codeValues[codeId];\n      }\n      function createBoundMethodPlaceholder(id) {\n        const fn2 = function __zuzu_loaded_bound_method(...args) {\n          const receiver = fn2.__zuzu_bound_receiver;\n          const methodName = fn2.__zuzu_bound_method_name;\n          if (receiver == null || typeof receiver[methodName] !== "function") {\n            throw new Error(`Bound method object payload ${id} method is not loaded`);\n          }\n          return receiver[methodName](...args);\n        };\n        Object.defineProperty(fn2, "__zuzu_method", {\n          value: true,\n          enumerable: false,\n          configurable: true\n        });\n        fn2.invoke = function invoke(_self, args = []) {\n          return fn2(...args);\n        };\n        return fn2;\n      }\n      function fillBoundMethodPayload(id, payload, placeholders) {\n        assertRecordArray(payload, `Bound method object payload ${id}`, 2);\n        const receiver = decodeValue(payload[0], placeholders, {\n          allowWeak: false,\n          context: `Bound method object payload ${id} receiver`\n        });\n        if (receiver == null || typeof receiver !== "object") {\n          throw new Error(`Bound method object payload ${id} receiver must resolve to an Object`);\n        }\n        if (!cbor.isTextString(payload[1])) {\n          throw new Error(`Bound method object payload ${id} method name must be a text string`);\n        }\n        const methodName = cbor.textValue(payload[1]);\n        if (typeof receiver[methodName] !== "function") {\n          throw new Error(\n            `Bound method object payload ${id} method \'${methodName}\' was not found`\n          );\n        }\n        const fn2 = placeholders[id];\n        Object.defineProperty(fn2, "__zuzu_bound_receiver", {\n          value: receiver,\n          enumerable: false,\n          configurable: true,\n          writable: true\n        });\n        Object.defineProperty(fn2, "__zuzu_bound_method_name", {\n          value: methodName,\n          enumerable: false,\n          configurable: true,\n          writable: true\n        });\n        fn2.invoke = function invoke(_self, args = []) {\n          return receiver[methodName](...args);\n        };\n      }\n      function fillObject(id, payload, placeholders) {\n        assertRecordArray(payload, `Object payload ${id}`, 2);\n        const [classRef, slotPayload] = payload;\n        const klass = decodeValue(classRef, placeholders, {\n          allowWeak: false,\n          context: `Object payload ${id} class`\n        });\n        if (typeof klass !== "function") {\n          throw new Error(`Object payload ${id} class must resolve to a Class`);\n        }\n        if (!Array.isArray(slotPayload)) {\n          throw new Error(`Object payload ${id} slots must be an array`);\n        }\n        const object = placeholders[id];\n        Object.setPrototypeOf(object, klass.prototype);\n        const seen = /* @__PURE__ */ new Set();\n        for (const record of slotPayload) {\n          assertRecordArray(record, `Object payload ${id} slot records`, 2);\n          const [nameValue, encodedValue] = record;\n          if (!cbor.isTextString(nameValue)) {\n            throw new Error(`Object payload ${id} slot names must be text strings`);\n          }\n          const name2 = cbor.textValue(nameValue);\n          if (seen.has(name2)) {\n            throw new Error(`Object payload ${id} contains duplicate slot \'${name2}\'`);\n          }\n          seen.add(name2);\n          object[name2] = storeStrongLoadedValue(decodeValue(encodedValue, placeholders, {\n            context: `Object payload ${id} slot \'${name2}\'`\n          }));\n        }\n      }\n      function runOnLoadHooks(objects, placeholders) {\n        for (let id = 0; id < objects.length; id++) {\n          const [kind] = objects[id];\n          if (kind !== KIND_OBJECT) {\n            continue;\n          }\n          const object = placeholders[id];\n          if (typeof object.__on_load__ === "function") {\n            try {\n              object.__on_load__();\n            } catch (err) {\n              throw new Error(\n                `__on_load__ for ${typeName2(object)} failed: ${err.message || err}`\n              );\n            }\n          }\n        }\n      }\n      function decodeItemPayload(context, payload, placeholders) {\n        if (!Array.isArray(payload)) {\n          throw new Error(`${context} must be an array`);\n        }\n        return payload.map((item) => decodeValue(item, placeholders, {\n          context: `${context} item`\n        }));\n      }\n      function decodeKeyValueRecord(context, pair, placeholders) {\n        assertRecordArray(pair, `${context} entries`, 2);\n        const [key, value] = pair;\n        if (!cbor.isTextString(key)) {\n          throw new Error(`${context} keys must be text strings`);\n        }\n        return [\n          cbor.textValue(key),\n          decodeValue(value, placeholders, {\n            context: `${context} value`\n          })\n        ];\n      }\n      function decodeValue(value, placeholders, opts = {}) {\n        const allowWeak = Object.prototype.hasOwnProperty.call(opts, "allowWeak") ? opts.allowWeak : true;\n        const context = opts.context || "Encoded value";\n        if (isEncodedScalar(value)) {\n          return decodeScalar(value);\n        }\n        if (Array.isArray(value)) {\n          if (value.length !== 2) {\n            throw new Error(`${context} array must be [0, id] or [1, value]`);\n          }\n          const [marker, id] = value;\n          if (!isInteger(marker) || marker !== 0 && marker !== 1) {\n            throw new Error(`${context} marker must be 0 or 1`);\n          }\n          if (marker === 1) {\n            validateWeakStorageRecord(value, placeholders, context);\n            if (!allowWeak) {\n              throw new Error(`${context} weak storage record is not allowed here`);\n            }\n            return makeWeakValue(decodeValue(id, placeholders, {\n              allowWeak: false,\n              context: `${context} weak storage value`\n            }));\n          }\n          if (!isInteger(id)) {\n            throw new Error("Encoded reference id must be an integer");\n          }\n          if (id < 0 || id >= placeholders.length) {\n            throw new Error(`Reference id ${id} is outside the object table`);\n          }\n          return placeholders[id];\n        }\n        throw new Error("Envelope root is not a scalar or supported reference");\n      }\n      function storeStrongLoadedValue(value) {\n        return isWeakCell(value) ? value : retainValue(value);\n      }\n      function storeCollectionLoadedValue(owner, value) {\n        return isWeakCell(value) ? value : retainCollectionValue(owner, value);\n      }\n      function validateWeakStorageRecord(record, placeholders, context) {\n        assertRecordArray(record, `${context} weak storage record`, 2);\n        const inner = record[1];\n        if (isWeakStorageRecord(inner)) {\n          throw new Error(`${context} nested weak storage records are invalid`);\n        }\n        decodeValue(inner, placeholders, {\n          allowWeak: false,\n          context: `${context} weak storage value`\n        });\n      }\n      function isWeakStorageRecord(value) {\n        return Array.isArray(value) && value.length === 2 && value[0] === 1;\n      }\n      function isEncodedScalar(value) {\n        return value == null || typeof value === "boolean" || typeof value === "number" || cbor.isTextString(value) || cbor.isByteString(value);\n      }\n      function decodeScalar(value) {\n        if (value == null) {\n          return null;\n        }\n        if (typeof value === "boolean" || typeof value === "number") {\n          return value;\n        }\n        if (cbor.isTextString(value)) {\n          return cbor.textValue(value);\n        }\n        if (cbor.isByteString(value)) {\n          return new BinaryString2(cbor.bytesValue(value));\n        }\n        throw new Error("Envelope root is not a scalar value");\n      }\n      function assertRecordArray(value, context, length) {\n        if (!Array.isArray(value) || value.length !== length) {\n          const item = length === 1 ? "one-item" : `${length}-item`;\n          throw new Error(`${context} must be a ${item} array`);\n        }\n      }\n      function assertInteger(value, context) {\n        if (!isInteger(value)) {\n          throw new Error(`${context} must be an integer`);\n        }\n      }\n      function isInteger(value) {\n        return typeof value === "number" && Number.isInteger(value);\n      }\n      function isPlainDict(value) {\n        if (value == null || typeof value !== "object") {\n          return false;\n        }\n        if (value instanceof ZuzuBinary || value instanceof Pair || isPairListLike(value)) {\n          return false;\n        }\n        if (value instanceof Set || value instanceof ZuzuBag || Array.isArray(value)) {\n          return false;\n        }\n        if (isTimeValue(value) || isPathValue(value)) {\n          return false;\n        }\n        const proto = Object.getPrototypeOf(value);\n        if (proto === null || proto === Object.prototype) {\n          return true;\n        }\n        return Object.prototype.toString.call(value) === "[object Object]" && value.constructor && value.constructor.name === "Object";\n      }\n      function isUserObjectValue(value) {\n        return value && typeof value === "object" && !Array.isArray(value) && isUserClassValue(value.constructor) && !isTimeValue(value) && !isPathValue(value);\n      }\n      function isFunctionValue(value) {\n        return typeof value === "function" && !isUserClassValue(value) && value.__zuzu_marshal_meta && value.__zuzu_marshal_meta.kind === "function";\n      }\n      function isUserClassValue(value) {\n        return typeof value === "function" && typeof value.__zuzu_class_name === "string" && value.__zuzu_class_spec && typeof value.__zuzu_class_spec === "object";\n      }\n      function isTraitValue(value) {\n        return value && typeof value === "object" && value.__zuzu_trait_methods && typeof value.__zuzu_trait_name === "string";\n      }\n      function isBoundMethodValue(value) {\n        return value && (value.__zuzu_method || value.constructor && value.constructor.name === "ZuzuMethod");\n      }\n      function isScalarForCapture(value) {\n        return value == null || typeof value === "boolean" || typeof value === "number" || typeof value === "string" || value instanceof ZuzuBinary;\n      }\n      function isMarshalableObjectSlot(value) {\n        return typeof value !== "function";\n      }\n      function isTimeValue(value) {\n        return value && typeof value === "object" && (value.__zuzu_type_name === "Time" || value.constructor && value.constructor.name === "Time") && (typeof value.epoch === "function" || typeof value._epoch === "number");\n      }\n      function isPathValue(value) {\n        return value && typeof value === "object" && value.constructor && value.constructor.name === "Path" && (typeof value.to_String === "function" || typeof value.value === "string");\n      }\n      function timeClass() {\n        return require_time().Time;\n      }\n      function pathClass() {\n        if (runtimePolicy2.host_name === "browser") {\n          throw new Error("UnmarshallingException: Path requires std/io");\n        }\n        const dynamicRequire = __require;\n        return dynamicRequire("../io").Path;\n      }\n      function marshalBindingName(rawName, id) {\n        const name2 = String(rawName || "");\n        if (/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name2)) {\n          return name2;\n        }\n        return `__zuzu_marshal_class_${id}`;\n      }\n      function marshalClassSource(klass, bindingName) {\n        const fields = classFields(klass).map(sourceField).join("\\n");\n        return fields ? `class ${bindingName} {\n${fields}\n}` : `class ${bindingName} {}`;\n      }\n      function classFields(klass) {\n        const spec = klass.__zuzu_class_spec || {};\n        return Array.isArray(spec.fields) ? spec.fields : [];\n      }\n      function sourceField(field) {\n        const kind = field.kind === "const" ? "const" : "let";\n        const typeName3 = field.typeName ? `${field.typeName} ` : "";\n        const accessors = Array.isArray(field.accessors) && field.accessors.length > 0 ? ` with ${field.accessors.join(", ")}` : "";\n        return `	${kind} ${typeName3}${field.name}${accessors};`;\n      }\n      function registerCodeValue(kind, bindingName, source, value) {\n        codeRegistry.set(codeRegistryKey(kind, bindingName, source), value);\n        if (kind === CODE_CLASS) {\n          classRegistry.set(classRegistryKey(bindingName, source), value);\n        }\n      }\n      function classRegistryKey(bindingName, source) {\n        return `${bindingName}\\0${source}`;\n      }\n      function codeRegistryKey(kind, bindingName, source) {\n        return `${kind}\\0${bindingName}\\0${source}`;\n      }\n      function buildFunctionFromSource(bindingName, source, env = {}) {\n        const names = Object.keys(env);\n        const values = names.map((name2) => env[name2]);\n        let fn2;\n        if (["node", "browser", "electron"].includes(runtimePolicy2.host_name)) {\n          try {\n            fn2 = buildFunctionWithRuntime(bindingName, source, env);\n          } catch (runtimeErr) {\n            try {\n              fn2 = Function(...names, `return ( ${source} );`)(...values);\n            } catch (rawErr) {\n              fn2 = unloadedFunction(bindingName, runtimeErr, rawErr);\n            }\n          }\n        } else {\n          try {\n            fn2 = Function(...names, `return ( ${source} );`)(...values);\n          } catch (rawErr) {\n            fn2 = unloadedFunction(bindingName, rawErr);\n          }\n        }\n        Object.defineProperty(fn2, "__zuzu_marshal_meta", {\n          value: {\n            kind: "function",\n            name: bindingName,\n            source,\n            captures: env\n          },\n          enumerable: false,\n          configurable: true,\n          writable: true\n        });\n        return fn2;\n      }\n      function unloadedFunction(bindingName, ...errors) {\n        return function __zuzu_loaded_function() {\n          const err = errors.find((item) => item && item.message);\n          const message = err ? err.message : `Loaded function \'${bindingName}\' is not executable in JS`;\n          throw new Error(message);\n        };\n      }\n      function buildFunctionWithRuntime(bindingName, source, env = {}) {\n        if (runtimePolicy2.host_name && !["node", "browser", "electron"].includes(runtimePolicy2.host_name)) {\n          throw new Error(`Loaded function \'${bindingName}\' is not executable in JS`);\n        }\n        const denyCapabilities = [];\n        for (const capability of [\n          "fs",\n          "net",\n          "perl",\n          "js",\n          "proc",\n          "db",\n          "clib",\n          "gui",\n          "worker"\n        ]) {\n          if (runtimePolicy2[`deny_${capability}`]) {\n            denyCapabilities.push(capability);\n          }\n        }\n        const runtimeOptions = {\n          repoRoot: runtimePolicy2.repo_root || void 0,\n          includePaths: runtimePolicy2.include_paths || [],\n          denyCapabilities,\n          denyModules: runtimePolicy2.deny_modules || [],\n          debugLevel: runtimePolicy2.debug_level || 0,\n          transpiler: runtimePolicy2.transpiler || void 0\n        };\n        let runtime;\n        if (runtimePolicy2.host_name === "browser") {\n          const { createBrowserRuntime } = require_browser_runtime();\n          const defaults = typeof globalThis !== "undefined" && globalThis.__ZUZU_BROWSER_DEFAULT_RUNTIME_OPTIONS__ && typeof globalThis.__ZUZU_BROWSER_DEFAULT_RUNTIME_OPTIONS__ === "object" ? globalThis.__ZUZU_BROWSER_DEFAULT_RUNTIME_OPTIONS__ : {};\n          runtime = createBrowserRuntime({\n            ...defaults,\n            ...runtimeOptions\n          }).runtime;\n        } else {\n          const entrypointsModule = "../../../lib/runtime-entrypoints";\n          const { createNodeRuntime } = __require(entrypointsModule);\n          runtime = createNodeRuntime(runtimeOptions);\n        }\n        const js = runtime.transpile(\n          `let __zuzu_marshal_value := ${source};\n__global__{__zuzu_marshal_result} := __zuzu_marshal_value;`\n        );\n        const context = runtime.buildContext({\n          filename: "<std/marshal-code>",\n          globals: env\n        });\n        context.__global__ = /* @__PURE__ */ Object.create(null);\n        runtime.installCollectionMethods(context);\n        runtime.host.runInContext(\n          js,\n          context,\n          { filename: "<std/marshal-code>" }\n        );\n        const fn2 = context.__global__.__zuzu_marshal_result;\n        if (typeof fn2 !== "function") {\n          throw new Error(`Loaded function \'${bindingName}\' is not executable in JS`);\n        }\n        return fn2;\n      }\n      function buildClassFromSource(bindingName, source, env = {}) {\n        const spec = parseClassSource(source, env);\n        return buildMarshalClass(\n          bindingName,\n          spec.baseName ? env[spec.baseName] : null,\n          spec.fields,\n          spec.methods,\n          spec.statics,\n          spec.traitNames.map((name2) => env[name2]).filter(isTraitValue),\n          env,\n          source\n        );\n      }\n      function buildTraitFromSource(bindingName, source, env = {}) {\n        const trait = {\n          __zuzu_trait_name: bindingName,\n          __zuzu_trait_methods: parseMethods(source, env).methods\n        };\n        Object.defineProperty(trait, "__zuzu_marshal_meta", {\n          value: {\n            kind: "trait",\n            name: bindingName,\n            source,\n            captures: env\n          },\n          enumerable: false,\n          configurable: true,\n          writable: true\n        });\n        return trait;\n      }\n      function parseClassSource(source, env = {}) {\n        return {\n          baseName: parseClassBaseName(source),\n          fields: parseClassFields(source),\n          traitNames: parseClassTraitNames(source),\n          ...parseMethods(source, env)\n        };\n      }\n      function parseClassBaseName(source) {\n        const match = String(source || "").match(\n          /\\bclass\\s+[A-Za-z_][A-Za-z0-9_]*\\s+extends\\s+([A-Za-z_][A-Za-z0-9_]*)/u\n        );\n        return match ? match[1] : null;\n      }\n      function parseClassFields(source) {\n        const body = String(source || "").replace(/\\/\\*[\\s\\S]*?\\*\\//gu, "");\n        const fields = [];\n        const byName = /* @__PURE__ */ new Map();\n        const rx = /\\b(let|const)\\s+(?:(Null|Any|Boolean|Number|String|BinaryString|Array|Dict|PairList|Set|Bag|Pair|Time|Path|Object)\\s+)?([A-Za-z_][A-Za-z0-9_]*)(?:\\s+with\\s+([^;:=]+?))?\\s*(?::=\\s*([^;]*))?;/gu;\n        let match = rx.exec(body);\n        while (match) {\n          const field = {\n            kind: match[1],\n            typeName: match[2] || null,\n            name: match[3],\n            accessors: match[4] ? match[4].split(",").map((item) => item.trim()).filter(Boolean) : [],\n            defaultSource: match[5] ? match[5].trim() : null\n          };\n          fields.push(field);\n          byName.set(field.name, field);\n          match = rx.exec(body);\n        }\n        const methodRx = /\\bmethod\\s+(get|set|clear|has)_([A-Za-z_][A-Za-z0-9_]*)\\s*\\(([^)]*)\\)/gu;\n        let methodMatch = methodRx.exec(body);\n        while (methodMatch) {\n          const field = byName.get(methodMatch[2]);\n          if (field && !field.accessors.includes(methodMatch[1])) {\n            field.accessors.push(methodMatch[1]);\n          }\n          if (field && methodMatch[1] === "set" && !field.typeName) {\n            const typeMatch = methodMatch[3].match(/\\b(Null|Any|Boolean|Number|String|BinaryString|Array|Dict|PairList|Set|Bag|Pair|Time|Path|Object)\\s+[A-Za-z_][A-Za-z0-9_]*\\b/u);\n            if (typeMatch) {\n              field.typeName = typeMatch[1];\n            }\n          }\n          methodMatch = methodRx.exec(body);\n        }\n        return fields;\n      }\n      function parseClassTraitNames(source) {\n        const match = String(source || "").match(\n          /\\bclass\\s+[A-Za-z_][A-Za-z0-9_]*(?:\\s+extends\\s+[A-Za-z_][A-Za-z0-9_]*)?\\s+(?:with|but)\\s+([^{;]+)/u\n        );\n        if (!match) {\n          return [];\n        }\n        return match[1].split(",").map((item) => item.trim()).filter((item) => /^[A-Za-z_][A-Za-z0-9_]*$/u.test(item));\n      }\n      function parseMethods(source, env = {}) {\n        const text = String(source || "").replace(/\\/\\*[\\s\\S]*?\\*\\//gu, "");\n        const methods = {};\n        const statics = {};\n        const rx = /\\b(static\\s+)?method\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*\\(([^)]*)\\)\\s*(?:->\\s*[A-Za-z_][A-Za-z0-9_]*)?\\s*\\{([\\s\\S]*?)\\}/gu;\n        let match = rx.exec(text);\n        while (match) {\n          const target = match[1] ? statics : methods;\n          target[match[2]] = compileSimpleMethod(\n            match[2],\n            parseParamNames(match[3]),\n            match[4],\n            env\n          );\n          match = rx.exec(text);\n        }\n        return { methods, statics };\n      }\n      function parseParamNames(source) {\n        return String(source || "").split(",").map((item) => item.trim()).filter(Boolean).map((item) => {\n          const match = item.match(/([A-Za-z_][A-Za-z0-9_]*)$/u);\n          return match ? match[1] : null;\n        }).filter(Boolean);\n      }\n      function compileSimpleMethod(name2, paramNames, body, env) {\n        const match = String(body || "").match(/\\breturn\\s+([\\s\\S]*?)\\s*;/u);\n        if (!match) {\n          return function _loaded_method() {\n            return null;\n          };\n        }\n        const expression = match[1];\n        return {\n          [name2]: function _loaded_method(...args) {\n            const params = /* @__PURE__ */ Object.create(null);\n            for (let i = 0; i < paramNames.length; i++) {\n              params[paramNames[i]] = args[i];\n            }\n            return evalSimpleExpression(expression, this, env, params);\n          }\n        }[name2];\n      }\n      function evalSimpleExpression(source, self, env = {}, params = {}) {\n        const expression = normalizeSimpleExpression(source);\n        const envNames = Object.keys(env);\n        const paramNames = Object.keys(params);\n        const fn2 = Function(\n          "self",\n          ...envNames,\n          ...paramNames,\n          `with ( self ) { return ( ${expression} ); }`\n        );\n        return fn2(\n          self || {},\n          ...envNames.map((name2) => env[name2]),\n          ...paramNames.map((name2) => params[name2])\n        );\n      }\n      function normalizeSimpleExpression(source) {\n        return String(source || "null").replace(/\\s+_\\s+/gu, " + ");\n      }\n      function buildMarshalClass(name2, base = null, fields, methods = {}, statics = {}, traits = [], env = {}, source = "") {\n        const parent = typeof base === "function" ? base : Object;\n        const ctor = {\n          [name2]: class extends parent {\n            constructor(initial = {}) {\n              super(initial);\n              for (const field of fields) {\n                let value = field.defaultSource ? evalSimpleExpression(field.defaultSource, this, env) : null;\n                if (isPairListLike(initial)) {\n                  value = initial.get(field.name, value);\n                } else if (initial && typeof initial === "object" && Object.prototype.hasOwnProperty.call(initial, field.name)) {\n                  value = initial[field.name];\n                }\n                this[field.name] = value;\n              }\n            }\n          }\n        }[name2];\n        for (const field of fields) {\n          if (!Array.isArray(field.accessors)) {\n            continue;\n          }\n          if (field.accessors.includes("get")) {\n            ctor.prototype[`get_${field.name}`] = function _get_field() {\n              return this[field.name];\n            };\n          }\n          if (field.accessors.includes("set")) {\n            ctor.prototype[`set_${field.name}`] = function _set_field(value) {\n              if (field.typeName && value != null && !typeMatches(value, field.typeName)) {\n                throw new Error(\n                  `TypeException: field \'${field.name}\' must be ${field.typeName}, got ${typeName2(value)}`\n                );\n              }\n              this[field.name] = value;\n              return this;\n            };\n          }\n        }\n        for (const trait of traits) {\n          for (const [methodName, fn2] of Object.entries(trait.__zuzu_trait_methods)) {\n            if (typeof fn2 === "function" && typeof ctor.prototype[methodName] !== "function") {\n              ctor.prototype[methodName] = fn2;\n            }\n          }\n        }\n        const generatedAccessors = /* @__PURE__ */ new Set();\n        for (const field of fields) {\n          for (const accessor of field.accessors || []) {\n            generatedAccessors.add(`${accessor}_${field.name}`);\n          }\n        }\n        for (const [methodName, fn2] of Object.entries(methods)) {\n          if (generatedAccessors.has(methodName)) {\n            continue;\n          }\n          ctor.prototype[methodName] = fn2;\n        }\n        for (const [methodName, fn2] of Object.entries(statics)) {\n          ctor[methodName] = fn2;\n        }\n        Object.defineProperty(ctor, "__zuzu_class_name", {\n          value: name2,\n          enumerable: false,\n          configurable: true,\n          writable: true\n        });\n        Object.defineProperty(ctor, "__zuzu_class_spec", {\n          value: { fields, traits, methods, statics, nested: {} },\n          enumerable: false,\n          configurable: true,\n          writable: true\n        });\n        Object.defineProperty(ctor, "__zuzu_marshal_meta", {\n          value: {\n            kind: "class",\n            name: name2,\n            source,\n            captures: env\n          },\n          enumerable: false,\n          configurable: true,\n          writable: true\n        });\n        return ctor;\n      }\n      function typeMatches(value, expected) {\n        if (expected === "Any" || expected == null) {\n          return true;\n        }\n        if (expected === "Null") {\n          return value == null;\n        }\n        if (expected === "Boolean") {\n          return typeof value === "boolean";\n        }\n        if (expected === "Number") {\n          return typeof value === "number";\n        }\n        if (expected === "String") {\n          return typeof value === "string";\n        }\n        if (expected === "BinaryString") {\n          return value instanceof BinaryString2;\n        }\n        if (expected === "Array") {\n          return Array.isArray(value);\n        }\n        if (expected === "Dict") {\n          return isPlainDict(value);\n        }\n        if (expected === "PairList") {\n          return isPairListLike(value);\n        }\n        if (expected === "Set") {\n          return value instanceof Set;\n        }\n        if (expected === "Bag") {\n          return value instanceof ZuzuBag;\n        }\n        if (expected === "Pair") {\n          return value instanceof Pair;\n        }\n        if (expected === "Time") {\n          return isTimeValue(value);\n        }\n        if (expected === "Path") {\n          return isPathValue(value);\n        }\n        return true;\n      }\n      function typeName2(value) {\n        if (value == null) {\n          return "Null";\n        }\n        if (value instanceof BinaryString2) {\n          return "BinaryString";\n        }\n        if (typeof value === "boolean") {\n          return "Boolean";\n        }\n        if (typeof value === "number") {\n          return "Number";\n        }\n        if (typeof value === "string") {\n          return "String";\n        }\n        if (Array.isArray(value)) {\n          return "Array";\n        }\n        if (value && value.constructor && value.constructor.name) {\n          return value.constructor.name;\n        }\n        return typeof value;\n      }\n      module2.exports = {\n        dumpGraph,\n        loadGraph,\n        safeToDumpGraph,\n        setRuntimePolicy: setRuntimePolicy2\n      };\n    }\n  });\n\n  // modules/std/marshal.js\n  var require_marshal = __commonJS({\n    "modules/std/marshal.js"(exports2, module2) {\n      "use strict";\n      var cbor = require_cbor();\n      var {\n        dumpGraph,\n        loadGraph,\n        safeToDumpGraph,\n        setRuntimePolicy: setRuntimePolicy2\n      } = require_graph();\n      var MarshallingException = class extends Error {\n        constructor(message = "std/marshal.dump failed") {\n          super(String(message));\n          this.name = "MarshallingException";\n        }\n        to_String() {\n          return `${this.name}: ${this.message}`;\n        }\n      };\n      var UnmarshallingException = class extends Error {\n        constructor(message = "std/marshal.load failed") {\n          super(String(message));\n          this.name = "UnmarshallingException";\n        }\n        to_String() {\n          return `${this.name}: ${this.message}`;\n        }\n      };\n      function dump(value) {\n        assertArity("dump", arguments.length, 1);\n        try {\n          return dumpGraph(value);\n        } catch (err) {\n          throw new MarshallingException(\n            `std/marshal.dump failed: ${err.message || err}`\n          );\n        }\n      }\n      function load(blob) {\n        assertArity("load", arguments.length, 1);\n        try {\n          return loadGraph(blob);\n        } catch (err) {\n          if (String(err && err.message || err).startsWith("TypeException:")) {\n            throw err;\n          }\n          throw new UnmarshallingException(\n            `std/marshal.load failed: ${err.message || err}`\n          );\n        }\n      }\n      function safe_to_dump(value) {\n        assertArity("safe_to_dump", arguments.length, 1);\n        return safeToDumpGraph(value);\n      }\n      function assertArity(name2, got, expected) {\n        if (got !== expected) {\n          throw new Error(\n            `TypeException: ${name2} expects ${expected} argument, got ${got}`\n          );\n        }\n      }\n      module2.exports = {\n        dump,\n        load,\n        safe_to_dump,\n        MarshallingException,\n        UnmarshallingException,\n        __zuzu_set_runtime_policy: setRuntimePolicy2\n      };\n      Object.defineProperty(module2.exports, "__cbor", {\n        value: cbor,\n        enumerable: false,\n        configurable: false,\n        writable: false\n      });\n    }\n  });\n\n  // modules/std/worker.js\n  var require_worker = __commonJS({\n    "modules/std/worker.js"(exports2, module2) {\n      "use strict";\n      var { BinaryString: BinaryString2, PairList } = require_runtime_helpers();\n      var taskRuntime2 = require_task();\n      var { CancelledException, ChannelClosedException, Task } = taskRuntime2;\n      var marshal = require_marshal();\n      var DENIAL_CAPABILITIES = [\n        "fs",\n        "net",\n        "perl",\n        "js",\n        "proc",\n        "db",\n        "clib",\n        "gui",\n        "worker"\n      ];\n      var runtimePolicy2 = {\n        host_name: "node",\n        repo_root: null,\n        include_paths: [],\n        deny_modules: [],\n        debug_level: 0,\n        transpiler: null,\n        browser_worker_source: null,\n        browser_worker_url: null,\n        browser_worker_factory: null\n      };\n      function setRuntimePolicy2(policy = {}) {\n        runtimePolicy2 = {\n          ...runtimePolicy2,\n          ...policy,\n          include_paths: Array.isArray(policy.include_paths) ? policy.include_paths.slice() : runtimePolicy2.include_paths,\n          deny_modules: Array.isArray(policy.deny_modules) ? policy.deny_modules.slice() : runtimePolicy2.deny_modules\n        };\n        marshal.__zuzu_set_runtime_policy(runtimePolicy2);\n      }\n      function loadWorkerThreads() {\n        if (runtimePolicy2.host_name === "browser") {\n          return null;\n        }\n        try {\n          return __require("node:worker_threads");\n        } catch (_err) {\n          return null;\n        }\n      }\n      function loadNodePath() {\n        try {\n          return __require("node:path");\n        } catch (_err) {\n          return null;\n        }\n      }\n      function browserRoot() {\n        return typeof globalThis !== "undefined" ? globalThis : null;\n      }\n      function browserWorkerSource() {\n        const root = browserRoot();\n        return runtimePolicy2.browser_worker_source || root && root.__ZUZU_BROWSER_WORKER_SOURCE__ || null;\n      }\n      function browserWorkerUrl() {\n        const root = browserRoot();\n        return runtimePolicy2.browser_worker_url || root && root.__ZUZU_BROWSER_WORKER_URL__ || null;\n      }\n      function loadBrowserWorkerFactory() {\n        if (runtimePolicy2.host_name !== "browser") {\n          return null;\n        }\n        if (typeof runtimePolicy2.browser_worker_factory === "function") {\n          return runtimePolicy2.browser_worker_factory;\n        }\n        const root = browserRoot();\n        if (root && typeof root.__ZUZU_BROWSER_WORKER_FACTORY__ === "function") {\n          return root.__ZUZU_BROWSER_WORKER_FACTORY__;\n        }\n        return null;\n      }\n      function assertWorkerCapability(label) {\n        if (runtimePolicy2.deny_worker) {\n          throw new Error(`${label} is denied by runtime policy`);\n        }\n      }\n      function createBrowserWorker() {\n        const factory = loadBrowserWorkerFactory();\n        const source = browserWorkerSource();\n        const url = browserWorkerUrl();\n        if (factory) {\n          return factory({\n            source,\n            url,\n            name: "zuzu-browser-worker"\n          });\n        }\n        const root = browserRoot();\n        if (!root || typeof root.Worker !== "function") {\n          return null;\n        }\n        if (url) {\n          return new root.Worker(url);\n        }\n        if (source && typeof root.Blob === "function" && root.URL && typeof root.URL.createObjectURL === "function") {\n          const blob = new root.Blob([source], { type: "text/javascript" });\n          const objectUrl = root.URL.createObjectURL(blob);\n          return new root.Worker(objectUrl);\n        }\n        return null;\n      }\n      function isPairList(value) {\n        return value instanceof PairList || value && typeof value === "object" && Array.isArray(value.list) && typeof value.has === "function" && typeof value.get === "function";\n      }\n      function typeName2(value) {\n        if (value == null) {\n          return "Null";\n        }\n        if (isPairList(value)) {\n          return "PairList";\n        }\n        if (Array.isArray(value)) {\n          return "Array";\n        }\n        if (typeof value === "function") {\n          return "Function";\n        }\n        if (typeof value === "boolean") {\n          return "Boolean";\n        }\n        if (typeof value === "number") {\n          return "Number";\n        }\n        if (typeof value === "string") {\n          return "String";\n        }\n        if (value && value.__zuzu_type_name) {\n          return String(value.__zuzu_type_name);\n        }\n        if (value && value.constructor && value.constructor.name) {\n          return value.constructor.name;\n        }\n        return "Object";\n      }\n      function namedOptionMap(namedArgs) {\n        const out = /* @__PURE__ */ Object.create(null);\n        if (!namedArgs) {\n          return out;\n        }\n        for (const pair of namedArgs.list || []) {\n          if (Array.isArray(pair) && pair.length >= 2) {\n            out[String(pair[0])] = pair[1];\n          }\n        }\n        return out;\n      }\n      function parseWorkerOptions(namedArgs) {\n        const named = namedOptionMap(namedArgs);\n        const extraDenials = [];\n        const refusedRelaxations = [];\n        for (const key of Object.keys(named).sort()) {\n          if (!key.startsWith("deny_")) {\n            throw new Error(`Unknown named argument \'${key}\' for Worker.spawn`);\n          }\n          const capability = key.slice("deny_".length);\n          if (!DENIAL_CAPABILITIES.includes(capability)) {\n            throw new Error(`Unknown named argument \'${key}\' for Worker.spawn`);\n          }\n          if (typeof named[key] !== "boolean") {\n            throw new Error(\n              `TypeException: Worker.spawn named argument \'${key}\' expects Boolean, got ${typeName2(named[key])}`\n            );\n          }\n          if (named[key]) {\n            extraDenials.push(capability);\n          } else if (runtimePolicy2[key]) {\n            refusedRelaxations.push(capability);\n          }\n        }\n        return { extraDenials, refusedRelaxations };\n      }\n      function effectivePolicy(extraDenials) {\n        const policy = {\n          host_name: runtimePolicy2.host_name,\n          repo_root: runtimePolicy2.repo_root,\n          include_paths: (runtimePolicy2.include_paths || []).slice(),\n          deny_modules: (runtimePolicy2.deny_modules || []).slice(),\n          debug_level: runtimePolicy2.debug_level,\n          transpiler: runtimePolicy2.transpiler\n        };\n        for (const capability of DENIAL_CAPABILITIES) {\n          policy[`deny_${capability}`] = Boolean(runtimePolicy2[`deny_${capability}`]) || extraDenials.includes(capability);\n        }\n        return policy;\n      }\n      function taskException(message) {\n        const err = new Error(String(message || "worker failed"));\n        err.name = "Exception";\n        err.to_String = function toString() {\n          return `Exception: ${this.message}`;\n        };\n        return err;\n      }\n      var Worker = class {\n        static spawn(...rawArgs) {\n          assertWorkerCapability("Worker.spawn");\n          let namedArgs = null;\n          if (rawArgs.length > 0 && isPairList(rawArgs[rawArgs.length - 1])) {\n            namedArgs = rawArgs.pop();\n          }\n          if (rawArgs.length < 1 || rawArgs.length > 2) {\n            throw new Error("Worker.spawn expects Callable and optional Array arguments");\n          }\n          const callable = rawArgs[0];\n          if (typeof callable !== "function") {\n            throw new Error(\n              `TypeException: Worker.spawn expects Function, got ${typeName2(callable)}`\n            );\n          }\n          const workerArgs = rawArgs.length > 1 ? rawArgs[1] : [];\n          if (!Array.isArray(workerArgs)) {\n            throw new Error(\n              `TypeException: Worker.spawn expects Array arguments, got ${typeName2(workerArgs)}`\n            );\n          }\n          const threads = loadWorkerThreads();\n          const browserMode = runtimePolicy2.host_name === "browser";\n          if (!threads && !browserMode) {\n            throw new Error("std/worker transport is unavailable");\n          }\n          const { extraDenials, refusedRelaxations } = parseWorkerOptions(namedArgs);\n          if (refusedRelaxations.length > 0) {\n            return Task.failed(taskException(\n              `Denied capability \'${refusedRelaxations[0]}\' cannot be relaxed for worker`\n            ));\n          }\n          let requestBytes;\n          try {\n            requestBytes = marshal.dump([callable, workerArgs]);\n          } catch (err) {\n            throw err;\n          }\n          if (browserMode) {\n            return spawnBrowserWorker(requestBytes, extraDenials);\n          }\n          return spawnNodeWorker(threads, requestBytes, extraDenials);\n        }\n        static spawn_handle(...rawArgs) {\n          assertWorkerCapability("Worker.spawn_handle");\n          let namedArgs = null;\n          if (rawArgs.length > 0 && isPairList(rawArgs[rawArgs.length - 1])) {\n            namedArgs = rawArgs.pop();\n          }\n          if (rawArgs.length < 1 || rawArgs.length > 2) {\n            throw new Error(\n              "Worker.spawn_handle expects Callable and optional Array arguments"\n            );\n          }\n          const callable = rawArgs[0];\n          if (typeof callable !== "function") {\n            throw new Error(\n              `TypeException: Worker.spawn_handle expects Function, got ${typeName2(callable)}`\n            );\n          }\n          const workerArgs = rawArgs.length > 1 ? rawArgs[1] : [];\n          if (!Array.isArray(workerArgs)) {\n            throw new Error(\n              `TypeException: Worker.spawn_handle expects Array arguments, got ${typeName2(workerArgs)}`\n            );\n          }\n          const threads = loadWorkerThreads();\n          const browserMode = runtimePolicy2.host_name === "browser";\n          if (!threads && !browserMode) {\n            throw new Error("std/worker transport is unavailable");\n          }\n          const { extraDenials, refusedRelaxations } = parseWorkerOptions(namedArgs);\n          if (refusedRelaxations.length > 0) {\n            const task = Task.failed(taskException(\n              `Denied capability \'${refusedRelaxations[0]}\' cannot be relaxed for worker`\n            ));\n            return new WorkerHandle(null, {\n              resultTask: task,\n              remoteClosed: true\n            });\n          }\n          const requestBytes = marshal.dump([callable, workerArgs]);\n          if (browserMode) {\n            return spawnBrowserWorkerHandle(requestBytes, extraDenials);\n          }\n          return spawnNodeWorkerHandle(threads, requestBytes, extraDenials);\n        }\n      };\n      var WorkerHandle = class {\n        constructor(transport, options = {}) {\n          this._transport = transport;\n          this._queue = [];\n          this._receivers = [];\n          this._localClosed = false;\n          this._remoteClosed = Boolean(options.remoteClosed);\n          this._cancelled = false;\n          this._remoteError = null;\n          this._nextOutgoingSeq = 1;\n          this._nextIncomingSeq = 1;\n          this._incomingFrames = /* @__PURE__ */ new Map();\n          this._resultTask = options.resultTask || new Task(null, {\n            status: "running",\n            name: "WorkerHandle.result",\n            cancel: (reason) => this.cancel(reason)\n          });\n        }\n        send(value = null) {\n          if (this._localClosed || this._remoteClosed || this._cancelled) {\n            return Task.failed(\n              new ChannelClosedException("send on closed worker handle")\n            );\n          }\n          let bytes;\n          try {\n            bytes = marshal.dump(value);\n          } catch (err) {\n            return Task.failed(err);\n          }\n          try {\n            this._post({\n              type: "message",\n              bytes: Array.from(bytes.bytes)\n            });\n          } catch (err) {\n            this._closeRemote(err);\n            return Task.failed(err);\n          }\n          return Task.resolved(value);\n        }\n        recv() {\n          if (this._queue.length > 0) {\n            return Task.resolved(this._queue.shift());\n          }\n          if (this._cancelled) {\n            return Task.failed(new CancelledException("worker cancelled"));\n          }\n          if (this._remoteClosed) {\n            return Task.failed(\n              new ChannelClosedException("worker handle closed")\n            );\n          }\n          const task = new Task(null, {\n            status: "waiting",\n            name: "WorkerHandle.recv",\n            cancel: () => {\n              this._receivers = this._receivers.filter((item) => item !== task);\n            }\n          });\n          this._receivers.push(task);\n          return task;\n        }\n        close() {\n          if (this._localClosed) {\n            return Task.resolved(null);\n          }\n          this._localClosed = true;\n          try {\n            this._post({ type: "close" });\n          } catch (_err) {\n          }\n          return Task.resolved(null);\n        }\n        cancel(reason = null) {\n          if (this._cancelled) {\n            return this;\n          }\n          this._cancelled = true;\n          this._localClosed = true;\n          this._remoteClosed = true;\n          const err = reason instanceof Error ? reason : new CancelledException(reason == null ? "worker cancelled" : reason);\n          this._rejectReceivers(err, true);\n          try {\n            this._post({\n              type: "cancel",\n              reason: err.message || String(err)\n            });\n          } catch (_err) {\n          }\n          if (this._transport && typeof this._transport.terminate === "function") {\n            this._transport.terminate();\n          }\n          if (!this._resultTask.done()) {\n            this._resultTask.cancel(err);\n          }\n          return this;\n        }\n        result() {\n          return this._resultTask;\n        }\n        status() {\n          return this._resultTask.status();\n        }\n        done() {\n          return this._resultTask.done();\n        }\n        _post(message) {\n          if (!this._transport || typeof this._transport.postMessage !== "function") {\n            throw taskException("worker transport is closed");\n          }\n          const payload = { ...message };\n          if (["message", "close", "cancel"].includes(payload.type) && !Number.isInteger(payload.seq)) {\n            payload.seq = this._nextOutgoingSeq++;\n          }\n          this._transport.postMessage(payload);\n        }\n        _deliverBytes(bytes) {\n          let value;\n          try {\n            value = marshal.load(new BinaryString2(bytes || []));\n          } catch (err) {\n            this._closeRemote(err);\n            return;\n          }\n          const receiver = this._receivers.shift();\n          if (receiver) {\n            receiver._resolve(value);\n          } else {\n            this._queue.push(value);\n          }\n        }\n        _resolveResultBytes(bytes) {\n          try {\n            this._resultTask._resolve(\n              marshal.load(new BinaryString2(bytes || []))\n            );\n          } catch (err) {\n            this._resultTask._reject(err);\n          }\n        }\n        _rejectResult(err) {\n          if (!this._resultTask.done()) {\n            this._resultTask._reject(err);\n          }\n        }\n        _closeRemote(err = null) {\n          this._remoteClosed = true;\n          if (err) {\n            this._remoteError = err;\n          }\n          this._rejectReceivers(\n            err || this._remoteError || new ChannelClosedException("worker handle closed"),\n            false\n          );\n        }\n        _rejectReceivers(err, forceCancel = false) {\n          while (this._receivers.length > 0) {\n            this._receivers.shift()._reject(\n              err,\n              forceCancel ? "cancelled" : null\n            );\n          }\n        }\n        _receiveFrame(message) {\n          if (Number.isInteger(message.seq)) {\n            this._incomingFrames.set(message.seq, message);\n            while (this._incomingFrames.has(this._nextIncomingSeq)) {\n              const next = this._incomingFrames.get(this._nextIncomingSeq);\n              this._incomingFrames.delete(this._nextIncomingSeq);\n              this._nextIncomingSeq++;\n              processWorkerHandleMessage(this, next);\n            }\n            return;\n          }\n          processWorkerHandleMessage(this, message);\n        }\n      };\n      Object.defineProperty(WorkerHandle.prototype, "__zuzu_type_name", {\n        value: "WorkerHandle",\n        enumerable: false,\n        configurable: true,\n        writable: true\n      });\n      function spawnNodeWorker(threads, requestBytes, extraDenials) {\n        const nodePath = loadNodePath();\n        if (!threads || !nodePath) {\n          throw new Error("std/worker transport is unavailable");\n        }\n        const task = new Task(null, {\n          status: "running",\n          name: "Worker.spawn"\n        });\n        const nodeWorker = new threads.Worker(\n          nodePath.join(__dirname, "worker-thread.js"),\n          {\n            workerData: {\n              request_bytes: Array.from(requestBytes.bytes),\n              policy: effectivePolicy(extraDenials)\n            }\n          }\n        );\n        task._cancelHook = function cancelWorker() {\n          nodeWorker.terminate().catch(() => {\n          });\n        };\n        let settled = false;\n        nodeWorker.once("message", (message) => {\n          settled = true;\n          handleWorkerMessage(task, message);\n        });\n        nodeWorker.once("error", (err) => {\n          settled = true;\n          if (!task.done()) {\n            task._reject(taskException(err && err.message ? err.message : err));\n          }\n        });\n        nodeWorker.once("exit", (code) => {\n          if (!settled && !task.done() && code !== 0) {\n            task._reject(taskException(`Worker exited with code ${code}`));\n          }\n        });\n        return task;\n      }\n      function spawnBrowserWorker(requestBytes, extraDenials) {\n        const browserWorker = createBrowserWorker();\n        if (!browserWorker) {\n          throw new Error("std/worker transport is unavailable");\n        }\n        const task = new Task(null, {\n          status: "running",\n          name: "Worker.spawn"\n        });\n        task._cancelHook = function cancelWorker() {\n          if (browserWorker && typeof browserWorker.terminate === "function") {\n            browserWorker.terminate();\n          }\n        };\n        const onMessage = (event) => handleWorkerMessage(\n          task,\n          event && Object.prototype.hasOwnProperty.call(event, "data") ? event.data : event\n        );\n        const onError = (err) => {\n          const root = browserRoot();\n          const reject = () => {\n            if (!task.done()) {\n              task._reject(taskException(err && err.message ? err.message : err));\n            }\n          };\n          if (root && typeof root.setTimeout === "function") {\n            root.setTimeout(reject, 25);\n            return;\n          }\n          reject();\n        };\n        if (typeof browserWorker.addEventListener === "function") {\n          browserWorker.addEventListener("message", onMessage);\n          browserWorker.addEventListener("error", onError);\n        } else {\n          browserWorker.onmessage = onMessage;\n          browserWorker.onerror = onError;\n        }\n        browserWorker.postMessage({\n          request_bytes: Array.from(requestBytes.bytes),\n          policy: effectivePolicy(extraDenials)\n        });\n        return task;\n      }\n      function spawnNodeWorkerHandle(threads, requestBytes, extraDenials) {\n        const nodePath = loadNodePath();\n        if (!threads || !nodePath) {\n          throw new Error("std/worker transport is unavailable");\n        }\n        const nodeWorker = new threads.Worker(\n          nodePath.join(__dirname, "worker-thread.js"),\n          {\n            workerData: {\n              mode: "handle",\n              request_bytes: Array.from(requestBytes.bytes),\n              policy: effectivePolicy(extraDenials)\n            }\n          }\n        );\n        const handle = new WorkerHandle({\n          postMessage: (message) => nodeWorker.postMessage(message),\n          terminate: () => nodeWorker.terminate().catch(() => {\n          })\n        });\n        let settled = false;\n        nodeWorker.on("message", (message) => handleWorkerHandleMessage(handle, message));\n        nodeWorker.once("error", (err) => {\n          settled = true;\n          const wrapped = taskException(err && err.message ? err.message : err);\n          handle._closeRemote(wrapped);\n          handle._rejectResult(wrapped);\n        });\n        nodeWorker.once("exit", (code) => {\n          if (settled) {\n            return;\n          }\n          if (code !== 0 && !handle._cancelled) {\n            const err = taskException(`Worker exited with code ${code}`);\n            handle._closeRemote(err);\n            handle._rejectResult(err);\n            return;\n          }\n          handle._closeRemote();\n          if (!handle._resultTask.done() && !handle._cancelled) {\n            handle._rejectResult(taskException("Worker exited without result"));\n          }\n        });\n        return handle;\n      }\n      function spawnBrowserWorkerHandle(requestBytes, extraDenials) {\n        const browserWorker = createBrowserWorker();\n        if (!browserWorker) {\n          throw new Error("std/worker transport is unavailable");\n        }\n        const handle = new WorkerHandle({\n          postMessage: (message) => browserWorker.postMessage(message),\n          terminate: () => {\n            if (typeof browserWorker.terminate === "function") {\n              browserWorker.terminate();\n            }\n          }\n        });\n        const onMessage = (event) => handleWorkerHandleMessage(\n          handle,\n          event && Object.prototype.hasOwnProperty.call(event, "data") ? event.data : event\n        );\n        const onError = (err) => {\n          const wrapped = taskException(err && err.message ? err.message : err);\n          handle._closeRemote(wrapped);\n          handle._rejectResult(wrapped);\n        };\n        if (typeof browserWorker.addEventListener === "function") {\n          browserWorker.addEventListener("message", onMessage);\n          browserWorker.addEventListener("error", onError);\n        } else {\n          browserWorker.onmessage = onMessage;\n          browserWorker.onerror = onError;\n        }\n        browserWorker.postMessage({\n          type: "start_handle",\n          request_bytes: Array.from(requestBytes.bytes),\n          policy: effectivePolicy(extraDenials)\n        });\n        return handle;\n      }\n      function handleWorkerMessage(task, message) {\n        if (task.done()) {\n          return;\n        }\n        if (!message || typeof message !== "object") {\n          task._reject(taskException("Worker returned invalid reply"));\n          return;\n        }\n        if (!message.ok) {\n          task._reject(taskException(message.error || "worker failed"));\n          return;\n        }\n        try {\n          task._resolve(marshal.load(new BinaryString2(message.bytes || [])));\n        } catch (err) {\n          task._reject(err);\n        }\n      }\n      function handleWorkerHandleMessage(handle, message) {\n        if (!message || typeof message !== "object") {\n          const err = taskException("Worker returned invalid reply");\n          handle._closeRemote(err);\n          handle._rejectResult(err);\n          return;\n        }\n        handle._receiveFrame(message);\n      }\n      function processWorkerHandleMessage(handle, message) {\n        if (message.type === "message") {\n          handle._deliverBytes(message.bytes || []);\n          return;\n        }\n        if (message.type === "close") {\n          handle._closeRemote();\n          return;\n        }\n        if (message.type === "result") {\n          if (message.ok) {\n            handle._resolveResultBytes(message.bytes || []);\n          } else {\n            const err2 = taskException(message.error || "worker failed");\n            handle._remoteError = err2;\n            handle._rejectResult(err2);\n          }\n          return;\n        }\n        const err = taskException("Worker returned invalid reply");\n        handle._closeRemote(err);\n        handle._rejectResult(err);\n      }\n      module2.exports = {\n        Worker,\n        __zuzu_set_runtime_policy: setRuntimePolicy2\n      };\n    }\n  });\n\n  // modules/std/digest/_hash.js\n  var require_hash = __commonJS({\n    "modules/std/digest/_hash.js"(exports2, module2) {\n      "use strict";\n      var { BinaryString: BinaryString2 } = require_runtime_helpers();\n      function valueType(value) {\n        if (value == null) {\n          return "Null";\n        }\n        if (typeof value === "string") {\n          return "String";\n        }\n        return value.constructor && value.constructor.name ? value.constructor.name : typeof value;\n      }\n      function assertBinary(value, fnName, label = "BinaryString") {\n        if (!value || !(value.bytes instanceof Uint8Array)) {\n          throw new Error(`TypeException: ${fnName} expects ${label}, got ${valueType(value)}`);\n        }\n      }\n      function toBinary(bytes) {\n        return new BinaryString2(Uint8Array.from(bytes));\n      }\n      function bytesToHex(bytes) {\n        return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");\n      }\n      function bytesToBase64(bytes) {\n        if (typeof Buffer !== "undefined") {\n          return Buffer.from(bytes).toString("base64").replace(/=+$/u, "");\n        }\n        let text = "";\n        for (let i = 0; i < bytes.length; i++) {\n          text += String.fromCharCode(bytes[i]);\n        }\n        return btoa(text).replace(/=+$/u, "");\n      }\n      function concatBytes2(...items) {\n        const total = items.reduce((sum, item) => sum + item.length, 0);\n        const out = new Uint8Array(total);\n        let offset = 0;\n        for (const item of items) {\n          out.set(item, offset);\n          offset += item.length;\n        }\n        return out;\n      }\n      function padded64(bytes, littleEndianLength = false) {\n        const bitLength = bytes.length * 8;\n        const total = Math.ceil((bytes.length + 9) / 64) * 64;\n        const out = new Uint8Array(total);\n        out.set(bytes);\n        out[bytes.length] = 128;\n        if (littleEndianLength) {\n          let n = bitLength;\n          for (let i = 0; i < 8; i++) {\n            out[total - 8 + i] = n & 255;\n            n = Math.floor(n / 256);\n          }\n        } else {\n          let n = bitLength;\n          for (let i = 7; i >= 0; i--) {\n            out[total - 8 + i] = n & 255;\n            n = Math.floor(n / 256);\n          }\n        }\n        return out;\n      }\n      function padded128(bytes) {\n        const bitLength = BigInt(bytes.length) * 8n;\n        const total = Math.ceil((bytes.length + 17) / 128) * 128;\n        const out = new Uint8Array(total);\n        out.set(bytes);\n        out[bytes.length] = 128;\n        let n = bitLength;\n        for (let i = 15; i >= 0; i--) {\n          out[total - 16 + i] = Number(n & 0xffn);\n          n >>= 8n;\n        }\n        return out;\n      }\n      function rotl32(value, bits) {\n        return (value << bits | value >>> 32 - bits) >>> 0;\n      }\n      function rotr32(value, bits) {\n        return (value >>> bits | value << 32 - bits) >>> 0;\n      }\n      function add32(...values) {\n        return values.reduce((sum, value) => sum + value >>> 0, 0);\n      }\n      function md5Bytes(bytes) {\n        const s = [\n          7,\n          12,\n          17,\n          22,\n          7,\n          12,\n          17,\n          22,\n          7,\n          12,\n          17,\n          22,\n          7,\n          12,\n          17,\n          22,\n          5,\n          9,\n          14,\n          20,\n          5,\n          9,\n          14,\n          20,\n          5,\n          9,\n          14,\n          20,\n          5,\n          9,\n          14,\n          20,\n          4,\n          11,\n          16,\n          23,\n          4,\n          11,\n          16,\n          23,\n          4,\n          11,\n          16,\n          23,\n          4,\n          11,\n          16,\n          23,\n          6,\n          10,\n          15,\n          21,\n          6,\n          10,\n          15,\n          21,\n          6,\n          10,\n          15,\n          21,\n          6,\n          10,\n          15,\n          21\n        ];\n        const k = Array.from(\n          { length: 64 },\n          (_value, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296) >>> 0\n        );\n        const data = padded64(bytes, true);\n        let a0 = 1732584193;\n        let b0 = 4023233417;\n        let c0 = 2562383102;\n        let d0 = 271733878;\n        for (let offset = 0; offset < data.length; offset += 64) {\n          const m = new Uint32Array(16);\n          for (let i = 0; i < 16; i++) {\n            const j = offset + i * 4;\n            m[i] = data[j] | data[j + 1] << 8 | data[j + 2] << 16 | data[j + 3] << 24;\n          }\n          let a = a0;\n          let b = b0;\n          let c = c0;\n          let d = d0;\n          for (let i = 0; i < 64; i++) {\n            let f;\n            let g;\n            if (i < 16) {\n              f = b & c | ~b & d;\n              g = i;\n            } else if (i < 32) {\n              f = d & b | ~d & c;\n              g = (5 * i + 1) % 16;\n            } else if (i < 48) {\n              f = b ^ c ^ d;\n              g = (3 * i + 5) % 16;\n            } else {\n              f = c ^ (b | ~d);\n              g = 7 * i % 16;\n            }\n            const tmp = d;\n            d = c;\n            c = b;\n            b = add32(b, rotl32(add32(a, f, k[i], m[g]), s[i]));\n            a = tmp;\n          }\n          a0 = add32(a0, a);\n          b0 = add32(b0, b);\n          c0 = add32(c0, c);\n          d0 = add32(d0, d);\n        }\n        const out = new Uint8Array(16);\n        for (const [index, value] of [a0, b0, c0, d0].entries()) {\n          out[index * 4] = value & 255;\n          out[index * 4 + 1] = value >>> 8 & 255;\n          out[index * 4 + 2] = value >>> 16 & 255;\n          out[index * 4 + 3] = value >>> 24 & 255;\n        }\n        return out;\n      }\n      function sha1Bytes(bytes) {\n        const data = padded64(bytes);\n        let h0 = 1732584193;\n        let h1 = 4023233417;\n        let h2 = 2562383102;\n        let h3 = 271733878;\n        let h4 = 3285377520;\n        for (let offset = 0; offset < data.length; offset += 64) {\n          const w = new Uint32Array(80);\n          for (let i = 0; i < 16; i++) {\n            const j = offset + i * 4;\n            w[i] = data[j] << 24 | data[j + 1] << 16 | data[j + 2] << 8 | data[j + 3];\n          }\n          for (let i = 16; i < 80; i++) {\n            w[i] = rotl32(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);\n          }\n          let a = h0;\n          let b = h1;\n          let c = h2;\n          let d = h3;\n          let e = h4;\n          for (let i = 0; i < 80; i++) {\n            let f;\n            let k;\n            if (i < 20) {\n              f = b & c | ~b & d;\n              k = 1518500249;\n            } else if (i < 40) {\n              f = b ^ c ^ d;\n              k = 1859775393;\n            } else if (i < 60) {\n              f = b & c | b & d | c & d;\n              k = 2400959708;\n            } else {\n              f = b ^ c ^ d;\n              k = 3395469782;\n            }\n            const temp = add32(rotl32(a, 5), f, e, k, w[i]);\n            e = d;\n            d = c;\n            c = rotl32(b, 30);\n            b = a;\n            a = temp;\n          }\n          h0 = add32(h0, a);\n          h1 = add32(h1, b);\n          h2 = add32(h2, c);\n          h3 = add32(h3, d);\n          h4 = add32(h4, e);\n        }\n        return words32ToBytes([h0, h1, h2, h3, h4]);\n      }\n      var SHA256_K = [\n        1116352408,\n        1899447441,\n        3049323471,\n        3921009573,\n        961987163,\n        1508970993,\n        2453635748,\n        2870763221,\n        3624381080,\n        310598401,\n        607225278,\n        1426881987,\n        1925078388,\n        2162078206,\n        2614888103,\n        3248222580,\n        3835390401,\n        4022224774,\n        264347078,\n        604807628,\n        770255983,\n        1249150122,\n        1555081692,\n        1996064986,\n        2554220882,\n        2821834349,\n        2952996808,\n        3210313671,\n        3336571891,\n        3584528711,\n        113926993,\n        338241895,\n        666307205,\n        773529912,\n        1294757372,\n        1396182291,\n        1695183700,\n        1986661051,\n        2177026350,\n        2456956037,\n        2730485921,\n        2820302411,\n        3259730800,\n        3345764771,\n        3516065817,\n        3600352804,\n        4094571909,\n        275423344,\n        430227734,\n        506948616,\n        659060556,\n        883997877,\n        958139571,\n        1322822218,\n        1537002063,\n        1747873779,\n        1955562222,\n        2024104815,\n        2227730452,\n        2361852424,\n        2428436474,\n        2756734187,\n        3204031479,\n        3329325298\n      ];\n      function words32ToBytes(words) {\n        const out = new Uint8Array(words.length * 4);\n        for (let i = 0; i < words.length; i++) {\n          out[i * 4] = words[i] >>> 24 & 255;\n          out[i * 4 + 1] = words[i] >>> 16 & 255;\n          out[i * 4 + 2] = words[i] >>> 8 & 255;\n          out[i * 4 + 3] = words[i] & 255;\n        }\n        return out;\n      }\n      function sha256Core(bytes, initial) {\n        const data = padded64(bytes);\n        const h = initial.slice();\n        for (let offset = 0; offset < data.length; offset += 64) {\n          const w = new Uint32Array(64);\n          for (let i = 0; i < 16; i++) {\n            const j = offset + i * 4;\n            w[i] = data[j] << 24 | data[j + 1] << 16 | data[j + 2] << 8 | data[j + 3];\n          }\n          for (let i = 16; i < 64; i++) {\n            const s0 = rotr32(w[i - 15], 7) ^ rotr32(w[i - 15], 18) ^ w[i - 15] >>> 3;\n            const s1 = rotr32(w[i - 2], 17) ^ rotr32(w[i - 2], 19) ^ w[i - 2] >>> 10;\n            w[i] = add32(w[i - 16], s0, w[i - 7], s1);\n          }\n          let [a, b, c, d, e, f, g, hh] = h;\n          for (let i = 0; i < 64; i++) {\n            const s1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25);\n            const ch = e & f ^ ~e & g;\n            const temp1 = add32(hh, s1, ch, SHA256_K[i], w[i]);\n            const s0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22);\n            const maj = a & b ^ a & c ^ b & c;\n            const temp2 = add32(s0, maj);\n            hh = g;\n            g = f;\n            f = e;\n            e = add32(d, temp1);\n            d = c;\n            c = b;\n            b = a;\n            a = add32(temp1, temp2);\n          }\n          for (const [i, value] of [a, b, c, d, e, f, g, hh].entries()) {\n            h[i] = add32(h[i], value);\n          }\n        }\n        return words32ToBytes(h);\n      }\n      function sha224Bytes(bytes) {\n        return sha256Core(\n          bytes,\n          [3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428]\n        ).slice(0, 28);\n      }\n      function sha256Bytes(bytes) {\n        return sha256Core(\n          bytes,\n          [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]\n        );\n      }\n      var MASK64 = (1n << 64n) - 1n;\n      var SHA512_K = [\n        0x428a2f98d728ae22n,\n        0x7137449123ef65cdn,\n        0xb5c0fbcfec4d3b2fn,\n        0xe9b5dba58189dbbcn,\n        0x3956c25bf348b538n,\n        0x59f111f1b605d019n,\n        0x923f82a4af194f9bn,\n        0xab1c5ed5da6d8118n,\n        0xd807aa98a3030242n,\n        0x12835b0145706fben,\n        0x243185be4ee4b28cn,\n        0x550c7dc3d5ffb4e2n,\n        0x72be5d74f27b896fn,\n        0x80deb1fe3b1696b1n,\n        0x9bdc06a725c71235n,\n        0xc19bf174cf692694n,\n        0xe49b69c19ef14ad2n,\n        0xefbe4786384f25e3n,\n        0x0fc19dc68b8cd5b5n,\n        0x240ca1cc77ac9c65n,\n        0x2de92c6f592b0275n,\n        0x4a7484aa6ea6e483n,\n        0x5cb0a9dcbd41fbd4n,\n        0x76f988da831153b5n,\n        0x983e5152ee66dfabn,\n        0xa831c66d2db43210n,\n        0xb00327c898fb213fn,\n        0xbf597fc7beef0ee4n,\n        0xc6e00bf33da88fc2n,\n        0xd5a79147930aa725n,\n        0x06ca6351e003826fn,\n        0x142929670a0e6e70n,\n        0x27b70a8546d22ffcn,\n        0x2e1b21385c26c926n,\n        0x4d2c6dfc5ac42aedn,\n        0x53380d139d95b3dfn,\n        0x650a73548baf63den,\n        0x766a0abb3c77b2a8n,\n        0x81c2c92e47edaee6n,\n        0x92722c851482353bn,\n        0xa2bfe8a14cf10364n,\n        0xa81a664bbc423001n,\n        0xc24b8b70d0f89791n,\n        0xc76c51a30654be30n,\n        0xd192e819d6ef5218n,\n        0xd69906245565a910n,\n        0xf40e35855771202an,\n        0x106aa07032bbd1b8n,\n        0x19a4c116b8d2d0c8n,\n        0x1e376c085141ab53n,\n        0x2748774cdf8eeb99n,\n        0x34b0bcb5e19b48a8n,\n        0x391c0cb3c5c95a63n,\n        0x4ed8aa4ae3418acbn,\n        0x5b9cca4f7763e373n,\n        0x682e6ff3d6b2b8a3n,\n        0x748f82ee5defb2fcn,\n        0x78a5636f43172f60n,\n        0x84c87814a1f0ab72n,\n        0x8cc702081a6439ecn,\n        0x90befffa23631e28n,\n        0xa4506cebde82bde9n,\n        0xbef9a3f7b2c67915n,\n        0xc67178f2e372532bn,\n        0xca273eceea26619cn,\n        0xd186b8c721c0c207n,\n        0xeada7dd6cde0eb1en,\n        0xf57d4f7fee6ed178n,\n        0x06f067aa72176fban,\n        0x0a637dc5a2c898a6n,\n        0x113f9804bef90daen,\n        0x1b710b35131c471bn,\n        0x28db77f523047d84n,\n        0x32caab7b40c72493n,\n        0x3c9ebe0a15c9bebcn,\n        0x431d67c49c100d4cn,\n        0x4cc5d4becb3e42b6n,\n        0x597f299cfc657e2an,\n        0x5fcb6fab3ad6faecn,\n        0x6c44198c4a475817n\n      ];\n      function rotr64(value, bits) {\n        const n = BigInt(bits);\n        return (value >> n | value << 64n - n) & MASK64;\n      }\n      function add64(...values) {\n        return values.reduce((sum, value) => sum + value & MASK64, 0n);\n      }\n      function words64ToBytes(words) {\n        const out = new Uint8Array(words.length * 8);\n        for (let i = 0; i < words.length; i++) {\n          let value = words[i];\n          for (let j = 7; j >= 0; j--) {\n            out[i * 8 + j] = Number(value & 0xffn);\n            value >>= 8n;\n          }\n        }\n        return out;\n      }\n      function sha512Core(bytes, initial) {\n        const data = padded128(bytes);\n        const h = initial.slice();\n        for (let offset = 0; offset < data.length; offset += 128) {\n          const w = new Array(80).fill(0n);\n          for (let i = 0; i < 16; i++) {\n            let value = 0n;\n            for (let j = 0; j < 8; j++) {\n              value = value << 8n | BigInt(data[offset + i * 8 + j]);\n            }\n            w[i] = value;\n          }\n          for (let i = 16; i < 80; i++) {\n            const s0 = rotr64(w[i - 15], 1) ^ rotr64(w[i - 15], 8) ^ w[i - 15] >> 7n;\n            const s1 = rotr64(w[i - 2], 19) ^ rotr64(w[i - 2], 61) ^ w[i - 2] >> 6n;\n            w[i] = add64(w[i - 16], s0, w[i - 7], s1);\n          }\n          let [a, b, c, d, e, f, g, hh] = h;\n          for (let i = 0; i < 80; i++) {\n            const s1 = rotr64(e, 14) ^ rotr64(e, 18) ^ rotr64(e, 41);\n            const ch = e & f ^ ~e & g;\n            const temp1 = add64(hh, s1, ch, SHA512_K[i], w[i]);\n            const s0 = rotr64(a, 28) ^ rotr64(a, 34) ^ rotr64(a, 39);\n            const maj = a & b ^ a & c ^ b & c;\n            const temp2 = add64(s0, maj);\n            hh = g;\n            g = f;\n            f = e;\n            e = add64(d, temp1);\n            d = c;\n            c = b;\n            b = a;\n            a = add64(temp1, temp2);\n          }\n          for (const [i, value] of [a, b, c, d, e, f, g, hh].entries()) {\n            h[i] = add64(h[i], value);\n          }\n        }\n        return words64ToBytes(h);\n      }\n      function sha384Bytes(bytes) {\n        return sha512Core(\n          bytes,\n          [\n            0xcbbb9d5dc1059ed8n,\n            0x629a292a367cd507n,\n            0x9159015a3070dd17n,\n            0x152fecd8f70e5939n,\n            0x67332667ffc00b31n,\n            0x8eb44a8768581511n,\n            0xdb0c2e0d64f98fa7n,\n            0x47b5481dbefa4fa4n\n          ]\n        ).slice(0, 48);\n      }\n      function sha512Bytes(bytes) {\n        return sha512Core(\n          bytes,\n          [\n            0x6a09e667f3bcc908n,\n            0xbb67ae8584caa73bn,\n            0x3c6ef372fe94f82bn,\n            0xa54ff53a5f1d36f1n,\n            0x510e527fade682d1n,\n            0x9b05688c2b3e6c1fn,\n            0x1f83d9abfb41bd6bn,\n            0x5be0cd19137e2179n\n          ]\n        );\n      }\n      var ALGORITHMS = {\n        md5: { blockSize: 64, digest: md5Bytes },\n        sha1: { blockSize: 64, digest: sha1Bytes },\n        sha224: { blockSize: 64, digest: sha224Bytes },\n        sha256: { blockSize: 64, digest: sha256Bytes },\n        sha384: { blockSize: 128, digest: sha384Bytes },\n        sha512: { blockSize: 128, digest: sha512Bytes }\n      };\n      function digestBytes2(algorithm, value, fnName) {\n        assertBinary(value, fnName);\n        return ALGORITHMS[algorithm].digest(value.bytes);\n      }\n      function hmacBytes2(algorithm, value, key, fnName) {\n        assertBinary(value, fnName);\n        assertBinary(key, fnName, "BinaryString key");\n        const spec = ALGORITHMS[algorithm];\n        let keyBytes = key.bytes;\n        if (keyBytes.length > spec.blockSize) {\n          keyBytes = spec.digest(keyBytes);\n        }\n        const paddedKey = new Uint8Array(spec.blockSize);\n        paddedKey.set(keyBytes);\n        const innerKey = new Uint8Array(spec.blockSize);\n        const outerKey = new Uint8Array(spec.blockSize);\n        for (let i = 0; i < spec.blockSize; i++) {\n          innerKey[i] = paddedKey[i] ^ 54;\n          outerKey[i] = paddedKey[i] ^ 92;\n        }\n        return spec.digest(concatBytes2(outerKey, spec.digest(concatBytes2(innerKey, value.bytes))));\n      }\n      module2.exports = {\n        digestBytes: digestBytes2,\n        hmacBytes: hmacBytes2,\n        toBinary,\n        bytesToHex,\n        bytesToBase64\n      };\n    }\n  });\n\n  // modules/std/secure.js\n  var require_secure = __commonJS({\n    "modules/std/secure.js"(exports, module) {\n      "use strict";\n      var { BinaryString } = require_runtime_helpers();\n      var taskRuntime = require_task();\n      var { digestBytes, hmacBytes } = require_hash();\n      var { Time } = require_time();\n      var BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";\n      var MAX_SAFE_INT = 9007199254740992;\n      var RANDOM_CAPABILITIES = /* @__PURE__ */ new Set(["bytes", "token", "int"]);\n      var KDF_CAPABILITIES = /* @__PURE__ */ new Set(["hkdf-sha256"]);\n      var CIPHER_CAPABILITIES = /* @__PURE__ */ new Set([\n        "aes-256-gcm",\n        "chacha20-poly1305"\n      ]);\n      var BROWSER_CIPHER_CAPABILITIES = /* @__PURE__ */ new Set(["aes-256-gcm"]);\n      var KEY_AGREEMENT_CAPABILITIES = /* @__PURE__ */ new Set(["x25519"]);\n      var CERTIFICATE_CAPABILITIES = /* @__PURE__ */ new Set([\n        "parse-x509",\n        "parse-x509-der",\n        "fingerprint-sha256",\n        "public-key",\n        "verify-chain"\n      ]);\n      var BROWSER_CERTIFICATE_CAPABILITIES = /* @__PURE__ */ new Set([\n        "parse-x509-der",\n        "fingerprint-sha256"\n      ]);\n      var TLS_IDENTITY_CAPABILITIES = /* @__PURE__ */ new Set(["pem", "pkcs12"]);\n      var BROWSER_TLS_IDENTITY_CAPABILITIES = /* @__PURE__ */ new Set(["pem"]);\n      var SIGNING_CAPABILITIES = /* @__PURE__ */ new Set([\n        "ed25519",\n        "ecdsa-p256-sha256",\n        "ecdsa-p384-sha384"\n      ]);\n      var SIGNING_ALGORITHMS = {\n        ed25519: {\n          type: "ed25519",\n          privateLength: 32,\n          publicLength: 32\n        },\n        "ecdsa-p256-sha256": {\n          type: "ecdsa",\n          privateLength: 32,\n          publicLength: 65,\n          signatureLength: 64,\n          nodeCurve: "prime256v1",\n          webCurve: "P-256",\n          jwkCurve: "P-256",\n          nodeHash: "sha256",\n          webHash: "SHA-256"\n        },\n        "ecdsa-p384-sha384": {\n          type: "ecdsa",\n          privateLength: 48,\n          publicLength: 97,\n          signatureLength: 96,\n          nodeCurve: "secp384r1",\n          webCurve: "P-384",\n          jwkCurve: "P-384",\n          nodeHash: "sha384",\n          webHash: "SHA-384"\n        }\n      };\n      var KEY_AGREEMENT_ALGORITHMS = {\n        x25519: {\n          privateLength: 32,\n          publicLength: 32\n        }\n      };\n      var DEFAULT_PASSWORD_HASH_ALGORITHM = "pbkdf2-sha256";\n      var HKDF_SHA256_HASH_LENGTH = 32;\n      var HKDF_SHA256_MAX_LENGTH = 255 * HKDF_SHA256_HASH_LENGTH;\n      var CIPHER_ALGORITHMS = {\n        "aes-256-gcm": {\n          keyLength: 32,\n          nonceLength: 12,\n          tagLength: 16,\n          nodeName: "aes-256-gcm",\n          webName: "AES-GCM"\n        },\n        "chacha20-poly1305": {\n          keyLength: 32,\n          nonceLength: 12,\n          tagLength: 16,\n          nodeName: "chacha20-poly1305",\n          webName: null\n        }\n      };\n      var PASSWORD_HASH_SALT_LENGTH = 16;\n      var PASSWORD_HASH_LENGTH = 32;\n      var PBKDF2_SHA256_ITERATIONS = 6e5;\n      var SCRYPT_LOG_N = 17;\n      var SCRYPT_R = 8;\n      var SCRYPT_P = 1;\n      var runtimePolicy = {\n        host_name: "node"\n      };\n      function setRuntimePolicy(policy = {}) {\n        runtimePolicy = {\n          ...runtimePolicy,\n          ...policy\n        };\n      }\n      function capabilities() {\n        return {\n          host: hostName(),\n          random: hasRandomSource(),\n          password_hash: passwordHashCapabilities(),\n          kdf: [...KDF_CAPABILITIES],\n          cipher: cipherCapabilities(),\n          key_agreement: keyAgreementCapabilities(),\n          signing: signingCapabilities(),\n          certificate: certificateCapabilities(),\n          tls_identity: tlsIdentityCapabilities(),\n          async_required: {\n            cipher: hostName() === "browser",\n            kdf: false,\n            password_hash: hostName() === "browser",\n            signing: hostName() === "browser",\n            key_agreement: hostName() === "browser" && keyAgreementCapabilities().length > 0\n          }\n        };\n      }\n      function hostName() {\n        return runtimePolicy.host_name || "node";\n      }\n      function capabilityPart(value) {\n        return value == null ? "" : String(value);\n      }\n      function passwordHashCapabilities() {\n        return hostName() === "browser" ? ["pbkdf2-sha256"] : ["pbkdf2-sha256", "scrypt"];\n      }\n      function signingCapabilities() {\n        if (hostName() === "browser") {\n          return ["ecdsa-p256-sha256", "ecdsa-p384-sha384"];\n        }\n        return [...SIGNING_CAPABILITIES];\n      }\n      function keyAgreementCapabilities() {\n        if (hostName() === "browser") {\n          return subtleKeyAgreementCrypto() ? ["x25519"] : [];\n        }\n        const crypto = nodeCrypto();\n        return crypto && typeof crypto.generateKeyPairSync === "function" && typeof crypto.diffieHellman === "function" ? [...KEY_AGREEMENT_CAPABILITIES] : [];\n      }\n      function cipherCapabilities() {\n        if (hostName() === "browser") {\n          return [...BROWSER_CIPHER_CAPABILITIES];\n        }\n        const crypto = nodeCrypto();\n        if (!crypto || typeof crypto.getCiphers !== "function") {\n          return [];\n        }\n        const supported = new Set(crypto.getCiphers());\n        return [...CIPHER_CAPABILITIES].filter((algorithm) => {\n          const meta = CIPHER_ALGORITHMS[algorithm];\n          return meta && supported.has(meta.nodeName);\n        });\n      }\n      function certificateCapabilities() {\n        return hostName() === "browser" ? [...BROWSER_CERTIFICATE_CAPABILITIES] : [...CERTIFICATE_CAPABILITIES];\n      }\n      function tlsIdentityCapabilities() {\n        return hostName() === "browser" ? [...BROWSER_TLS_IDENTITY_CAPABILITIES] : [...TLS_IDENTITY_CAPABILITIES];\n      }\n      function hasCapability(area, name2) {\n        area = capabilityPart(area);\n        name2 = capabilityPart(name2);\n        if (area === "random") {\n          return hasRandomSource() && RANDOM_CAPABILITIES.has(name2);\n        }\n        if (area === "password_hash") {\n          return passwordHashCapabilities().includes(name2);\n        }\n        if (area === "kdf") {\n          return KDF_CAPABILITIES.has(name2);\n        }\n        if (area === "cipher") {\n          return cipherCapabilities().includes(name2);\n        }\n        if (area === "key_agreement") {\n          return keyAgreementCapabilities().includes(name2);\n        }\n        if (area === "signing") {\n          return signingCapabilities().includes(name2);\n        }\n        if (area === "certificate") {\n          return certificateCapabilities().includes(name2);\n        }\n        if (area === "tls_identity") {\n          return tlsIdentityCapabilities().includes(name2);\n        }\n        return false;\n      }\n      function requireCapability(area, name2) {\n        area = capabilityPart(area);\n        name2 = capabilityPart(name2);\n        if (hasCapability(area, name2)) {\n          return true;\n        }\n        throw new Error(\n          `Secure capability \'${area}/${name2}\' is not available on host \'${hostName()}\'`\n        );\n      }\n      function hasRandomSource() {\n        if (globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") {\n          return true;\n        }\n        const crypto = nodeCrypto();\n        return !!(crypto && typeof crypto.randomBytes === "function");\n      }\n      function nodeCrypto() {\n        if (typeof __require !== "function") {\n          return null;\n        }\n        try {\n          return __require("node:crypto");\n        } catch (_err) {\n          return null;\n        }\n      }\n      function nodeForge() {\n        if (hostName() === "browser" || typeof __require !== "function") {\n          return null;\n        }\n        try {\n          const nodeRequire = eval("require");\n          return nodeRequire("node-forge");\n        } catch (_err) {\n          return null;\n        }\n      }\n      function nodeTls() {\n        if (hostName() === "browser" || typeof __require !== "function") {\n          return null;\n        }\n        try {\n          const nodeRequire = eval("require");\n          return nodeRequire("node:tls");\n        } catch (_err) {\n          return null;\n        }\n      }\n      function fillRandom(bytes) {\n        if (globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") {\n          for (let offset = 0; offset < bytes.length; offset += 65536) {\n            globalThis.crypto.getRandomValues(\n              bytes.subarray(offset, Math.min(offset + 65536, bytes.length))\n            );\n          }\n          return bytes;\n        }\n        const crypto = nodeCrypto();\n        if (crypto && typeof crypto.randomBytes === "function") {\n          bytes.set(crypto.randomBytes(bytes.length));\n          return bytes;\n        }\n        throw new Error("Secure random source is unavailable");\n      }\n      function nonNegativeInteger(value, label) {\n        const number = Number(value ?? 0);\n        if (!Number.isInteger(number) || number < 0) {\n          throw new Error(`${label} expects a non-negative integer`);\n        }\n        return number;\n      }\n      function positiveInteger(value, label) {\n        const number = Number(value ?? 0);\n        if (!Number.isInteger(number) || number <= 0) {\n          throw new Error(`${label} expects a positive integer`);\n        }\n        if (number > MAX_SAFE_INT) {\n          throw new Error(`${label} maximum is too large`);\n        }\n        return number;\n      }\n      function randomBytes(length) {\n        return fillRandom(new Uint8Array(length));\n      }\n      function base64url(bytes) {\n        let out = "";\n        for (let i = 0; i < bytes.length; i += 3) {\n          const b0 = bytes[i];\n          const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;\n          const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;\n          const triple = b0 << 16 | b1 << 8 | b2;\n          out += BASE64URL[triple >> 18 & 63];\n          out += BASE64URL[triple >> 12 & 63];\n          if (i + 1 < bytes.length) {\n            out += BASE64URL[triple >> 6 & 63];\n          }\n          if (i + 2 < bytes.length) {\n            out += BASE64URL[triple & 63];\n          }\n        }\n        return out;\n      }\n      function base64urlDecode(text) {\n        if (typeof text !== "string" || /[^A-Za-z0-9_-]/u.test(text)) {\n          return null;\n        }\n        const alphabet = new Map(BASE64URL.split("").map(\n          (value, index) => [value, index]\n        ));\n        const out = [];\n        let bits = 0;\n        let bitLength = 0;\n        for (const char of text) {\n          bits = bits << 6 | alphabet.get(char);\n          bitLength += 6;\n          while (bitLength >= 8) {\n            bitLength -= 8;\n            out.push(bits >> bitLength & 255);\n          }\n        }\n        if (bitLength > 0 && (bits & (1 << bitLength) - 1) !== 0) {\n          return null;\n        }\n        return Uint8Array.from(out);\n      }\n      function base64(bytes) {\n        const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";\n        let out = "";\n        for (let i = 0; i < bytes.length; i += 3) {\n          const b0 = bytes[i];\n          const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;\n          const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;\n          const triple = b0 << 16 | b1 << 8 | b2;\n          out += alphabet[triple >> 18 & 63];\n          out += alphabet[triple >> 12 & 63];\n          out += i + 1 < bytes.length ? alphabet[triple >> 6 & 63] : "=";\n          out += i + 2 < bytes.length ? alphabet[triple & 63] : "=";\n        }\n        return out;\n      }\n      function base64Decode(text) {\n        if (typeof text !== "string" || /[^A-Za-z0-9+/=]/u.test(text)) {\n          return null;\n        }\n        const clean = text.replace(/=+$/u, "");\n        const alphabet = new Map(\n          "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").map((value, index) => [value, index])\n        );\n        const out = [];\n        let bits = 0;\n        let bitLength = 0;\n        for (const char of clean) {\n          if (!alphabet.has(char)) {\n            return null;\n          }\n          bits = bits << 6 | alphabet.get(char);\n          bitLength += 6;\n          while (bitLength >= 8) {\n            bitLength -= 8;\n            out.push(bits >> bitLength & 255);\n          }\n        }\n        return Uint8Array.from(out);\n      }\n      function pemToDer(pem, label) {\n        const text = assertString(pem, label, "String key");\n        const body = text.replace(/-----BEGIN [^-]+-----/gu, "").replace(/-----END [^-]+-----/gu, "").replace(/\\s+/gu, "");\n        const bytes = base64Decode(body);\n        if (!bytes) {\n          throw new Error(`${label} expects PEM key text`);\n        }\n        return bytes;\n      }\n      function derToPem(label, der) {\n        const encoded = base64(der);\n        const lines = [];\n        for (let i = 0; i < encoded.length; i += 64) {\n          lines.push(encoded.slice(i, i + 64));\n        }\n        return `-----BEGIN ${label}-----\n${lines.join("\\n")}\n-----END ${label}-----\n`;\n      }\n      function certificateDerToPem(der) {\n        return derToPem("CERTIFICATE", der);\n      }\n      function certificatePemBlocks(pem, label) {\n        const text = assertString(pem, label, "String pem");\n        const blocks = [];\n        const re = /-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/gu;\n        let match;\n        while (match = re.exec(text)) {\n          const bytes = base64Decode(match[1].replace(/\\s+/gu, ""));\n          if (!bytes) {\n            throw new Error(`${label} expects PEM certificate text`);\n          }\n          blocks.push(bytes);\n        }\n        if (blocks.length === 0) {\n          throw new Error(`${label} expects PEM certificate text`);\n        }\n        return blocks;\n      }\n      function randomInt(max) {\n        if (max === 1) {\n          return 0;\n        }\n        const space = 2 ** 56;\n        const limit = space - space % max;\n        while (true) {\n          const bytes = randomBytes(7);\n          let value = 0;\n          for (const byte of bytes) {\n            value = value * 256 + byte;\n          }\n          if (value < limit) {\n            return value % max;\n          }\n        }\n      }\n      function typeName(value) {\n        if (value == null) {\n          return "Null";\n        }\n        if (value && value.bytes instanceof Uint8Array) {\n          return "BinaryString";\n        }\n        if (typeof value === "string") {\n          return "String";\n        }\n        return value.constructor && value.constructor.name ? value.constructor.name : typeof value;\n      }\n      function isPlainObject(value) {\n        return value != null && typeof value === "object" && !Array.isArray(value) && !(value.bytes instanceof Uint8Array);\n      }\n      function assertBinaryString(value, label, argName = "BinaryString") {\n        if (value && value.bytes instanceof Uint8Array) {\n          return value.bytes;\n        }\n        throw new Error(\n          `TypeException: ${label} expects ${argName}, got ${typeName(value)}`\n        );\n      }\n      function optionalBinaryString(value, label, argName) {\n        if (value == null) {\n          return new Uint8Array(0);\n        }\n        return assertBinaryString(value, label, argName);\n      }\n      function optionalDict(value, label, argName = "Dict") {\n        if (value == null) {\n          return {};\n        }\n        if (isPlainObject(value)) {\n          return value;\n        }\n        throw new Error(\n          `TypeException: ${label} expects ${argName}, got ${typeName(value)}`\n        );\n      }\n      function assertString(value, label, argName = "String") {\n        if (typeof value === "string") {\n          return value;\n        }\n        throw new Error(\n          `TypeException: ${label} expects ${argName}, got ${typeName(value)}`\n        );\n      }\n      function cipherAlgorithm(value, label) {\n        const algorithm = value == null ? "aes-256-gcm" : String(value);\n        if (!CIPHER_ALGORITHMS[algorithm] || !cipherCapabilities().includes(algorithm)) {\n          throw new Error(`${label} cipher algorithm \'${algorithm}\' is not available`);\n        }\n        return algorithm;\n      }\n      function cipherOptions(value, label) {\n        const options = optionalDict(value, label, "Dict options");\n        const algorithmValue = options.algorithm;\n        return {\n          algorithm: cipherAlgorithm(algorithmValue, label),\n          algorithmSupplied: algorithmValue != null,\n          aad: optionalBinaryString(options.aad, label, "BinaryString aad")\n        };\n      }\n      function cipherMeta(algorithm) {\n        return CIPHER_ALGORITHMS[algorithm];\n      }\n      function cipherKey(value, label, meta) {\n        const key = assertBinaryString(value, label, "BinaryString key");\n        if (key.length !== meta.keyLength) {\n          throw new Error(`${label} expects a ${meta.keyLength}-byte key`);\n        }\n        return key;\n      }\n      function envelopeBytes(envelope, field, label, length = null) {\n        const bytes = assertBinaryString(\n          envelope[field],\n          label,\n          `BinaryString envelope.${field}`\n        );\n        if (length != null && bytes.length !== length) {\n          throw new Error(`${label} expects envelope.${field} to be ${length} bytes`);\n        }\n        return bytes;\n      }\n      function cipherEnvelope(value, label) {\n        const envelope = optionalDict(value, label, "Dict envelope");\n        if (envelope.version !== 1) {\n          throw new Error(`${label} expects envelope.version 1`);\n        }\n        const algorithm = cipherAlgorithm(envelope.algorithm, label);\n        const meta = cipherMeta(algorithm);\n        return {\n          algorithm,\n          nonce: envelopeBytes(envelope, "nonce", label, meta.nonceLength),\n          ciphertext: envelopeBytes(envelope, "ciphertext", label),\n          tag: envelopeBytes(envelope, "tag", label, meta.tagLength)\n        };\n      }\n      function cipherEnvelopeValue(algorithm, nonce, ciphertext, tag) {\n        return {\n          version: 1,\n          algorithm,\n          nonce: new BinaryString(nonce),\n          ciphertext: new BinaryString(ciphertext),\n          tag: new BinaryString(tag)\n        };\n      }\n      function hkdfLength(value, label) {\n        const number = Number(value);\n        if (!Number.isInteger(number) || number < 0 || number > HKDF_SHA256_MAX_LENGTH) {\n          throw new Error(\n            `${label} expects length between 0 and ${HKDF_SHA256_MAX_LENGTH}`\n          );\n        }\n        return number;\n      }\n      function concatBytes(...items) {\n        const total = items.reduce((sum, item) => sum + item.length, 0);\n        const out = new Uint8Array(total);\n        let offset = 0;\n        for (const item of items) {\n          out.set(item, offset);\n          offset += item.length;\n        }\n        return out;\n      }\n      function hmacSha256(key, value) {\n        return hmacBytes(\n          "sha256",\n          new BinaryString(value),\n          new BinaryString(key),\n          "KeyDerivation.hkdf_sha256"\n        );\n      }\n      function hkdfSha256Bytes(inputKeyMaterial, length, salt, info) {\n        if (length === 0) {\n          return new Uint8Array(0);\n        }\n        const prk = hmacSha256(salt, inputKeyMaterial);\n        let previous = new Uint8Array(0);\n        let out = new Uint8Array(0);\n        let counter = 1;\n        while (out.length < length) {\n          previous = hmacSha256(\n            prk,\n            concatBytes(previous, info, Uint8Array.of(counter))\n          );\n          out = concatBytes(out, previous);\n          counter++;\n        }\n        return out.slice(0, length);\n      }\n      function hkdfSha256Inputs(inputKeyMaterial, length, salt, info) {\n        const label = "KeyDerivation.hkdf_sha256";\n        return {\n          inputKeyMaterial: assertBinaryString(inputKeyMaterial, label),\n          length: hkdfLength(length, label),\n          salt: optionalBinaryString(salt, label, "BinaryString salt"),\n          info: optionalBinaryString(info, label, "BinaryString info")\n        };\n      }\n      function hkdfSha256(inputKeyMaterial, length, salt = null, info = null) {\n        const args = hkdfSha256Inputs(inputKeyMaterial, length, salt, info);\n        return new BinaryString(\n          hkdfSha256Bytes(\n            args.inputKeyMaterial,\n            args.length,\n            args.salt,\n            args.info\n          )\n        );\n      }\n      function passwordBytes(value, label) {\n        return new TextEncoder().encode(\n          assertString(value, label, "String password")\n        );\n      }\n      function optionString(options, key, fallback) {\n        return options[key] == null ? fallback : String(options[key]);\n      }\n      function optionPositiveInteger(options, key, fallback, label) {\n        if (options[key] == null) {\n          return fallback;\n        }\n        return positiveInteger(options[key], `${label} option \'${key}\'`);\n      }\n      function passwordHashAlgorithm(options, label) {\n        const algorithm = optionString(\n          options,\n          "algorithm",\n          DEFAULT_PASSWORD_HASH_ALGORITHM\n        );\n        if (!passwordHashCapabilities().includes(algorithm)) {\n          throw new Error(\n            `${label} password hash algorithm \'${algorithm}\' is not available`\n          );\n        }\n        return algorithm;\n      }\n      function pbkdf2Options(options, label) {\n        return {\n          iterations: optionPositiveInteger(\n            options,\n            "iterations",\n            PBKDF2_SHA256_ITERATIONS,\n            label\n          ),\n          length: optionPositiveInteger(\n            options,\n            "length",\n            PASSWORD_HASH_LENGTH,\n            label\n          )\n        };\n      }\n      function scryptOptions(options, label) {\n        let logN = optionPositiveInteger(options, "log_n", SCRYPT_LOG_N, label);\n        const defaultCost = 2 ** logN;\n        const cost = optionPositiveInteger(options, "cost", defaultCost, label);\n        if (cost < 2 || (cost & cost - 1) !== 0) {\n          throw new Error(`${label} option \'cost\' must be a power of two`);\n        }\n        logN = Math.log2(cost);\n        return {\n          logN,\n          cost,\n          r: optionPositiveInteger(options, "r", SCRYPT_R, label),\n          p: optionPositiveInteger(options, "p", SCRYPT_P, label),\n          length: optionPositiveInteger(\n            options,\n            "length",\n            PASSWORD_HASH_LENGTH,\n            label\n          )\n        };\n      }\n      function constantTimeEqual(left, right) {\n        if (!left || !right || left.length !== right.length) {\n          return false;\n        }\n        let diff = 0;\n        for (let i = 0; i < left.length; i++) {\n          diff |= left[i] ^ right[i];\n        }\n        return diff === 0;\n      }\n      function parseParamList(text) {\n        const out = {};\n        for (const part of text.split(",")) {\n          const index = part.indexOf("=");\n          if (index <= 0) {\n            return null;\n          }\n          out[part.slice(0, index)] = part.slice(index + 1);\n        }\n        return out;\n      }\n      function parsePasswordHash(encoded) {\n        if (typeof encoded !== "string") {\n          return null;\n        }\n        let match = encoded.match(\n          /^\\$zuzu-pbkdf2-sha256\\$v=1\\$([^$]+)\\$([^$]+)\\$([^$]+)$/u\n        );\n        if (match) {\n          const params = parseParamList(match[1]);\n          if (!params || !/^\\d+$/u.test(params.i || "") || !/^\\d+$/u.test(params.l || "")) {\n            return null;\n          }\n          const salt = base64urlDecode(match[2]);\n          const hash = base64urlDecode(match[3]);\n          if (!salt || !hash) {\n            return null;\n          }\n          return {\n            algorithm: "pbkdf2-sha256",\n            iterations: Number(params.i),\n            length: Number(params.l),\n            salt,\n            hash\n          };\n        }\n        match = encoded.match(\n          /^\\$scrypt\\$([^$]+)\\$([^$]+)\\$([^$]+)$/u\n        );\n        if (match) {\n          const params = parseParamList(match[1]);\n          if (!params || !/^\\d+$/u.test(params.ln || "") || !/^\\d+$/u.test(params.r || "") || !/^\\d+$/u.test(params.p || "") || !/^\\d+$/u.test(params.l || "")) {\n            return null;\n          }\n          const salt = base64urlDecode(match[2]);\n          const hash = base64urlDecode(match[3]);\n          if (!salt || !hash) {\n            return null;\n          }\n          return {\n            algorithm: "scrypt",\n            log_n: Number(params.ln),\n            r: Number(params.r),\n            p: Number(params.p),\n            length: Number(params.l),\n            salt,\n            hash\n          };\n        }\n        return null;\n      }\n      function nodePbkdf2(password, salt, iterations, length) {\n        const crypto = nodeCrypto();\n        if (!crypto || typeof crypto.pbkdf2Sync !== "function") {\n          throw new Error("PBKDF2-SHA256 is unavailable on this host");\n        }\n        return new Uint8Array(\n          crypto.pbkdf2Sync(password, salt, iterations, length, "sha256")\n        );\n      }\n      function nodeScrypt(password, salt, options) {\n        const crypto = nodeCrypto();\n        if (!crypto || typeof crypto.scryptSync !== "function") {\n          throw new Error("scrypt is unavailable on this host");\n        }\n        return new Uint8Array(\n          crypto.scryptSync(\n            password,\n            salt,\n            options.length,\n            {\n              N: options.cost,\n              r: options.r,\n              p: options.p,\n              maxmem: Math.max(\n                32 * 1024 * 1024,\n                128 * options.cost * options.r + 64 * 1024 * 1024\n              )\n            }\n          )\n        );\n      }\n      function passwordHashDeriveBytes(password, algorithm, salt, options, label) {\n        if (algorithm === "pbkdf2-sha256") {\n          const pbkdf2Opts = pbkdf2Options(options, label);\n          return nodePbkdf2(\n            password,\n            salt,\n            pbkdf2Opts.iterations,\n            pbkdf2Opts.length\n          );\n        }\n        if (algorithm === "scrypt") {\n          return nodeScrypt(password, salt, scryptOptions(options, label));\n        }\n        throw new Error(`${label} does not support algorithm \'${algorithm}\'`);\n      }\n      async function webCryptoPbkdf2(password, salt, iterations, length) {\n        const subtle = subtleCrypto();\n        if (!subtle) {\n          throw new Error("Web Crypto PBKDF2-SHA256 is unavailable");\n        }\n        const key = await subtle.importKey(\n          "raw",\n          password,\n          "PBKDF2",\n          false,\n          ["deriveBits"]\n        );\n        const bits = await subtle.deriveBits(\n          {\n            name: "PBKDF2",\n            hash: "SHA-256",\n            salt,\n            iterations\n          },\n          key,\n          length * 8\n        );\n        return new Uint8Array(bits);\n      }\n      async function passwordHashDeriveBytesAsync(password, algorithm, salt, options, label) {\n        if (algorithm === "pbkdf2-sha256" && hostName() === "browser") {\n          const pbkdf2Opts = pbkdf2Options(options, label);\n          return webCryptoPbkdf2(\n            password,\n            salt,\n            pbkdf2Opts.iterations,\n            pbkdf2Opts.length\n          );\n        }\n        return passwordHashDeriveBytes(password, algorithm, salt, options, label);\n      }\n      function passwordHash(passwordValue, optionsValue = null) {\n        const label = "PasswordHash.hash";\n        if (hostName() === "browser") {\n          throw new Error(\n            "PasswordHash.hash is not available synchronously on host browser; use PasswordHash.hash_async"\n          );\n        }\n        const password = passwordBytes(passwordValue, label);\n        const options = optionalDict(optionsValue, label, "Dict options");\n        const algorithm = passwordHashAlgorithm(options, label);\n        const salt = options.salt == null ? randomBytes(PASSWORD_HASH_SALT_LENGTH) : assertBinaryString(options.salt, label, "BinaryString salt");\n        const hash = passwordHashDeriveBytes(\n          password,\n          algorithm,\n          salt,\n          options,\n          label\n        );\n        if (algorithm === "pbkdf2-sha256") {\n          const pbkdf2Opts = pbkdf2Options(options, label);\n          return [\n            "",\n            "zuzu-pbkdf2-sha256",\n            "v=1",\n            `i=${pbkdf2Opts.iterations},l=${pbkdf2Opts.length}`,\n            base64url(salt),\n            base64url(hash)\n          ].join("$");\n        }\n        const scryptOpts = scryptOptions(options, label);\n        return [\n          "",\n          "scrypt",\n          `ln=${scryptOpts.logN},r=${scryptOpts.r},p=${scryptOpts.p},l=${scryptOpts.length}`,\n          base64url(salt),\n          base64url(hash)\n        ].join("$");\n      }\n      async function passwordHashAsyncValue(passwordValue, optionsValue = null) {\n        const label = "PasswordHash.hash";\n        const password = passwordBytes(passwordValue, label);\n        const options = optionalDict(optionsValue, label, "Dict options");\n        const algorithm = passwordHashAlgorithm(options, label);\n        const salt = options.salt == null ? randomBytes(PASSWORD_HASH_SALT_LENGTH) : assertBinaryString(options.salt, label, "BinaryString salt");\n        const hash = await passwordHashDeriveBytesAsync(\n          password,\n          algorithm,\n          salt,\n          options,\n          label\n        );\n        if (algorithm === "pbkdf2-sha256") {\n          const pbkdf2Opts = pbkdf2Options(options, label);\n          return [\n            "",\n            "zuzu-pbkdf2-sha256",\n            "v=1",\n            `i=${pbkdf2Opts.iterations},l=${pbkdf2Opts.length}`,\n            base64url(salt),\n            base64url(hash)\n          ].join("$");\n        }\n        const scryptOpts = scryptOptions(options, label);\n        return [\n          "",\n          "scrypt",\n          `ln=${scryptOpts.logN},r=${scryptOpts.r},p=${scryptOpts.p},l=${scryptOpts.length}`,\n          base64url(salt),\n          base64url(hash)\n        ].join("$");\n      }\n      function passwordHashVerify(passwordValue, encodedValue) {\n        const label = "PasswordHash.verify";\n        if (hostName() === "browser") {\n          throw new Error(\n            "PasswordHash.verify is not available synchronously on host browser; use PasswordHash.verify_async"\n          );\n        }\n        const password = passwordBytes(passwordValue, label);\n        const encoded = assertString(encodedValue, label, "String encoded_hash");\n        const parsed = parsePasswordHash(encoded);\n        if (!parsed || !passwordHashCapabilities().includes(parsed.algorithm)) {\n          return false;\n        }\n        try {\n          const hash = passwordHashDeriveBytes(\n            password,\n            parsed.algorithm,\n            parsed.salt,\n            parsed,\n            label\n          );\n          return constantTimeEqual(hash, parsed.hash);\n        } catch (_err) {\n          return false;\n        }\n      }\n      async function passwordHashVerifyAsyncValue(passwordValue, encodedValue) {\n        const label = "PasswordHash.verify";\n        const password = passwordBytes(passwordValue, label);\n        const encoded = assertString(encodedValue, label, "String encoded_hash");\n        const parsed = parsePasswordHash(encoded);\n        if (!parsed || !passwordHashCapabilities().includes(parsed.algorithm)) {\n          return false;\n        }\n        try {\n          const hash = await passwordHashDeriveBytesAsync(\n            password,\n            parsed.algorithm,\n            parsed.salt,\n            parsed,\n            label\n          );\n          return constantTimeEqual(hash, parsed.hash);\n        } catch (_err) {\n          return false;\n        }\n      }\n      function passwordHashNeedsRehash(encodedValue, optionsValue = null) {\n        const label = "PasswordHash.needs_rehash";\n        const encoded = assertString(encodedValue, label, "String encoded_hash");\n        const options = optionalDict(optionsValue, label, "Dict options");\n        const target = passwordHashAlgorithm(options, label);\n        const parsed = parsePasswordHash(encoded);\n        if (!parsed || parsed.algorithm !== target) {\n          return true;\n        }\n        if (target === "pbkdf2-sha256") {\n          const pbkdf2Opts = pbkdf2Options(options, label);\n          return parsed.iterations < pbkdf2Opts.iterations || parsed.length !== pbkdf2Opts.length;\n        }\n        if (target === "scrypt") {\n          const scryptOpts = scryptOptions(options, label);\n          return parsed.log_n < scryptOpts.logN || parsed.r !== scryptOpts.r || parsed.p !== scryptOpts.p || parsed.length !== scryptOpts.length;\n        }\n        return true;\n      }\n      function passwordHashDeriveKey(passwordValue, optionsValue = null) {\n        const label = "PasswordHash.derive_key";\n        if (hostName() === "browser") {\n          throw new Error(\n            "PasswordHash.derive_key is not available synchronously on host browser; use PasswordHash.derive_key_async"\n          );\n        }\n        const password = passwordBytes(passwordValue, label);\n        const options = optionalDict(optionsValue, label, "Dict options");\n        const algorithm = passwordHashAlgorithm(options, label);\n        if (options.salt == null) {\n          throw new Error(`${label} expects BinaryString salt`);\n        }\n        const salt = assertBinaryString(options.salt, label, "BinaryString salt");\n        return new BinaryString(\n          passwordHashDeriveBytes(password, algorithm, salt, options, label)\n        );\n      }\n      async function passwordHashDeriveKeyAsyncValue(passwordValue, optionsValue = null) {\n        const label = "PasswordHash.derive_key";\n        const password = passwordBytes(passwordValue, label);\n        const options = optionalDict(optionsValue, label, "Dict options");\n        const algorithm = passwordHashAlgorithm(options, label);\n        if (options.salt == null) {\n          throw new Error(`${label} expects BinaryString salt`);\n        }\n        const salt = assertBinaryString(options.salt, label, "BinaryString salt");\n        return new BinaryString(\n          await passwordHashDeriveBytesAsync(\n            password,\n            algorithm,\n            salt,\n            options,\n            label\n          )\n        );\n      }\n      function subtleCrypto() {\n        return globalThis.crypto && globalThis.crypto.subtle && typeof globalThis.crypto.subtle.importKey === "function" && typeof globalThis.crypto.subtle.deriveBits === "function" ? globalThis.crypto.subtle : null;\n      }\n      function subtleAesCrypto() {\n        return globalThis.crypto && globalThis.crypto.subtle && typeof globalThis.crypto.subtle.importKey === "function" && typeof globalThis.crypto.subtle.encrypt === "function" && typeof globalThis.crypto.subtle.decrypt === "function" ? globalThis.crypto.subtle : null;\n      }\n      function cipherGenerateKey(algorithm = "aes-256-gcm") {\n        const actual = cipherAlgorithm(algorithm, "Cipher.generate_key");\n        return new BinaryString(randomBytes(cipherMeta(actual).keyLength));\n      }\n      function nodeCipherEncrypt(plaintext, key, options) {\n        const crypto = nodeCrypto();\n        const meta = cipherMeta(options.algorithm);\n        if (!crypto || typeof crypto.createCipheriv !== "function" || !crypto.getCiphers().includes(meta.nodeName)) {\n          throw new Error(`${options.algorithm} is unavailable on this host`);\n        }\n        const nonce = randomBytes(meta.nonceLength);\n        const cipher = crypto.createCipheriv(\n          meta.nodeName,\n          key,\n          nonce,\n          { authTagLength: meta.tagLength }\n        );\n        cipher.setAAD(options.aad);\n        const ciphertext = concatBytes(\n          cipher.update(plaintext),\n          cipher.final()\n        );\n        const tag = new Uint8Array(cipher.getAuthTag());\n        return cipherEnvelopeValue(options.algorithm, nonce, ciphertext, tag);\n      }\n      function nodeCipherDecrypt(envelope, key, options) {\n        const crypto = nodeCrypto();\n        const meta = cipherMeta(envelope.algorithm);\n        if (!crypto || typeof crypto.createDecipheriv !== "function" || !crypto.getCiphers().includes(meta.nodeName)) {\n          throw new Error(`${envelope.algorithm} is unavailable on this host`);\n        }\n        try {\n          const decipher = crypto.createDecipheriv(\n            meta.nodeName,\n            key,\n            envelope.nonce,\n            { authTagLength: meta.tagLength }\n          );\n          decipher.setAAD(options.aad);\n          decipher.setAuthTag(envelope.tag);\n          return new BinaryString(\n            concatBytes(\n              decipher.update(envelope.ciphertext),\n              decipher.final()\n            )\n          );\n        } catch (_err) {\n          throw new Error("Cipher.decrypt authentication failed");\n        }\n      }\n      function cipherEncrypt(plaintext, key, options = null) {\n        const label = "Cipher.encrypt";\n        const bytes = assertBinaryString(plaintext, label, "BinaryString plaintext");\n        const cipherOpts = cipherOptions(options, label);\n        const keyBytes = cipherKey(key, label, cipherMeta(cipherOpts.algorithm));\n        if (hostName() === "browser") {\n          throw new Error(\n            "Cipher.encrypt is not available synchronously on host browser; use Cipher.encrypt_async"\n          );\n        }\n        return nodeCipherEncrypt(bytes, keyBytes, cipherOpts);\n      }\n      function cipherDecrypt(envelope, key, options = null) {\n        const label = "Cipher.decrypt";\n        const cipherOpts = cipherOptions(options, label);\n        const cipherEnv = cipherEnvelope(envelope, label);\n        if (cipherOpts.algorithmSupplied && cipherOpts.algorithm !== cipherEnv.algorithm) {\n          throw new Error(\n            `${label} options.algorithm does not match envelope.algorithm`\n          );\n        }\n        const keyBytes = cipherKey(key, label, cipherMeta(cipherEnv.algorithm));\n        if (hostName() === "browser") {\n          throw new Error(\n            "Cipher.decrypt is not available synchronously on host browser; use Cipher.decrypt_async"\n          );\n        }\n        return nodeCipherDecrypt(cipherEnv, keyBytes, cipherOpts);\n      }\n      async function webCryptoCipherEncrypt(plaintext, key, options) {\n        if (options.algorithm !== "aes-256-gcm") {\n          throw new Error(`${options.algorithm} is unavailable on host browser`);\n        }\n        const subtle = subtleAesCrypto();\n        if (!subtle) {\n          throw new Error("Web Crypto AES-GCM is unavailable");\n        }\n        const meta = cipherMeta(options.algorithm);\n        const nonce = randomBytes(meta.nonceLength);\n        const cryptoKey = await subtle.importKey(\n          "raw",\n          key,\n          "AES-GCM",\n          false,\n          ["encrypt"]\n        );\n        const sealed = new Uint8Array(await subtle.encrypt(\n          {\n            name: "AES-GCM",\n            iv: nonce,\n            additionalData: options.aad,\n            tagLength: 128\n          },\n          cryptoKey,\n          plaintext\n        ));\n        return cipherEnvelopeValue(\n          options.algorithm,\n          nonce,\n          sealed.slice(0, sealed.length - meta.tagLength),\n          sealed.slice(sealed.length - meta.tagLength)\n        );\n      }\n      async function webCryptoCipherDecrypt(envelope, key, options) {\n        if (envelope.algorithm !== "aes-256-gcm") {\n          throw new Error(`${envelope.algorithm} is unavailable on host browser`);\n        }\n        const subtle = subtleAesCrypto();\n        if (!subtle) {\n          throw new Error("Web Crypto AES-GCM is unavailable");\n        }\n        const cryptoKey = await subtle.importKey(\n          "raw",\n          key,\n          "AES-GCM",\n          false,\n          ["decrypt"]\n        );\n        try {\n          const plaintext = await subtle.decrypt(\n            {\n              name: "AES-GCM",\n              iv: envelope.nonce,\n              additionalData: options.aad,\n              tagLength: 128\n            },\n            cryptoKey,\n            concatBytes(envelope.ciphertext, envelope.tag)\n          );\n          return new BinaryString(new Uint8Array(plaintext));\n        } catch (_err) {\n          throw new Error("Cipher.decrypt authentication failed");\n        }\n      }\n      function cipherEncryptAsync(plaintext, key, options = null) {\n        const label = "Cipher.encrypt";\n        const bytes = assertBinaryString(plaintext, label, "BinaryString plaintext");\n        const cipherOpts = cipherOptions(options, label);\n        const keyBytes = cipherKey(key, label, cipherMeta(cipherOpts.algorithm));\n        if (hostName() === "browser") {\n          return taskRuntime.Task.from(\n            webCryptoCipherEncrypt(bytes, keyBytes, cipherOpts)\n          );\n        }\n        return taskRuntime.Task.resolved(\n          nodeCipherEncrypt(bytes, keyBytes, cipherOpts)\n        );\n      }\n      function cipherDecryptAsync(envelope, key, options = null) {\n        const label = "Cipher.decrypt";\n        const cipherOpts = cipherOptions(options, label);\n        const cipherEnv = cipherEnvelope(envelope, label);\n        if (cipherOpts.algorithmSupplied && cipherOpts.algorithm !== cipherEnv.algorithm) {\n          throw new Error(\n            `${label} options.algorithm does not match envelope.algorithm`\n          );\n        }\n        const keyBytes = cipherKey(key, label, cipherMeta(cipherEnv.algorithm));\n        if (hostName() === "browser") {\n          return taskRuntime.Task.from(\n            webCryptoCipherDecrypt(cipherEnv, keyBytes, cipherOpts)\n          );\n        }\n        return taskRuntime.Task.resolved(\n          nodeCipherDecrypt(cipherEnv, keyBytes, cipherOpts)\n        );\n      }\n      async function webCryptoHkdfSha256(args) {\n        if (args.length === 0) {\n          return new BinaryString();\n        }\n        const subtle = subtleCrypto();\n        if (!subtle) {\n          return hkdfSha256(\n            new BinaryString(args.inputKeyMaterial),\n            args.length,\n            new BinaryString(args.salt),\n            new BinaryString(args.info)\n          );\n        }\n        const key = await subtle.importKey(\n          "raw",\n          args.inputKeyMaterial,\n          "HKDF",\n          false,\n          ["deriveBits"]\n        );\n        const bits = await subtle.deriveBits(\n          {\n            name: "HKDF",\n            hash: "SHA-256",\n            salt: args.salt,\n            info: args.info\n          },\n          key,\n          args.length * 8\n        );\n        return new BinaryString(new Uint8Array(bits));\n      }\n      function signingAlgorithm(algorithm, label) {\n        const value = algorithm == null ? "ed25519" : String(algorithm);\n        if (!SIGNING_ALGORITHMS[value]) {\n          throw new Error(\n            `${label} only supports ed25519, ecdsa-p256-sha256, and ecdsa-p384-sha384`\n          );\n        }\n        return value;\n      }\n      function signingAlgorithmOption(options, label) {\n        return options.algorithm == null ? null : signingAlgorithm(options.algorithm, label);\n      }\n      function browserSigningAlgorithm(algorithm, label) {\n        if (!signingCapabilities().includes(algorithm)) {\n          throw new Error(\n            `${label} signing algorithm \'${algorithm}\' is not available on host browser`\n          );\n        }\n        return algorithm;\n      }\n      function signingMeta(algorithm) {\n        return SIGNING_ALGORITHMS[algorithm];\n      }\n      function keyAgreementAlgorithm(value = "x25519", label) {\n        if (value == null) {\n          value = "x25519";\n        }\n        value = String(value);\n        if (!KEY_AGREEMENT_ALGORITHMS[value]) {\n          throw new Error(`${label} only supports x25519`);\n        }\n        return value;\n      }\n      function keyAgreementAlgorithmOption(options, label) {\n        return options.algorithm == null ? null : keyAgreementAlgorithm(options.algorithm, label);\n      }\n      function keyAgreementMeta(algorithm) {\n        return KEY_AGREEMENT_ALGORITHMS[algorithm];\n      }\n      function keyFormat(key, optionsValue, label) {\n        const options = optionalDict(optionsValue, label, "Dict options");\n        if (options.format != null) {\n          return String(options.format);\n        }\n        return key && key.bytes instanceof Uint8Array ? "raw" : "pem";\n      }\n      function nodeUnsupported(label) {\n        throw new Error(`${label} signing is unavailable on this host`);\n      }\n      function keyAgreementUnsupported(label) {\n        throw new Error(`${label} key agreement is unavailable on this host`);\n      }\n      function derLength(length) {\n        if (length < 128) {\n          return Uint8Array.of(length);\n        }\n        const bytes = [];\n        while (length > 0) {\n          bytes.unshift(length & 255);\n          length >>= 8;\n        }\n        return Uint8Array.of(128 | bytes.length, ...bytes);\n      }\n      function derElement(tag, body) {\n        return concatBytes(Uint8Array.of(tag), derLength(body.length), body);\n      }\n      function derSequence(...items) {\n        return derElement(48, concatBytes(...items));\n      }\n      function derIntegerSmall(value) {\n        return derElement(2, Uint8Array.of(value));\n      }\n      function derOctetString(bytes) {\n        return derElement(4, bytes);\n      }\n      function derOid(bytes) {\n        return derElement(6, Uint8Array.from(bytes));\n      }\n      function derBitString(bytes) {\n        return derElement(3, concatBytes(Uint8Array.of(0), bytes));\n      }\n      function ecCurveOid(algorithm) {\n        return algorithm === "ecdsa-p256-sha256" ? [42, 134, 72, 206, 61, 3, 1, 7] : [43, 129, 4, 0, 34];\n      }\n      function pkcs8DerFromRawSeed(seed) {\n        return concatBytes(\n          Uint8Array.from([\n            48,\n            46,\n            2,\n            1,\n            0,\n            48,\n            5,\n            6,\n            3,\n            43,\n            101,\n            112,\n            4,\n            34,\n            4,\n            32\n          ]),\n          seed\n        );\n      }\n      function x25519Pkcs8DerFromRawPrivate(bytes) {\n        return concatBytes(\n          Uint8Array.from([\n            48,\n            46,\n            2,\n            1,\n            0,\n            48,\n            5,\n            6,\n            3,\n            43,\n            101,\n            110,\n            4,\n            34,\n            4,\n            32\n          ]),\n          bytes\n        );\n      }\n      function x25519SpkiDerFromRawPublic(bytes) {\n        return concatBytes(\n          Uint8Array.from([\n            48,\n            42,\n            48,\n            5,\n            6,\n            3,\n            43,\n            101,\n            110,\n            3,\n            33,\n            0\n          ]),\n          bytes\n        );\n      }\n      function ecdsaPkcs8DerFromRawScalar(scalar, algorithm) {\n        return derSequence(\n          derIntegerSmall(0),\n          derSequence(\n            derOid([42, 134, 72, 206, 61, 2, 1]),\n            derOid(ecCurveOid(algorithm))\n          ),\n          derOctetString(derSequence(\n            derIntegerSmall(1),\n            derOctetString(scalar)\n          ))\n        );\n      }\n      function ecdsaSpkiDerFromRawPublic(publicKey, algorithm) {\n        return derSequence(\n          derSequence(\n            derOid([42, 134, 72, 206, 61, 2, 1]),\n            derOid(ecCurveOid(algorithm))\n          ),\n          derBitString(publicKey)\n        );\n      }\n      function derReader(bytes) {\n        return {\n          bytes,\n          offset: 0,\n          readElement(expectedTag = null) {\n            if (this.offset + 2 > this.bytes.length) {\n              throw new Error("truncated DER");\n            }\n            const tag = this.bytes[this.offset++];\n            if (expectedTag != null && tag !== expectedTag) {\n              throw new Error("unexpected DER tag");\n            }\n            let length = this.bytes[this.offset++];\n            if (length & 128) {\n              const count = length & 127;\n              if (count === 0 || count > 4 || this.offset + count > this.bytes.length) {\n                throw new Error("invalid DER length");\n              }\n              length = 0;\n              for (let i = 0; i < count; ++i) {\n                length = length << 8 | this.bytes[this.offset++];\n              }\n            }\n            if (this.offset + length > this.bytes.length) {\n              throw new Error("truncated DER value");\n            }\n            const body = this.bytes.slice(this.offset, this.offset + length);\n            this.offset += length;\n            return body;\n          }\n        };\n      }\n      function derIntegerToFixed(integer, length) {\n        let value = integer;\n        while (value.length > 0 && value[0] === 0) {\n          value = value.slice(1);\n        }\n        if (value.length > length) {\n          throw new Error("ECDSA integer too long");\n        }\n        const out = new Uint8Array(length);\n        out.set(value, length - value.length);\n        return out;\n      }\n      function derToEcdsaRawSignature(signature, algorithm) {\n        const meta = signingMeta(algorithm);\n        const reader = derReader(signature);\n        const seqReader = derReader(reader.readElement(48));\n        const r = derIntegerToFixed(\n          seqReader.readElement(2),\n          meta.signatureLength / 2\n        );\n        const s = derIntegerToFixed(\n          seqReader.readElement(2),\n          meta.signatureLength / 2\n        );\n        if (reader.offset !== signature.length || seqReader.offset !== seqReader.bytes.length) {\n          throw new Error("trailing DER data");\n        }\n        return concatBytes(r, s);\n      }\n      function ecdsaIntegerFromRaw(bytes) {\n        let value = bytes;\n        while (value.length > 0 && value[0] === 0) {\n          value = value.slice(1);\n        }\n        if (value.length === 0) {\n          value = Uint8Array.of(0);\n        }\n        if (value[0] & 128) {\n          value = concatBytes(Uint8Array.of(0), value);\n        }\n        return derElement(2, value);\n      }\n      function ecdsaRawSignatureToDer(signature) {\n        const half = signature.length / 2;\n        return derSequence(\n          ecdsaIntegerFromRaw(signature.slice(0, half)),\n          ecdsaIntegerFromRaw(signature.slice(half))\n        );\n      }\n      function algorithmFromJwk(jwk, label) {\n        if (jwk.kty === "OKP" && jwk.crv === "Ed25519") {\n          return "ed25519";\n        }\n        if (jwk.kty === "OKP" && jwk.crv === "X25519") {\n          return "x25519";\n        }\n        if (jwk.kty === "EC" && jwk.crv === "P-256") {\n          return "ecdsa-p256-sha256";\n        }\n        if (jwk.kty === "EC" && jwk.crv === "P-384") {\n          return "ecdsa-p384-sha384";\n        }\n        throw new Error(`${label} expects an Ed25519, P-256, P-384, or X25519 key`);\n      }\n      function algorithmFromNodeKey(key, label) {\n        if (key.asymmetricKeyType === "ed25519") {\n          return "ed25519";\n        }\n        if (key.asymmetricKeyType === "ec") {\n          const curve = key.asymmetricKeyDetails?.namedCurve;\n          if (curve === "prime256v1") {\n            return "ecdsa-p256-sha256";\n          }\n          if (curve === "secp384r1") {\n            return "ecdsa-p384-sha384";\n          }\n        }\n        if (key.asymmetricKeyType === "x25519") {\n          return "x25519";\n        }\n        return algorithmFromJwk(key.export({ format: "jwk" }), label);\n      }\n      function rawPublicFromJwk(jwk, label) {\n        const algorithm = algorithmFromJwk(jwk, label);\n        if (algorithm === "ed25519") {\n          return base64urlDecode(jwk.x);\n        }\n        if (algorithm === "x25519") {\n          const x2 = base64urlDecode(jwk.x);\n          if (!x2 || x2.length !== 32) {\n            throw new Error(`${label} has invalid X25519 public key`);\n          }\n          return x2;\n        }\n        const x = base64urlDecode(jwk.x);\n        const y = base64urlDecode(jwk.y);\n        const meta = signingMeta(algorithm);\n        const width = (meta.publicLength - 1) / 2;\n        if (!x || !y || x.length !== width || y.length !== width) {\n          throw new Error(`${label} has invalid EC public key coordinates`);\n        }\n        return concatBytes(Uint8Array.of(4), x, y);\n      }\n      function rawPrivateFromJwk(jwk, label) {\n        const algorithm = algorithmFromJwk(jwk, label);\n        const d = base64urlDecode(jwk.d);\n        if (algorithm === "x25519") {\n          if (!d || d.length !== 32) {\n            throw new Error(`${label} has invalid X25519 private key`);\n          }\n          return d;\n        }\n        if (!d || d.length !== signingMeta(algorithm).privateLength) {\n          throw new Error(`${label} has invalid private key scalar`);\n        }\n        return d;\n      }\n      function jwkFromRawPrivate(bytes, algorithm, label) {\n        const meta = signingMeta(algorithm);\n        if (bytes.length !== meta.privateLength) {\n          throw new Error(`${label} expects a ${meta.privateLength}-byte raw private key`);\n        }\n        if (meta.type === "ed25519") {\n          return {\n            kty: "OKP",\n            crv: "Ed25519",\n            d: base64url(bytes)\n          };\n        }\n        return null;\n      }\n      function jwkFromRawPublic(bytes, algorithm, label) {\n        const meta = signingMeta(algorithm);\n        if (bytes.length !== meta.publicLength) {\n          throw new Error(`${label} expects a ${meta.publicLength}-byte raw public key`);\n        }\n        if (meta.type === "ed25519") {\n          return { kty: "OKP", crv: "Ed25519", x: base64url(bytes) };\n        }\n        if (bytes[0] !== 4) {\n          throw new Error(`${label} expects an uncompressed EC public key`);\n        }\n        const width = (meta.publicLength - 1) / 2;\n        return {\n          kty: "EC",\n          crv: meta.jwkCurve,\n          x: base64url(bytes.slice(1, 1 + width)),\n          y: base64url(bytes.slice(1 + width))\n        };\n      }\n      function algorithmFromRawPublic(bytes, label) {\n        if (bytes.length === 32) {\n          return "ed25519";\n        }\n        if (bytes.length === 65 && bytes[0] === 4) {\n          return "ecdsa-p256-sha256";\n        }\n        if (bytes.length === 97 && bytes[0] === 4) {\n          return "ecdsa-p384-sha384";\n        }\n        throw new Error(\n          `${label} expects a 32-byte Ed25519 key, 65-byte P-256 public key, or 97-byte P-384 public key`\n        );\n      }\n      function nodePrivateKeyFromRaw(key, algorithm, label) {\n        const bytes = assertBinaryString(key, label, "BinaryString key");\n        const meta = signingMeta(algorithm);\n        if (bytes.length !== meta.privateLength) {\n          throw new Error(`${label} expects a ${meta.privateLength}-byte raw private key`);\n        }\n        const crypto = nodeCrypto();\n        if (!crypto || typeof crypto.createPrivateKey !== "function") {\n          nodeUnsupported(label);\n        }\n        if (meta.type === "ed25519") {\n          return crypto.createPrivateKey({\n            key: Buffer.from(pkcs8DerFromRawSeed(bytes)),\n            format: "der",\n            type: "pkcs8"\n          });\n        }\n        return crypto.createPrivateKey({\n          key: Buffer.from(ecdsaPkcs8DerFromRawScalar(bytes, algorithm)),\n          format: "der",\n          type: "pkcs8"\n        });\n      }\n      function nodePublicKeyFromRaw(key, algorithm, label) {\n        const bytes = assertBinaryString(key, label, "BinaryString key");\n        const crypto = nodeCrypto();\n        if (!crypto || typeof crypto.createPublicKey !== "function") {\n          nodeUnsupported(label);\n        }\n        return crypto.createPublicKey({\n          key: jwkFromRawPublic(bytes, algorithm, label),\n          format: "jwk"\n        });\n      }\n      function x25519PrivateBytes(key, label) {\n        const bytes = assertBinaryString(key, label, "BinaryString key");\n        if (bytes.length !== 32) {\n          throw new Error(`${label} expects a 32-byte raw private key`);\n        }\n        return bytes;\n      }\n      function x25519PublicBytes(key, label) {\n        const bytes = assertBinaryString(key, label, "BinaryString key");\n        if (bytes.length !== 32) {\n          throw new Error(`${label} expects a 32-byte raw public key`);\n        }\n        return bytes;\n      }\n      function nodeX25519PrivateKeyFromRaw(key, label) {\n        const bytes = x25519PrivateBytes(key, label);\n        const crypto = nodeCrypto();\n        if (!crypto || typeof crypto.createPrivateKey !== "function") {\n          keyAgreementUnsupported(label);\n        }\n        return crypto.createPrivateKey({\n          key: Buffer.from(x25519Pkcs8DerFromRawPrivate(bytes)),\n          format: "der",\n          type: "pkcs8"\n        });\n      }\n      function nodeX25519PublicKeyFromRaw(key, label) {\n        const bytes = x25519PublicBytes(key, label);\n        const crypto = nodeCrypto();\n        if (!crypto || typeof crypto.createPublicKey !== "function") {\n          keyAgreementUnsupported(label);\n        }\n        return crypto.createPublicKey({\n          key: Buffer.from(x25519SpkiDerFromRawPublic(bytes)),\n          format: "der",\n          type: "spki"\n        });\n      }\n      function syncBrowserSigningError(label, asyncName) {\n        throw new Error(\n          `${label} is not available synchronously on host browser; use ${asyncName}`\n        );\n      }\n      function syncBrowserKeyAgreementError(label, asyncName) {\n        throw new Error(\n          `${label} is not available synchronously on host browser; use ${asyncName}`\n        );\n      }\n      function browserSigningUnsupported(label) {\n        throw new Error(`${label} signing is unavailable on this host`);\n      }\n      function subtleSigningCrypto() {\n        return globalThis.crypto && globalThis.crypto.subtle && typeof globalThis.crypto.subtle.generateKey === "function" && typeof globalThis.crypto.subtle.importKey === "function" && typeof globalThis.crypto.subtle.exportKey === "function" && typeof globalThis.crypto.subtle.sign === "function" && typeof globalThis.crypto.subtle.verify === "function" ? globalThis.crypto.subtle : null;\n      }\n      function subtleKeyAgreementCrypto() {\n        return globalThis.crypto && globalThis.crypto.subtle && typeof globalThis.crypto.subtle.generateKey === "function" && typeof globalThis.crypto.subtle.importKey === "function" && typeof globalThis.crypto.subtle.exportKey === "function" && typeof globalThis.crypto.subtle.deriveBits === "function" ? globalThis.crypto.subtle : null;\n      }\n      var X509_OIDS = {\n        "2.5.4.3": "CN",\n        "2.5.4.6": "C",\n        "2.5.4.7": "L",\n        "2.5.4.8": "ST",\n        "2.5.4.10": "O",\n        "2.5.4.11": "OU",\n        "1.2.840.10045.2.1": "ecPublicKey",\n        "1.2.840.10045.3.1.7": "prime256v1",\n        "1.3.132.0.34": "secp384r1",\n        "1.3.101.112": "ed25519"\n      };\n      function derError(label) {\n        throw new Error(`${label} expects DER X.509 certificate data`);\n      }\n      function x509DerReader(bytes, label) {\n        return {\n          bytes,\n          offset: 0,\n          readElement(expectedTag = null) {\n            if (this.offset + 2 > this.bytes.length) {\n              derError(label);\n            }\n            const start = this.offset;\n            const tag = this.bytes[this.offset++];\n            if (expectedTag != null && tag !== expectedTag) {\n              derError(label);\n            }\n            let length = this.bytes[this.offset++];\n            if (length & 128) {\n              const count = length & 127;\n              if (count === 0 || count > 4 || this.offset + count > this.bytes.length) {\n                derError(label);\n              }\n              length = 0;\n              for (let i = 0; i < count; ++i) {\n                length = length << 8 | this.bytes[this.offset++];\n              }\n            }\n            if (this.offset + length > this.bytes.length) {\n              derError(label);\n            }\n            const headerLength = this.offset - start;\n            const body = this.bytes.slice(this.offset, this.offset + length);\n            const raw = this.bytes.slice(start, this.offset + length);\n            this.offset += length;\n            return { tag, body, raw, headerLength };\n          },\n          readBody(expectedTag = null) {\n            return this.readElement(expectedTag).body;\n          },\n          empty() {\n            return this.offset >= this.bytes.length;\n          }\n        };\n      }\n      function oidFromDer(bytes) {\n        if (bytes.length === 0) {\n          return "";\n        }\n        const parts = [Math.floor(bytes[0] / 40), bytes[0] % 40];\n        let value = 0;\n        for (let i = 1; i < bytes.length; ++i) {\n          value = value << 7 | bytes[i] & 127;\n          if ((bytes[i] & 128) === 0) {\n            parts.push(value);\n            value = 0;\n          }\n        }\n        return parts.join(".");\n      }\n      function x509TextValue(tag, body) {\n        if (tag === 12 || tag === 19 || tag === 22 || tag === 20) {\n          return new TextDecoder().decode(body);\n        }\n        if (tag === 30) {\n          let out = "";\n          for (let i = 0; i + 1 < body.length; i += 2) {\n            out += String.fromCharCode(body[i] << 8 | body[i + 1]);\n          }\n          return out;\n        }\n        return Array.from(body, (byte) => byte.toString(16).padStart(2, "0")).join("").toUpperCase();\n      }\n      function x509NameString(bytes, label) {\n        const seq = x509DerReader(bytes, label);\n        const parts = [];\n        while (!seq.empty()) {\n          const set = x509DerReader(seq.readBody(49), label);\n          while (!set.empty()) {\n            const attr = x509DerReader(set.readBody(48), label);\n            const oid = oidFromDer(attr.readBody(6));\n            const value = attr.readElement();\n            const name2 = X509_OIDS[oid] || oid;\n            parts.push(`${name2}=${x509TextValue(value.tag, value.body)}`);\n          }\n        }\n        return parts.join(", ");\n      }\n      function x509SerialHex(bytes) {\n        let value = bytes;\n        while (value.length > 1 && value[0] === 0) {\n          value = value.slice(1);\n        }\n        return Array.from(value, (byte) => byte.toString(16).padStart(2, "0")).join("").toUpperCase();\n      }\n      function x509TimeEpoch(element, label) {\n        const text = new TextDecoder().decode(element.body);\n        let year;\n        let month;\n        let day;\n        let hour;\n        let minute;\n        let second;\n        if (element.tag === 23) {\n          const match = text.match(/^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/u);\n          if (!match) {\n            derError(label);\n          }\n          year = Number(match[1]);\n          year += year >= 50 ? 1900 : 2e3;\n          month = Number(match[2]);\n          day = Number(match[3]);\n          hour = Number(match[4]);\n          minute = Number(match[5]);\n          second = Number(match[6]);\n        } else if (element.tag === 24) {\n          const match = text.match(/^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/u);\n          if (!match) {\n            derError(label);\n          }\n          year = Number(match[1]);\n          month = Number(match[2]);\n          day = Number(match[3]);\n          hour = Number(match[4]);\n          minute = Number(match[5]);\n          second = Number(match[6]);\n        } else {\n          derError(label);\n        }\n        return Math.floor(Date.UTC(year, month - 1, day, hour, minute, second) / 1e3);\n      }\n      function x509BitStringPayload(bytes, label) {\n        if (bytes.length === 0 || bytes[0] !== 0) {\n          derError(label);\n        }\n        return bytes.slice(1);\n      }\n      function x509Spki(bytes, label) {\n        const seq = x509DerReader(bytes, label);\n        const alg = x509DerReader(seq.readBody(48), label);\n        const algOid = oidFromDer(alg.readBody(6));\n        let curveOid = null;\n        if (!alg.empty()) {\n          const param = alg.readElement();\n          if (param.tag === 6) {\n            curveOid = oidFromDer(param.body);\n          }\n        }\n        const publicBytes = x509BitStringPayload(seq.readBody(3), label);\n        return { algOid, curveOid, publicBytes };\n      }\n      function parseX509Der(der, label = "Certificate.parse") {\n        const bytes = Uint8Array.from(der);\n        const cert = x509DerReader(bytes, label);\n        const certSeq = x509DerReader(cert.readBody(48), label);\n        const tbs = x509DerReader(certSeq.readBody(48), label);\n        if (!cert.empty()) {\n          derError(label);\n        }\n        if (!tbs.empty()) {\n          const next = tbs.readElement();\n          if (next.tag !== 160) {\n            tbs.offset = 0;\n          }\n        }\n        const serial = x509SerialHex(tbs.readBody(2));\n        tbs.readElement(48);\n        const issuer = x509NameString(tbs.readBody(48), label);\n        const validity = x509DerReader(tbs.readBody(48), label);\n        const notBefore = x509TimeEpoch(validity.readElement(), label);\n        const notAfter = x509TimeEpoch(validity.readElement(), label);\n        const subject = x509NameString(tbs.readBody(48), label);\n        const spki = x509Spki(tbs.readBody(48), label);\n        return new Certificate(new SecureCertificate(\n          bytes,\n          subject,\n          issuer,\n          serial,\n          notBefore,\n          notAfter,\n          spki\n        ));\n      }\n      var SecureCertificate = class {\n        constructor(der, subject, issuer, serial, notBefore, notAfter, spki) {\n          this.der = der;\n          this.subject = subject;\n          this.issuer = issuer;\n          this.serial = serial;\n          this.notBefore = notBefore;\n          this.notAfter = notAfter;\n          this.spki = spki;\n        }\n      };\n      var SecureTlsIdentity = class {\n        constructor(certPem, keyPem, password = "", source = "pem", chainPem = certPem) {\n          this.certPem = certPem;\n          this.keyPem = keyPem;\n          this.password = password;\n          this.source = source;\n          this.chainPem = chainPem;\n        }\n      };\n      var SecureKeyAgreement = class {\n        constructor(algorithm, key, publicKey = null, rawPrivate = null, rawPublic = null) {\n          this.algorithm = algorithm;\n          this.key = key;\n          this.publicKey = publicKey;\n          this.rawPrivate = rawPrivate;\n          this.rawPublic = rawPublic;\n        }\n      };\n      var SecureSigningKey = class {\n        constructor(algorithm, key, publicKey = null, rawPrivate = null, rawPublic = null) {\n          this.algorithm = algorithm;\n          this.key = key;\n          this.publicKey = publicKey;\n          this.rawPrivate = rawPrivate;\n          this.rawPublic = rawPublic;\n        }\n      };\n      var SecurePublicKey = class {\n        constructor(algorithm, key, rawPublic = null) {\n          this.algorithm = algorithm;\n          this.key = key;\n          this.rawPublic = rawPublic;\n        }\n      };\n      function signingGenerate(algorithm = "ed25519") {\n        algorithm = signingAlgorithm(algorithm, "SigningKey.generate");\n        if (hostName() === "browser") {\n          syncBrowserSigningError(\n            "SigningKey.generate",\n            "SigningKey.generate_async"\n          );\n        }\n        const crypto = nodeCrypto();\n        if (!crypto || typeof crypto.generateKeyPairSync !== "function") {\n          nodeUnsupported("SigningKey.generate");\n        }\n        const meta = signingMeta(algorithm);\n        const pair = meta.type === "ed25519" ? crypto.generateKeyPairSync("ed25519") : crypto.generateKeyPairSync("ec", { namedCurve: meta.nodeCurve });\n        return new SigningKey(new SecureSigningKey(algorithm, pair.privateKey));\n      }\n      async function browserSigningKeyFromPair(algorithm, pair) {\n        const privateJwk = await globalThis.crypto.subtle.exportKey(\n          "jwk",\n          pair.privateKey\n        );\n        const publicJwk = await globalThis.crypto.subtle.exportKey(\n          "jwk",\n          pair.publicKey\n        );\n        return new SigningKey(new SecureSigningKey(\n          algorithm,\n          pair.privateKey,\n          pair.publicKey,\n          rawPrivateFromJwk(privateJwk, "SigningKey.generate_async"),\n          rawPublicFromJwk(publicJwk, "SigningKey.generate_async")\n        ));\n      }\n      async function signingGenerateAsyncValue(algorithm = "ed25519") {\n        algorithm = signingAlgorithm(algorithm, "SigningKey.generate");\n        if (hostName() !== "browser") {\n          return signingGenerate(algorithm);\n        }\n        browserSigningAlgorithm(algorithm, "SigningKey.generate_async");\n        const subtle = subtleSigningCrypto();\n        if (!subtle) {\n          browserSigningUnsupported("SigningKey.generate_async");\n        }\n        const meta = signingMeta(algorithm);\n        try {\n          const pair = await subtle.generateKey(\n            meta.type === "ed25519" ? { name: "Ed25519" } : { name: "ECDSA", namedCurve: meta.webCurve },\n            true,\n            ["sign", "verify"]\n          );\n          return await browserSigningKeyFromPair(algorithm, pair);\n        } catch (_err) {\n          browserSigningUnsupported("SigningKey.generate_async");\n        }\n      }\n      function signingImportPrivate(key, options = null) {\n        const label = "SigningKey.import_private";\n        if (hostName() === "browser") {\n          syncBrowserSigningError(label, "SigningKey.import_private_async");\n        }\n        const opts = optionalDict(options, label, "Dict options");\n        const format = keyFormat(key, options, label);\n        const crypto = nodeCrypto();\n        if (!crypto || typeof crypto.createPrivateKey !== "function") {\n          nodeUnsupported(label);\n        }\n        let algorithm = signingAlgorithmOption(opts, label);\n        let keyObject;\n        if (format === "raw") {\n          algorithm ??= "ed25519";\n          keyObject = nodePrivateKeyFromRaw(key, algorithm, label);\n        } else if (format === "pem") {\n          const pem = assertString(key, label, "String key");\n          const password = opts.password == null ? null : String(opts.password);\n          keyObject = crypto.createPrivateKey(\n            password == null ? pem : { key: pem, passphrase: password }\n          );\n          const actual = algorithmFromNodeKey(keyObject, label);\n          if (algorithm && actual !== algorithm) {\n            throw new Error(`${label} PEM key algorithm does not match ${algorithm}`);\n          }\n          algorithm = actual;\n        } else {\n          throw new Error(`${label} only supports raw and pem formats`);\n        }\n        return new SigningKey(new SecureSigningKey(algorithm, keyObject));\n      }\n      async function signingImportPrivateAsyncValue(key, options = null) {\n        const label = "SigningKey.import_private";\n        if (hostName() !== "browser") {\n          return signingImportPrivate(key, options);\n        }\n        const subtle = subtleSigningCrypto();\n        if (!subtle) {\n          browserSigningUnsupported(`${label}_async`);\n        }\n        const opts = optionalDict(options, label, "Dict options");\n        const format = keyFormat(key, options, label);\n        let algorithm = signingAlgorithmOption(opts, label);\n        let der;\n        if (format === "raw") {\n          const bytes = assertBinaryString(key, label, "BinaryString key");\n          algorithm ??= "ed25519";\n          browserSigningAlgorithm(algorithm, `${label}_async`);\n          const meta = signingMeta(algorithm);\n          if (bytes.length !== meta.privateLength) {\n            throw new Error(`${label} expects a ${meta.privateLength}-byte raw private key`);\n          }\n          der = meta.type === "ed25519" ? pkcs8DerFromRawSeed(bytes) : ecdsaPkcs8DerFromRawScalar(bytes, algorithm);\n        } else if (format === "pem") {\n          der = pemToDer(key, label);\n          if (algorithm) {\n            browserSigningAlgorithm(algorithm, `${label}_async`);\n          }\n        } else {\n          throw new Error(`${label} only supports raw and pem formats`);\n        }\n        try {\n          let cryptoKey = null;\n          let jwk = null;\n          const candidates = algorithm ? [algorithm] : signingCapabilities();\n          for (const candidate of candidates) {\n            const meta = signingMeta(candidate);\n            try {\n              cryptoKey = await subtle.importKey(\n                "pkcs8",\n                der,\n                meta.type === "ed25519" ? { name: "Ed25519" } : { name: "ECDSA", namedCurve: meta.webCurve },\n                true,\n                ["sign"]\n              );\n              jwk = await subtle.exportKey("jwk", cryptoKey);\n              algorithm = algorithmFromJwk(jwk, label);\n              break;\n            } catch (_err) {\n              cryptoKey = null;\n            }\n          }\n          if (!cryptoKey) {\n            browserSigningUnsupported(`${label}_async`);\n          }\n          const rawPublic = rawPublicFromJwk(jwk, label);\n          const publicKey = await subtle.importKey(\n            signingMeta(algorithm).type === "ed25519" ? "raw" : "jwk",\n            signingMeta(algorithm).type === "ed25519" ? rawPublic : jwkFromRawPublic(rawPublic, algorithm, label),\n            signingMeta(algorithm).type === "ed25519" ? { name: "Ed25519" } : { name: "ECDSA", namedCurve: signingMeta(algorithm).webCurve },\n            true,\n            ["verify"]\n          );\n          return new SigningKey(new SecureSigningKey(\n            algorithm,\n            cryptoKey,\n            publicKey,\n            rawPrivateFromJwk(jwk, label),\n            rawPublic\n          ));\n        } catch (_err) {\n          browserSigningUnsupported(`${label}_async`);\n        }\n      }\n      function signingImportPublic(key, options = null) {\n        const label = "SigningKey.import_public";\n        if (hostName() === "browser") {\n          syncBrowserSigningError(label, "SigningKey.import_public_async");\n        }\n        const opts = optionalDict(options, label, "Dict options");\n        const format = keyFormat(key, options, label);\n        const crypto = nodeCrypto();\n        if (!crypto || typeof crypto.createPublicKey !== "function") {\n          nodeUnsupported(label);\n        }\n        let algorithm = signingAlgorithmOption(opts, label);\n        let keyObject;\n        if (format === "raw") {\n          const bytes = assertBinaryString(key, label, "BinaryString key");\n          algorithm ??= algorithmFromRawPublic(bytes, label);\n          keyObject = nodePublicKeyFromRaw(key, algorithm, label);\n        } else if (format === "pem") {\n          keyObject = crypto.createPublicKey(assertString(key, label, "String key"));\n          const actual = algorithmFromNodeKey(keyObject, label);\n          if (algorithm && actual !== algorithm) {\n            throw new Error(`${label} PEM key algorithm does not match ${algorithm}`);\n          }\n          algorithm = actual;\n        } else {\n          throw new Error(`${label} only supports raw and pem formats`);\n        }\n        return new PublicKey(new SecurePublicKey(algorithm, keyObject));\n      }\n      async function signingImportPublicAsyncValue(key, options = null) {\n        const label = "SigningKey.import_public";\n        if (hostName() !== "browser") {\n          return signingImportPublic(key, options);\n        }\n        const subtle = subtleSigningCrypto();\n        if (!subtle) {\n          browserSigningUnsupported(`${label}_async`);\n        }\n        const opts = optionalDict(options, label, "Dict options");\n        const format = keyFormat(key, options, label);\n        let algorithm = signingAlgorithmOption(opts, label);\n        let importData;\n        let importFormat;\n        if (format === "raw") {\n          importData = assertBinaryString(key, label, "BinaryString key");\n          algorithm ??= algorithmFromRawPublic(importData, label);\n          browserSigningAlgorithm(algorithm, `${label}_async`);\n          importFormat = signingMeta(algorithm).type === "ed25519" ? "raw" : "jwk";\n          if (importFormat === "jwk") {\n            importData = jwkFromRawPublic(importData, algorithm, label);\n          }\n        } else if (format === "pem") {\n          importData = pemToDer(key, label);\n          importFormat = "spki";\n          if (algorithm) {\n            browserSigningAlgorithm(algorithm, `${label}_async`);\n          }\n        } else {\n          throw new Error(`${label} only supports raw and pem formats`);\n        }\n        try {\n          let cryptoKey = null;\n          let jwk = null;\n          const candidates = algorithm ? [algorithm] : signingCapabilities();\n          for (const candidate of candidates) {\n            const meta = signingMeta(candidate);\n            try {\n              cryptoKey = await subtle.importKey(\n                importFormat,\n                importData,\n                meta.type === "ed25519" ? { name: "Ed25519" } : { name: "ECDSA", namedCurve: meta.webCurve },\n                true,\n                ["verify"]\n              );\n              jwk = await subtle.exportKey("jwk", cryptoKey);\n              algorithm = algorithmFromJwk(jwk, label);\n              break;\n            } catch (_err) {\n              cryptoKey = null;\n            }\n          }\n          if (!cryptoKey) {\n            browserSigningUnsupported(`${label}_async`);\n          }\n          return new PublicKey(new SecurePublicKey(\n            algorithm,\n            cryptoKey,\n            rawPublicFromJwk(jwk, label)\n          ));\n        } catch (_err) {\n          browserSigningUnsupported(`${label}_async`);\n        }\n      }\n      function signingPublicKey(signingKey) {\n        const secure = signingKey.__secureSigningKey;\n        if (hostName() === "browser") {\n          if (secure.publicKey && secure.rawPublic) {\n            return new PublicKey(new SecurePublicKey(\n              secure.algorithm,\n              secure.publicKey,\n              secure.rawPublic\n            ));\n          }\n          throw new Error(\n            "SigningKey.public_key is unavailable for this browser key"\n          );\n        }\n        const crypto = nodeCrypto();\n        return new PublicKey(new SecurePublicKey(\n          secure.algorithm,\n          crypto.createPublicKey(secure.key)\n        ));\n      }\n      function signingSign(signingKey, message) {\n        const label = "SigningKey.sign";\n        if (hostName() === "browser") {\n          syncBrowserSigningError(label, "SigningKey.sign_async");\n        }\n        const bytes = assertBinaryString(message, label, "BinaryString message");\n        const crypto = nodeCrypto();\n        if (!crypto || typeof crypto.sign !== "function") {\n          nodeUnsupported(label);\n        }\n        const meta = signingMeta(signingKey.__secureSigningKey.algorithm);\n        return new BinaryString(\n          new Uint8Array(crypto.sign(meta.nodeHash ?? null, bytes, signingKey.__secureSigningKey.key))\n        );\n      }\n      async function signingSignAsyncValue(signingKey, message) {\n        const label = "SigningKey.sign";\n        const bytes = assertBinaryString(message, label, "BinaryString message");\n        if (hostName() !== "browser") {\n          return signingSign(signingKey, message);\n        }\n        const subtle = subtleSigningCrypto();\n        if (!subtle) {\n          browserSigningUnsupported(`${label}_async`);\n        }\n        const meta = signingMeta(signingKey.__secureSigningKey.algorithm);\n        try {\n          const rawSignature = new Uint8Array(await subtle.sign(\n            meta.type === "ed25519" ? { name: "Ed25519" } : { name: "ECDSA", hash: meta.webHash },\n            signingKey.__secureSigningKey.key,\n            bytes\n          ));\n          return new BinaryString(\n            meta.type === "ed25519" ? rawSignature : ecdsaRawSignatureToDer(rawSignature)\n          );\n        } catch (_err) {\n          browserSigningUnsupported(`${label}_async`);\n        }\n      }\n      function signingExportPrivate(signingKey, optionsValue = null) {\n        const label = "SigningKey.export_private";\n        const options = optionalDict(optionsValue, label, "Dict options");\n        const format = options.format == null ? "raw" : String(options.format);\n        const secure = signingKey.__secureSigningKey;\n        if (format === "raw") {\n          if (secure.rawPrivate) {\n            return new BinaryString(secure.rawPrivate);\n          }\n          return new BinaryString(\n            rawPrivateFromJwk(secure.key.export({ format: "jwk" }), label)\n          );\n        }\n        if (format === "pem") {\n          if (hostName() !== "browser") {\n            return String(secure.key.export({\n              format: "pem",\n              type: "pkcs8"\n            }));\n          }\n          const meta = signingMeta(secure.algorithm);\n          const der = meta.type === "ed25519" ? pkcs8DerFromRawSeed(secure.rawPrivate) : ecdsaPkcs8DerFromRawScalar(secure.rawPrivate, secure.algorithm);\n          return derToPem("PRIVATE KEY", der);\n        }\n        throw new Error(`${label} only supports raw and pem formats`);\n      }\n      function certificateParse(input) {\n        const label = "Certificate.parse";\n        if (input && input.bytes instanceof Uint8Array) {\n          return parseX509Der(input.bytes, label);\n        }\n        if (hostName() === "browser") {\n          throw new Error(`${label} only supports DER BinaryString on host browser`);\n        }\n        return parseX509Der(certificatePemBlocks(input, label)[0], label);\n      }\n      function certificateParseChain(input) {\n        const label = "Certificate.parse_chain";\n        if (input && input.bytes instanceof Uint8Array) {\n          return [parseX509Der(input.bytes, label)];\n        }\n        if (hostName() === "browser") {\n          throw new Error(`${label} only supports DER BinaryString on host browser`);\n        }\n        return certificatePemBlocks(input, label).map((der) => parseX509Der(der, label));\n      }\n      function certificateState(certificate, label) {\n        if (!(certificate instanceof Certificate)) {\n          throw new Error(`TypeException: ${label} expects Certificate`);\n        }\n        return certificate.__secureCertificate;\n      }\n      function certificateFingerprint(certificate, algorithm) {\n        const label = "Certificate.fingerprint";\n        const state = certificateState(certificate, label);\n        const value = algorithm == null ? "sha256" : String(algorithm).toLowerCase();\n        if (value !== "sha256") {\n          throw new Error(`${label} only supports sha256`);\n        }\n        return new BinaryString(\n          digestBytes("sha256", new BinaryString(state.der), label)\n        );\n      }\n      function certificatePublicKey(certificate) {\n        const label = "Certificate.public_key";\n        if (hostName() === "browser") {\n          throw new Error(`${label} is not supported on host browser`);\n        }\n        const state = certificateState(certificate, label);\n        const { algOid, curveOid, publicBytes } = state.spki;\n        if (algOid === "1.3.101.112") {\n          const raw = Uint8Array.from(publicBytes);\n          return new PublicKey(new SecurePublicKey(\n            "ed25519",\n            nodePublicKeyFromRaw(new BinaryString(raw), "ed25519", label),\n            raw\n          ));\n        }\n        if (algOid === "1.2.840.10045.2.1" && curveOid === "1.2.840.10045.3.1.7") {\n          const raw = Uint8Array.from(publicBytes);\n          return new PublicKey(new SecurePublicKey(\n            "ecdsa-p256-sha256",\n            nodePublicKeyFromRaw(\n              new BinaryString(raw),\n              "ecdsa-p256-sha256",\n              label\n            ),\n            raw\n          ));\n        }\n        if (algOid === "1.2.840.10045.2.1" && curveOid === "1.3.132.0.34") {\n          const raw = Uint8Array.from(publicBytes);\n          return new PublicKey(new SecurePublicKey(\n            "ecdsa-p384-sha384",\n            nodePublicKeyFromRaw(\n              new BinaryString(raw),\n              "ecdsa-p384-sha384",\n              label\n            ),\n            raw\n          ));\n        }\n        throw new Error(`${label} certificate public-key algorithm is unsupported`);\n      }\n      function certificateVerifyChain(chain, options = null) {\n        const label = "Certificate.verify_chain";\n        if (hostName() === "browser") {\n          throw new Error(`${label} is not supported on host browser`);\n        }\n        if (!Array.isArray(chain) || chain.length === 0) {\n          throw new Error(`TypeException: ${label} expects non-empty Array chain`);\n        }\n        const states = chain.map((certificate) => certificateState(certificate, label));\n        const opts = certificateVerifyOptions(options, label);\n        const crypto = nodeCrypto();\n        if (!crypto || typeof crypto.X509Certificate !== "function") {\n          throw new Error(`${label} requires X509Certificate support on host node`);\n        }\n        const rootCerts = certificateRootNodeCerts(opts.roots, crypto, label);\n        if (opts.use_system_roots) {\n          const tls = nodeTls();\n          if (tls && Array.isArray(tls.rootCertificates)) {\n            for (const pem of tls.rootCertificates) {\n              rootCerts.push(new crypto.X509Certificate(pem));\n            }\n          }\n        }\n        const nodeChain = states.map(\n          (state) => new crypto.X509Certificate(Buffer.from(state.der))\n        );\n        const verifiedAt = opts.time;\n        let valid = true;\n        let error = null;\n        error = certificateVerifyNodeChain(nodeChain, rootCerts, verifiedAt);\n        valid = error == null;\n        let reason = valid ? "ok" : certificateVerifyReason(error);\n        if (valid && opts.hostname != null) {\n          if (!certificateHostnameMatches(states[0], opts.hostname)) {\n            valid = false;\n            reason = "hostname-mismatch";\n            error = "hostname mismatch";\n          }\n        }\n        return {\n          valid,\n          reason,\n          error: valid ? null : error,\n          hostname: opts.hostname,\n          verified_at: verifiedAt,\n          chain_length: chain.length\n        };\n      }\n      function certificateVerifyOptions(options, label) {\n        if (options == null) {\n          options = {};\n        }\n        if (typeof options !== "object" || Array.isArray(options)) {\n          throw new Error(`TypeException: ${label} expects Dict options`);\n        }\n        const useSystemRoots = options.use_system_roots == null ? false : options.use_system_roots;\n        if (typeof useSystemRoots !== "boolean") {\n          throw new Error(\n            `TypeException: ${label} option \'use_system_roots\' expects Boolean`\n          );\n        }\n        let hostname = options.hostname == null ? null : options.hostname;\n        if (hostname != null && typeof hostname !== "string") {\n          throw new Error(`TypeException: ${label} option \'hostname\' expects String`);\n        }\n        let time = options.time;\n        if (time == null) {\n          time = Math.floor(Date.now() / 1e3);\n        } else if (time instanceof Time) {\n          time = time.epoch();\n        } else if (typeof time === "number") {\n          time = Math.floor(time);\n        } else {\n          throw new Error(\n            `TypeException: ${label} option \'time\' expects Time, Number, or null`\n          );\n        }\n        return {\n          roots: options.roots,\n          use_system_roots: useSystemRoots,\n          hostname,\n          time\n        };\n      }\n      function certificateRootNodeCerts(value, crypto, label) {\n        if (value == null) {\n          return [];\n        }\n        if (value instanceof Certificate) {\n          const state = certificateState(value, label);\n          return [new crypto.X509Certificate(Buffer.from(state.der))];\n        }\n        if (typeof value === "string") {\n          return certificatePemBlocks(value, label).map((der) => new crypto.X509Certificate(Buffer.from(der)));\n        }\n        if (Array.isArray(value)) {\n          return value.flatMap(\n            (item) => certificateRootNodeCerts(item, crypto, label)\n          );\n        }\n        throw new Error(\n          `TypeException: ${label} expects roots to be Certificate, String PEM, Array, or null`\n        );\n      }\n      function certificateVerifyNodeChain(chain, roots, verifiedAt) {\n        const verifiedDate = new Date(verifiedAt * 1e3);\n        for (const cert of chain) {\n          const notBefore = new Date(cert.validFrom);\n          const notAfter = new Date(cert.validTo);\n          if (verifiedDate < notBefore) {\n            return "certificate is not yet valid";\n          }\n          if (verifiedDate > notAfter) {\n            return "certificate has expired";\n          }\n        }\n        for (let i = 0; i < chain.length; i++) {\n          const child = chain[i];\n          const issuer = chain[i + 1] || roots.find(\n            (root) => child.checkIssued(root) && child.verify(root.publicKey)\n          );\n          if (!issuer) {\n            return "certificate is not trusted";\n          }\n          if (!child.checkIssued(issuer) || !child.verify(issuer.publicKey)) {\n            return "certificate signature is invalid";\n          }\n          if (i > 0 && issuer !== child && !child.ca) {\n            return "certificate is not a CA";\n          }\n        }\n        return null;\n      }\n      function certificateVerifyReason(error) {\n        const text = String(error || "").toLowerCase();\n        if (text === "" || text === "ok") {\n          return "ok";\n        }\n        if (text.includes("hostname")) {\n          return "hostname-mismatch";\n        }\n        if (text.includes("not valid yet") || text.includes("not yet valid")) {\n          return "not-yet-valid";\n        }\n        if (text.includes("expired") || text.includes("not valid")) {\n          return "expired";\n        }\n        if (text.includes("unknown_ca") || text.includes("not trusted") || text.includes("unknown ca")) {\n          return "untrusted-root";\n        }\n        return "invalid-chain";\n      }\n      function certificateHostnameMatches(state, hostname) {\n        const crypto = nodeCrypto();\n        if (crypto && typeof crypto.X509Certificate === "function") {\n          const cert = new crypto.X509Certificate(Buffer.from(state.der));\n          if (isIpAddress(hostname) && typeof cert.checkIP === "function") {\n            return !!cert.checkIP(hostname);\n          }\n          if (typeof cert.checkHost === "function") {\n            return !!cert.checkHost(hostname);\n          }\n        }\n        return certificateHostnameMatchesFallback(state, hostname);\n      }\n      function isIpAddress(text) {\n        return /^(\\d{1,3}\\.){3}\\d{1,3}$/u.test(text) || text.includes(":");\n      }\n      function certificateHostnameMatchesFallback(state, hostname) {\n        const extensions = state.extensions || [];\n        const subjectAltName = extensions.find(\n          (ext) => ext.oid === "2.5.29.17"\n        );\n        if (subjectAltName) {\n          for (const name2 of subjectAltName.names || []) {\n            if (name2.type === "dns" && dnsNameMatches(name2.value, hostname)) {\n              return true;\n            }\n            if (name2.type === "ip" && name2.value === hostname) {\n              return true;\n            }\n          }\n          return false;\n        }\n        const match = state.subject.match(/(?:^|,\\s*)CN=([^,]+)/u);\n        return !!(match && dnsNameMatches(match[1], hostname));\n      }\n      function dnsNameMatches(pattern, hostname) {\n        pattern = String(pattern).toLowerCase();\n        hostname = String(hostname).toLowerCase();\n        if (pattern === hostname) {\n          return true;\n        }\n        if (!pattern.startsWith("*.")) {\n          return false;\n        }\n        const suffix = pattern.slice(1);\n        return hostname.endsWith(suffix) && hostname.slice(0, -suffix.length).indexOf(".") === -1;\n      }\n      function binaryStringFromBytes(bytes) {\n        let out = "";\n        for (let i = 0; i < bytes.length; i += 8192) {\n          out += String.fromCharCode(...bytes.slice(i, i + 8192));\n        }\n        return out;\n      }\n      function bytesFromBinaryString(text) {\n        const bytes = new Uint8Array(text.length);\n        for (let i = 0; i < text.length; i++) {\n          bytes[i] = text.charCodeAt(i) & 255;\n        }\n        return bytes;\n      }\n      function forgeAsn1Bytes(forge, asn1) {\n        return bytesFromBinaryString(forge.asn1.toDer(asn1).getBytes());\n      }\n      function tlsIdentityFromPem(certificatePem, privateKeyPem, password = null) {\n        const label = "TlsIdentity.from_pem";\n        const certPem = assertString(\n          certificatePem,\n          label,\n          "String certificate_pem"\n        );\n        const keyPem = assertString(\n          privateKeyPem,\n          label,\n          "String private_key_pem"\n        );\n        const pass = password == null ? "" : assertString(\n          password,\n          label,\n          "String password"\n        );\n        const blocks = certificatePemBlocks(certPem, label);\n        parseX509Der(blocks[0], label);\n        if (!/-----BEGIN [A-Z ]*PRIVATE KEY-----/u.test(keyPem)) {\n          throw new Error(`${label} expects PEM private key text`);\n        }\n        return new TlsIdentity(new SecureTlsIdentity(\n          certificateDerToPem(blocks[0]),\n          keyPem,\n          pass,\n          "pem",\n          blocks.map(certificateDerToPem).join("")\n        ));\n      }\n      function tlsIdentityFromPkcs12(bytesValue, password = null) {\n        const label = "TlsIdentity.from_pkcs12";\n        if (hostName() === "browser") {\n          throw new Error(`${label} is not supported on host browser`);\n        }\n        const bytes = assertBinaryString(bytesValue, label, "BinaryString bytes");\n        const pass = password == null ? "" : assertString(\n          password,\n          label,\n          "String password"\n        );\n        const forge = nodeForge();\n        if (!forge) {\n          nodeUnsupported(label);\n        }\n        try {\n          const asn1 = forge.asn1.fromDer(\n            forge.util.createBuffer(binaryStringFromBytes(bytes))\n          );\n          const p12 = forge.pkcs12.pkcs12FromAsn1(asn1, false, pass);\n          const keyBags = [\n            ...p12.getBags({\n              bagType: forge.pki.oids.pkcs8ShroudedKeyBag\n            })[forge.pki.oids.pkcs8ShroudedKeyBag] || [],\n            ...p12.getBags({\n              bagType: forge.pki.oids.keyBag\n            })[forge.pki.oids.keyBag] || []\n          ];\n          const certBags = p12.getBags({\n            bagType: forge.pki.oids.certBag\n          })[forge.pki.oids.certBag] || [];\n          if (keyBags.length === 0 || certBags.length === 0) {\n            throw new Error("missing identity material");\n          }\n          const keyBag = keyBags[0];\n          const certBag = certBags[0];\n          const keyPem = keyBag.key ? forge.pki.privateKeyToPem(keyBag.key) : derToPem("PRIVATE KEY", forgeAsn1Bytes(forge, keyBag.asn1));\n          const certPem = certBag.cert ? forge.pki.certificateToPem(certBag.cert) : derToPem("CERTIFICATE", forgeAsn1Bytes(forge, certBag.asn1));\n          const chainPem = certBags.map(\n            (bag) => bag.cert ? forge.pki.certificateToPem(bag.cert) : derToPem("CERTIFICATE", forgeAsn1Bytes(forge, bag.asn1))\n          ).join("");\n          return new TlsIdentity(new SecureTlsIdentity(\n            certPem,\n            keyPem,\n            "",\n            "pkcs12",\n            chainPem\n          ));\n        } catch (err) {\n          if (/password|decrypt|mac|integrity/iu.test(String(err.message))) {\n            throw new Error(`${label} failed to decrypt PKCS#12 data`);\n          }\n          throw new Error(\n            `${label} expects PKCS#12 data with certificate and private key`\n          );\n        }\n      }\n      function tlsIdentityState(identity, label) {\n        if (!(identity instanceof TlsIdentity)) {\n          throw new Error(`TypeException: ${label} expects TlsIdentity`);\n        }\n        return identity.__secureTlsIdentity;\n      }\n      function tlsIdentityCertificate(identity) {\n        const label = "TlsIdentity.certificate";\n        const state = tlsIdentityState(identity, label);\n        return parseX509Der(certificatePemBlocks(state.certPem, label)[0], label);\n      }\n      function tlsIdentityPrivateKey(identity) {\n        const label = "TlsIdentity.private_key";\n        if (hostName() === "browser") {\n          throw new Error(`${label} is not supported on host browser`);\n        }\n        const state = tlsIdentityState(identity, label);\n        try {\n          return signingImportPrivate(\n            state.keyPem,\n            { format: "pem", password: state.password }\n          );\n        } catch (_err) {\n          throw new Error(\n            `${label} only supports Ed25519, ECDSA P-256, and ECDSA P-384 private keys`\n          );\n        }\n      }\n      function publicKeyVerify(publicKey, message, signature) {\n        const label = "PublicKey.verify";\n        if (hostName() === "browser") {\n          syncBrowserSigningError(label, "PublicKey.verify_async");\n        }\n        const messageBytes = assertBinaryString(\n          message,\n          label,\n          "BinaryString message"\n        );\n        const signatureBytes = assertBinaryString(\n          signature,\n          label,\n          "BinaryString signature"\n        );\n        const meta = signingMeta(publicKey.__securePublicKey.algorithm);\n        if (!meta) {\n          throw new Error(`${label} expects a signing public key`);\n        }\n        if (meta.type === "ed25519" && signatureBytes.length !== 64) {\n          return false;\n        }\n        const crypto = nodeCrypto();\n        if (!crypto || typeof crypto.verify !== "function") {\n          nodeUnsupported(label);\n        }\n        return crypto.verify(\n          meta.nodeHash ?? null,\n          messageBytes,\n          publicKey.__securePublicKey.key,\n          signatureBytes\n        );\n      }\n      async function publicKeyVerifyAsyncValue(publicKey, message, signature) {\n        const label = "PublicKey.verify";\n        const messageBytes = assertBinaryString(\n          message,\n          label,\n          "BinaryString message"\n        );\n        const signatureBytes = assertBinaryString(\n          signature,\n          label,\n          "BinaryString signature"\n        );\n        if (hostName() !== "browser") {\n          return publicKeyVerify(publicKey, message, signature);\n        }\n        const subtle = subtleSigningCrypto();\n        if (!subtle) {\n          browserSigningUnsupported(`${label}_async`);\n        }\n        const meta = signingMeta(publicKey.__securePublicKey.algorithm);\n        if (!meta) {\n          throw new Error(`${label} expects a signing public key`);\n        }\n        let verifySignature = signatureBytes;\n        if (meta.type === "ed25519") {\n          if (signatureBytes.length !== 64) {\n            return false;\n          }\n        } else {\n          try {\n            verifySignature = derToEcdsaRawSignature(\n              signatureBytes,\n              publicKey.__securePublicKey.algorithm\n            );\n          } catch (_err) {\n            return false;\n          }\n        }\n        try {\n          return await subtle.verify(\n            meta.type === "ed25519" ? { name: "Ed25519" } : { name: "ECDSA", hash: meta.webHash },\n            publicKey.__securePublicKey.key,\n            verifySignature,\n            messageBytes\n          );\n        } catch (_err) {\n          return false;\n        }\n      }\n      function publicKeyExport(publicKey, optionsValue = null) {\n        const label = "PublicKey.export";\n        const options = optionalDict(optionsValue, label, "Dict options");\n        const format = options.format == null ? "raw" : String(options.format);\n        const secure = publicKey.__securePublicKey;\n        if (format === "raw") {\n          if (secure.rawPublic) {\n            return new BinaryString(secure.rawPublic);\n          }\n          return new BinaryString(\n            rawPublicFromJwk(secure.key.export({ format: "jwk" }), label)\n          );\n        }\n        if (format === "pem") {\n          if (secure.algorithm === "x25519") {\n            throw new Error(\n              `${label} only supports raw format for x25519 public keys`\n            );\n          }\n          if (hostName() !== "browser") {\n            return String(secure.key.export({\n              format: "pem",\n              type: "spki"\n            }));\n          }\n          const meta = signingMeta(secure.algorithm);\n          const der = meta.type === "ed25519" ? null : ecdsaSpkiDerFromRawPublic(secure.rawPublic, secure.algorithm);\n          if (der == null) {\n            throw new Error(`${label} PEM export is unavailable for this browser key`);\n          }\n          return derToPem("PUBLIC KEY", der);\n        }\n        throw new Error(`${label} only supports raw and pem formats`);\n      }\n      function keyAgreementGenerate(algorithm = "x25519") {\n        const label = "KeyAgreement.generate";\n        algorithm = keyAgreementAlgorithm(algorithm, label);\n        if (hostName() === "browser") {\n          syncBrowserKeyAgreementError(label, "KeyAgreement.generate_async");\n        }\n        const crypto = nodeCrypto();\n        if (!crypto || typeof crypto.generateKeyPairSync !== "function") {\n          keyAgreementUnsupported(label);\n        }\n        const pair = crypto.generateKeyPairSync(algorithm);\n        return new KeyAgreement(new SecureKeyAgreement(\n          algorithm,\n          pair.privateKey\n        ));\n      }\n      async function browserKeyAgreementFromPair(algorithm, pair, label) {\n        const privateJwk = await globalThis.crypto.subtle.exportKey(\n          "jwk",\n          pair.privateKey\n        );\n        const publicJwk = await globalThis.crypto.subtle.exportKey(\n          "jwk",\n          pair.publicKey\n        );\n        return new KeyAgreement(new SecureKeyAgreement(\n          algorithm,\n          pair.privateKey,\n          pair.publicKey,\n          rawPrivateFromJwk(privateJwk, label),\n          rawPublicFromJwk(publicJwk, label)\n        ));\n      }\n      async function keyAgreementGenerateAsyncValue(algorithm = "x25519") {\n        const label = "KeyAgreement.generate";\n        algorithm = keyAgreementAlgorithm(algorithm, label);\n        if (hostName() !== "browser") {\n          return keyAgreementGenerate(algorithm);\n        }\n        const subtle = subtleKeyAgreementCrypto();\n        if (!subtle) {\n          keyAgreementUnsupported(`${label}_async`);\n        }\n        try {\n          const pair = await subtle.generateKey(\n            { name: "X25519" },\n            true,\n            ["deriveBits"]\n          );\n          return await browserKeyAgreementFromPair(algorithm, pair, label);\n        } catch (_err) {\n          keyAgreementUnsupported(`${label}_async`);\n        }\n      }\n      function keyAgreementImportPrivate(key, options = null) {\n        const label = "KeyAgreement.import_private";\n        if (hostName() === "browser") {\n          syncBrowserKeyAgreementError(\n            label,\n            "KeyAgreement.import_private_async"\n          );\n        }\n        const opts = optionalDict(options, label, "Dict options");\n        keyAgreementAlgorithmOption(opts, label);\n        const format = keyFormat(key, options, label);\n        if (format !== "raw") {\n          throw new Error(`${label} only supports raw format`);\n        }\n        return new KeyAgreement(new SecureKeyAgreement(\n          "x25519",\n          nodeX25519PrivateKeyFromRaw(key, label)\n        ));\n      }\n      async function keyAgreementImportPrivateAsyncValue(key, options = null) {\n        const label = "KeyAgreement.import_private";\n        if (hostName() !== "browser") {\n          return keyAgreementImportPrivate(key, options);\n        }\n        const subtle = subtleKeyAgreementCrypto();\n        if (!subtle) {\n          keyAgreementUnsupported(`${label}_async`);\n        }\n        const opts = optionalDict(options, label, "Dict options");\n        keyAgreementAlgorithmOption(opts, label);\n        const format = keyFormat(key, options, label);\n        if (format !== "raw") {\n          throw new Error(`${label} only supports raw format`);\n        }\n        const rawPrivate = x25519PrivateBytes(key, label);\n        try {\n          const privateKey = await subtle.importKey(\n            "pkcs8",\n            x25519Pkcs8DerFromRawPrivate(rawPrivate),\n            { name: "X25519" },\n            true,\n            ["deriveBits"]\n          );\n          const privateJwk = await subtle.exportKey("jwk", privateKey);\n          const rawPublic = rawPublicFromJwk(privateJwk, label);\n          const publicKey = await subtle.importKey(\n            "raw",\n            rawPublic,\n            { name: "X25519" },\n            true,\n            []\n          );\n          return new KeyAgreement(new SecureKeyAgreement(\n            "x25519",\n            privateKey,\n            publicKey,\n            rawPrivateFromJwk(privateJwk, label),\n            rawPublic\n          ));\n        } catch (_err) {\n          keyAgreementUnsupported(`${label}_async`);\n        }\n      }\n      function keyAgreementImportPublic(key, options = null) {\n        const label = "KeyAgreement.import_public";\n        if (hostName() === "browser") {\n          syncBrowserKeyAgreementError(label, "KeyAgreement.import_public_async");\n        }\n        const opts = optionalDict(options, label, "Dict options");\n        keyAgreementAlgorithmOption(opts, label);\n        const format = keyFormat(key, options, label);\n        if (format !== "raw") {\n          throw new Error(`${label} only supports raw format`);\n        }\n        return new PublicKey(new SecurePublicKey(\n          "x25519",\n          nodeX25519PublicKeyFromRaw(key, label)\n        ));\n      }\n      async function keyAgreementImportPublicAsyncValue(key, options = null) {\n        const label = "KeyAgreement.import_public";\n        if (hostName() !== "browser") {\n          return keyAgreementImportPublic(key, options);\n        }\n        const subtle = subtleKeyAgreementCrypto();\n        if (!subtle) {\n          keyAgreementUnsupported(`${label}_async`);\n        }\n        const opts = optionalDict(options, label, "Dict options");\n        keyAgreementAlgorithmOption(opts, label);\n        const format = keyFormat(key, options, label);\n        if (format !== "raw") {\n          throw new Error(`${label} only supports raw format`);\n        }\n        const rawPublic = x25519PublicBytes(key, label);\n        try {\n          const publicKey = await subtle.importKey(\n            "raw",\n            rawPublic,\n            { name: "X25519" },\n            true,\n            []\n          );\n          return new PublicKey(new SecurePublicKey(\n            "x25519",\n            publicKey,\n            rawPublic\n          ));\n        } catch (_err) {\n          keyAgreementUnsupported(`${label}_async`);\n        }\n      }\n      function keyAgreementPublicKey(keyAgreement) {\n        const secure = keyAgreement.__secureKeyAgreement;\n        if (hostName() === "browser") {\n          if (secure.publicKey && secure.rawPublic) {\n            return new PublicKey(new SecurePublicKey(\n              secure.algorithm,\n              secure.publicKey,\n              secure.rawPublic\n            ));\n          }\n          throw new Error(\n            "KeyAgreement.public_key is unavailable for this browser key"\n          );\n        }\n        const crypto = nodeCrypto();\n        return new PublicKey(new SecurePublicKey(\n          secure.algorithm,\n          crypto.createPublicKey(secure.key)\n        ));\n      }\n      function keyAgreementExportPrivate(keyAgreement, optionsValue = null) {\n        const label = "KeyAgreement.export_private";\n        const options = optionalDict(optionsValue, label, "Dict options");\n        const format = options.format == null ? "raw" : String(options.format);\n        if (format !== "raw") {\n          throw new Error(`${label} only supports raw format`);\n        }\n        const secure = keyAgreement.__secureKeyAgreement;\n        if (secure.rawPrivate) {\n          return new BinaryString(secure.rawPrivate);\n        }\n        return new BinaryString(\n          rawPrivateFromJwk(secure.key.export({ format: "jwk" }), label)\n        );\n      }\n      function keyAgreementDerive(keyAgreement, publicKey) {\n        const label = "KeyAgreement.derive";\n        if (hostName() === "browser") {\n          syncBrowserKeyAgreementError(label, "KeyAgreement.derive_async");\n        }\n        if (!(publicKey instanceof PublicKey) || publicKey.__securePublicKey.algorithm !== "x25519") {\n          throw new Error(`${label} expects an x25519 public key`);\n        }\n        const crypto = nodeCrypto();\n        if (!crypto || typeof crypto.diffieHellman !== "function") {\n          keyAgreementUnsupported(label);\n        }\n        return new BinaryString(\n          new Uint8Array(crypto.diffieHellman({\n            privateKey: keyAgreement.__secureKeyAgreement.key,\n            publicKey: publicKey.__securePublicKey.key\n          }))\n        );\n      }\n      async function keyAgreementDeriveAsyncValue(keyAgreement, publicKey) {\n        const label = "KeyAgreement.derive";\n        if (hostName() !== "browser") {\n          return keyAgreementDerive(keyAgreement, publicKey);\n        }\n        if (!(publicKey instanceof PublicKey) || publicKey.__securePublicKey.algorithm !== "x25519") {\n          throw new Error(`${label} expects an x25519 public key`);\n        }\n        const subtle = subtleKeyAgreementCrypto();\n        if (!subtle) {\n          keyAgreementUnsupported(`${label}_async`);\n        }\n        try {\n          return new BinaryString(new Uint8Array(await subtle.deriveBits(\n            { name: "X25519", public: publicKey.__securePublicKey.key },\n            keyAgreement.__secureKeyAgreement.key,\n            256\n          )));\n        } catch (_err) {\n          keyAgreementUnsupported(`${label}_async`);\n        }\n      }\n      var Secure = class {\n        static capabilities() {\n          return capabilities();\n        }\n        static has(area, name2) {\n          return hasCapability(area, name2);\n        }\n        static require(area, name2) {\n          return requireCapability(area, name2);\n        }\n      };\n      var KeyDerivation = class {\n        static hkdf_sha256(inputKeyMaterial, length, salt = null, info = null) {\n          return hkdfSha256(inputKeyMaterial, length, salt, info);\n        }\n        static hkdf_sha256_async(inputKeyMaterial, length, salt = null, info = null) {\n          const args = hkdfSha256Inputs(inputKeyMaterial, length, salt, info);\n          if (subtleCrypto()) {\n            return taskRuntime.Task.from(webCryptoHkdfSha256(args));\n          }\n          return taskRuntime.Task.resolved(\n            new BinaryString(\n              hkdfSha256Bytes(\n                args.inputKeyMaterial,\n                args.length,\n                args.salt,\n                args.info\n              )\n            )\n          );\n        }\n      };\n      var SecureRandom = class {\n        static bytes(length) {\n          if (arguments.length !== 1 || length == null) {\n            throw new Error("SecureRandom.bytes expects a non-negative integer");\n          }\n          return new BinaryString(\n            randomBytes(nonNegativeInteger(length, "SecureRandom.bytes"))\n          );\n        }\n        static token(length = 32) {\n          if (length == null) {\n            length = 32;\n          }\n          return base64url(\n            randomBytes(nonNegativeInteger(length, "SecureRandom.token"))\n          );\n        }\n        static int(max) {\n          return randomInt(positiveInteger(max, "SecureRandom.int"));\n        }\n      };\n      var PasswordHash = class {\n        static default_algorithm() {\n          return DEFAULT_PASSWORD_HASH_ALGORITHM;\n        }\n        static hash(password, options = null) {\n          return passwordHash(password, options);\n        }\n        static hash_async(password, options = null) {\n          return taskRuntime.Task.from(passwordHashAsyncValue(password, options));\n        }\n        static verify(password, encodedHash) {\n          return passwordHashVerify(password, encodedHash);\n        }\n        static verify_async(password, encodedHash) {\n          return taskRuntime.Task.from(\n            passwordHashVerifyAsyncValue(password, encodedHash)\n          );\n        }\n        static needs_rehash(encodedHash, options = null) {\n          return passwordHashNeedsRehash(encodedHash, options);\n        }\n        static derive_key(password, options = null) {\n          return passwordHashDeriveKey(password, options);\n        }\n        static derive_key_async(password, options = null) {\n          return taskRuntime.Task.from(\n            passwordHashDeriveKeyAsyncValue(password, options)\n          );\n        }\n      };\n      var Cipher = class {\n        static generate_key(algorithm = "aes-256-gcm") {\n          return cipherGenerateKey(algorithm);\n        }\n        static encrypt(plaintext, key, options = null) {\n          return cipherEncrypt(plaintext, key, options);\n        }\n        static decrypt(envelope, key, options = null) {\n          return cipherDecrypt(envelope, key, options);\n        }\n        static encrypt_async(plaintext, key, options = null) {\n          return cipherEncryptAsync(plaintext, key, options);\n        }\n        static decrypt_async(envelope, key, options = null) {\n          return cipherDecryptAsync(envelope, key, options);\n        }\n      };\n      var KeyAgreement = class {\n        constructor(secureKeyAgreement) {\n          if (!(secureKeyAgreement instanceof SecureKeyAgreement)) {\n            throw new Error("KeyAgreement objects are created by std/secure");\n          }\n          this.__secureKeyAgreement = secureKeyAgreement;\n        }\n        static generate(algorithm = "x25519") {\n          return keyAgreementGenerate(algorithm);\n        }\n        static generate_async(algorithm = "x25519") {\n          return taskRuntime.Task.from(\n            keyAgreementGenerateAsyncValue(algorithm)\n          );\n        }\n        static import_private(key, options = null) {\n          return keyAgreementImportPrivate(key, options);\n        }\n        static import_private_async(key, options = null) {\n          return taskRuntime.Task.from(\n            keyAgreementImportPrivateAsyncValue(key, options)\n          );\n        }\n        static import_public(key, options = null) {\n          return keyAgreementImportPublic(key, options);\n        }\n        static import_public_async(key, options = null) {\n          return taskRuntime.Task.from(\n            keyAgreementImportPublicAsyncValue(key, options)\n          );\n        }\n        public_key() {\n          return keyAgreementPublicKey(this);\n        }\n        derive(publicKey) {\n          return keyAgreementDerive(this, publicKey);\n        }\n        derive_async(publicKey) {\n          return taskRuntime.Task.from(\n            keyAgreementDeriveAsyncValue(this, publicKey)\n          );\n        }\n        export_private(options = null) {\n          return keyAgreementExportPrivate(this, options);\n        }\n      };\n      var SigningKey = class {\n        constructor(secureSigningKey) {\n          if (!(secureSigningKey instanceof SecureSigningKey)) {\n            throw new Error("SigningKey objects are created by std/secure");\n          }\n          this.__secureSigningKey = secureSigningKey;\n        }\n        static generate(algorithm = "ed25519") {\n          return signingGenerate(algorithm);\n        }\n        static generate_async(algorithm = "ed25519") {\n          return taskRuntime.Task.from(signingGenerateAsyncValue(algorithm));\n        }\n        static import_private(key, options = null) {\n          return signingImportPrivate(key, options);\n        }\n        static import_private_async(key, options = null) {\n          return taskRuntime.Task.from(\n            signingImportPrivateAsyncValue(key, options)\n          );\n        }\n        static import_public(key, options = null) {\n          return signingImportPublic(key, options);\n        }\n        static import_public_async(key, options = null) {\n          return taskRuntime.Task.from(\n            signingImportPublicAsyncValue(key, options)\n          );\n        }\n        public_key() {\n          return signingPublicKey(this);\n        }\n        sign(message) {\n          return signingSign(this, message);\n        }\n        sign_async(message) {\n          return taskRuntime.Task.from(signingSignAsyncValue(this, message));\n        }\n        export_private(options = null) {\n          return signingExportPrivate(this, options);\n        }\n      };\n      var Certificate = class {\n        constructor(secureCertificate) {\n          if (!(secureCertificate instanceof SecureCertificate)) {\n            throw new Error("Certificate objects are created by std/secure");\n          }\n          this.__secureCertificate = secureCertificate;\n        }\n        static parse(input) {\n          return certificateParse(input);\n        }\n        static parse_chain(input) {\n          return certificateParseChain(input);\n        }\n        static verify_chain(chain, options = null) {\n          return certificateVerifyChain(chain, options);\n        }\n        subject() {\n          return certificateState(this, "Certificate.subject").subject;\n        }\n        issuer() {\n          return certificateState(this, "Certificate.issuer").issuer;\n        }\n        serial_number() {\n          return certificateState(this, "Certificate.serial_number").serial;\n        }\n        not_before() {\n          return new Time(certificateState(this, "Certificate.not_before").notBefore);\n        }\n        not_after() {\n          return new Time(certificateState(this, "Certificate.not_after").notAfter);\n        }\n        fingerprint(algorithm = "sha256") {\n          return certificateFingerprint(this, algorithm);\n        }\n        to_der() {\n          return new BinaryString(\n            Uint8Array.from(certificateState(this, "Certificate.to_der").der)\n          );\n        }\n        to_pem() {\n          return certificateDerToPem(\n            certificateState(this, "Certificate.to_pem").der\n          );\n        }\n        public_key() {\n          return certificatePublicKey(this);\n        }\n      };\n      var PrivateKey = class {\n      };\n      var PublicKey = class {\n        constructor(securePublicKey) {\n          if (!(securePublicKey instanceof SecurePublicKey)) {\n            throw new Error("PublicKey objects are created by std/secure");\n          }\n          this.__securePublicKey = securePublicKey;\n        }\n        verify(message, signature) {\n          return publicKeyVerify(this, message, signature);\n        }\n        verify_async(message, signature) {\n          return taskRuntime.Task.from(\n            publicKeyVerifyAsyncValue(this, message, signature)\n          );\n        }\n        export(options = null) {\n          return publicKeyExport(this, options);\n        }\n      };\n      var SealedBox = class {\n      };\n      var TlsIdentity = class {\n        constructor(secureTlsIdentity) {\n          if (!(secureTlsIdentity instanceof SecureTlsIdentity)) {\n            throw new Error("TlsIdentity objects are created by std/secure");\n          }\n          this.__secureTlsIdentity = secureTlsIdentity;\n        }\n        static from_pem(certificatePem, privateKeyPem, password = null) {\n          return tlsIdentityFromPem(certificatePem, privateKeyPem, password);\n        }\n        static from_pkcs12(bytes, password = null) {\n          return tlsIdentityFromPkcs12(bytes, password);\n        }\n        certificate() {\n          return tlsIdentityCertificate(this);\n        }\n        private_key() {\n          return tlsIdentityPrivateKey(this);\n        }\n      };\n      module.exports = {\n        Secure,\n        SecureRandom,\n        PasswordHash,\n        KeyDerivation,\n        Cipher,\n        KeyAgreement,\n        SigningKey,\n        Certificate,\n        PrivateKey,\n        PublicKey,\n        SealedBox,\n        TlsIdentity,\n        __zuzu_set_runtime_policy: setRuntimePolicy\n      };\n    }\n  });\n\n  // modules/std/data/json.js\n  var require_json = __commonJS({\n    "modules/std/data/json.js"(exports2, module2) {\n      "use strict";\n      var { Pair, PairList, ZuzuBag } = require_collections();\n      var { BinaryString: BinaryString2 } = require_runtime_helpers();\n      var utf8Decoder = new TextDecoder("utf-8", { fatal: true });\n      var utf8Encoder = new TextEncoder();\n      function _isPlainObject(value) {\n        return value != null && typeof value === "object" && !Array.isArray(value) && !(value instanceof PairList) && !(value instanceof ZuzuBag) && Object.prototype.toString.call(value) !== "[object Set]";\n      }\n      function _isSet(value) {\n        return Object.prototype.toString.call(value) === "[object Set]";\n      }\n      function _optionsObject(value) {\n        if (value instanceof PairList) {\n          const out = {};\n          for (const [key, inner] of value.list) {\n            out[String(key)] = inner;\n          }\n          return out;\n        }\n        if (_isPlainObject(value)) {\n          return value;\n        }\n        return {};\n      }\n      function _decorateDict(value) {\n        if (!_isPlainObject(value)) {\n          return value;\n        }\n        const sortedKeys = () => Object.keys(value).sort();\n        for (const [name2, fn2] of [\n          ["length", function _length() {\n            return Object.keys(this).length;\n          }],\n          ["count", function _count() {\n            return Object.keys(this).length;\n          }],\n          ["empty", function _empty() {\n            return Object.keys(this).length === 0 ? 1 : 0;\n          }],\n          ["keys", function _keys() {\n            return new Set(sortedKeys());\n          }],\n          ["values", function _values() {\n            return new ZuzuBag(sortedKeys().map((key) => this[key]));\n          }],\n          [\n            "enumerate",\n            function _enumerate() {\n              return new ZuzuBag(\n                sortedKeys().map(\n                  (key) => new Pair({ pair: [key, this[key]] })\n                )\n              );\n            }\n          ],\n          ["has", function _has(key) {\n            return Object.prototype.hasOwnProperty.call(this, String(key)) ? 1 : 0;\n          }],\n          ["contains", function _contains(key) {\n            return this.has(key);\n          }],\n          ["exists", function _exists(key) {\n            return this.has(key);\n          }],\n          ["defined", function _defined(key) {\n            return this.has(key) && this[String(key)] != null ? 1 : 0;\n          }],\n          ["get", function _get(key, fallback = null) {\n            return this.has(key) ? this[String(key)] : fallback;\n          }],\n          ["add", function _add(key, inner) {\n            this[String(key)] = inner;\n            return this;\n          }],\n          ["set", function _set(key, inner) {\n            return this.add(key, inner);\n          }],\n          [\n            "kv",\n            function _kv() {\n              const out = [];\n              for (const key of sortedKeys()) {\n                out.push(key, this[key]);\n              }\n              return out;\n            }\n          ],\n          ["sorted_keys", function _sorted_keys() {\n            return sortedKeys();\n          }],\n          [\n            "to_Array",\n            function _to_array() {\n              return sortedKeys().map(\n                (key) => new Pair({ pair: [key, this[key]] })\n              );\n            }\n          ],\n          ["to_Iterator", function _to_iterator() {\n            return sortedKeys()[Symbol.iterator]();\n          }],\n          [\n            "for_each_key",\n            function _for_each_key(fn3) {\n              for (const key of sortedKeys()) {\n                fn3(key);\n              }\n              return this;\n            }\n          ],\n          [\n            "for_each_value",\n            function _for_each_value(fn3) {\n              for (const key of sortedKeys()) {\n                fn3(this[key]);\n              }\n              return this;\n            }\n          ],\n          [\n            "for_each_pair",\n            function _for_each_pair(fn3) {\n              for (const key of sortedKeys()) {\n                fn3(new Pair({ pair: [key, this[key]] }));\n              }\n              return this;\n            }\n          ],\n          [\n            "remove",\n            function _remove(key) {\n              if (typeof key === "function") {\n                for (const entryKey of Object.keys(this)) {\n                  if (key(new Pair({ pair: [entryKey, this[entryKey]] }))) {\n                    delete this[entryKey];\n                  }\n                }\n                return this;\n              }\n              delete this[String(key)];\n              return this;\n            }\n          ],\n          [\n            "clear",\n            function _clear() {\n              for (const key of Object.keys(this)) {\n                delete this[key];\n              }\n              return this;\n            }\n          ]\n        ]) {\n          if (!Object.prototype.hasOwnProperty.call(value, name2)) {\n            Object.defineProperty(value, name2, {\n              value: fn2,\n              enumerable: false,\n              configurable: true,\n              writable: true\n            });\n          }\n        }\n        for (const key of Object.keys(value)) {\n          value[key] = _decorateValue(value[key]);\n        }\n        return value;\n      }\n      function _decoratePairList(value) {\n        if (!(value instanceof PairList)) {\n          return value;\n        }\n        for (const [name2, getter] of [\n          ["keys", function _keys() {\n            return value.list.map((pair) => pair[0]);\n          }],\n          ["values", function _values() {\n            return value.list.map((pair) => pair[1]);\n          }]\n        ]) {\n          if (!Object.prototype.hasOwnProperty.call(value, name2)) {\n            Object.defineProperty(value, name2, {\n              get: getter,\n              enumerable: false,\n              configurable: true\n            });\n          }\n        }\n        return value;\n      }\n      function _decorateArray(value) {\n        if (!Array.isArray(value)) {\n          return value;\n        }\n        for (let i = 0; i < value.length; i++) {\n          value[i] = _decorateValue(value[i]);\n        }\n        return value;\n      }\n      function _decorateValue(value) {\n        if (Array.isArray(value)) {\n          return _decorateArray(value);\n        }\n        if (value instanceof PairList) {\n          return _decoratePairList(value);\n        }\n        if (_isPlainObject(value)) {\n          return _decorateDict(value);\n        }\n        return value;\n      }\n      function _sortCollectionValues(values) {\n        return values.slice().sort((left, right) => String(left).localeCompare(String(right)));\n      }\n      function _collapsePairListEntries(entries) {\n        const order = [];\n        const values = /* @__PURE__ */ new Map();\n        for (const [rawKey, entryValue] of entries) {\n          const key = String(rawKey);\n          if (!values.has(key)) {\n            order.push(key);\n          }\n          values.set(key, entryValue);\n        }\n        return order.map((key) => [key, values.get(key)]);\n      }\n      function _objectEntriesForEncode(value, options) {\n        if (value instanceof PairList) {\n          const entries2 = value.list.map((pair) => [String(pair[0]), pair[1]]);\n          if (options.pairlists) {\n            return options.canonical ? entries2.slice().sort((left, right) => left[0].localeCompare(right[0])) : entries2;\n          }\n          value = Object.fromEntries(_collapsePairListEntries(entries2));\n        }\n        const entries = Object.keys(value).map((key) => [key, value[key]]);\n        if (options.canonical) {\n          entries.sort((left, right) => left[0].localeCompare(right[0]));\n        }\n        return entries;\n      }\n      function _encodeJson(value, options, depth = 0) {\n        if (value == null) {\n          return "null";\n        }\n        if (typeof value === "string") {\n          return JSON.stringify(value);\n        }\n        if (typeof value === "number") {\n          return Number.isFinite(value) ? String(value) : "null";\n        }\n        if (typeof value === "boolean") {\n          return value ? "true" : "false";\n        }\n        if (Array.isArray(value)) {\n          const items = value.map((item) => {\n            const encoded = _encodeJson(item, options, depth + 1);\n            return encoded === void 0 ? "null" : encoded;\n          });\n          if (!options.pretty) {\n            return `[${items.join(",")}]`;\n          }\n          if (items.length === 0) {\n            return "[]";\n          }\n          const indent = "	".repeat(depth);\n          const inner = "	".repeat(depth + 1);\n          return `[\n${inner}${items.join(`,\n${inner}`)}\n${indent}]`;\n        }\n        if (value instanceof ZuzuBag) {\n          return _encodeJson(_sortCollectionValues(value.items), options, depth);\n        }\n        if (_isSet(value)) {\n          return _encodeJson(_sortCollectionValues([...value]), options, depth);\n        }\n        if (value instanceof PairList || _isPlainObject(value)) {\n          const entries = _objectEntriesForEncode(value, options).map((pair) => [pair[0], _encodeJson(pair[1], options, depth + 1)]).filter((pair) => pair[1] !== void 0);\n          if (!options.pretty) {\n            return `{${entries.map((pair) => `${JSON.stringify(pair[0])}:${pair[1]}`).join(",")}}`;\n          }\n          if (entries.length === 0) {\n            return "{}";\n          }\n          const indent = "	".repeat(depth);\n          const inner = "	".repeat(depth + 1);\n          return `{\n${inner}${entries.map((pair) => `${JSON.stringify(pair[0])}: ${pair[1]}`).join(`,\n${inner}`)}\n${indent}}`;\n        }\n        if (typeof value.toJSON === "function") {\n          return _encodeJson(value.toJSON(), options, depth);\n        }\n        return void 0;\n      }\n      function _parseJson(text, pairlists) {\n        let index = 0;\n        let source = "";\n        if (text && text.bytes instanceof Uint8Array) {\n          source = utf8Decoder.decode(text.bytes);\n        } else {\n          source = String(text ?? "");\n        }\n        function error(message) {\n          throw new Error(`JSON.parse error at position ${index}: ${message}`);\n        }\n        function skipWhitespace() {\n          while (index < source.length && /\\s/u.test(source[index])) {\n            index++;\n          }\n        }\n        function parseString() {\n          let out = "";\n          index++;\n          while (index < source.length) {\n            const ch = source[index++];\n            if (ch === \'"\') {\n              return out;\n            }\n            if (ch !== "\\\\") {\n              out += ch;\n              continue;\n            }\n            if (index >= source.length) {\n              error("unterminated escape sequence");\n            }\n            const esc = source[index++];\n            if (esc === \'"\' || esc === "\\\\" || esc === "/") {\n              out += esc;\n              continue;\n            }\n            if (esc === "b") {\n              out += "\\b";\n              continue;\n            }\n            if (esc === "f") {\n              out += "\\f";\n              continue;\n            }\n            if (esc === "n") {\n              out += "\\n";\n              continue;\n            }\n            if (esc === "r") {\n              out += "\\r";\n              continue;\n            }\n            if (esc === "t") {\n              out += "	";\n              continue;\n            }\n            if (esc === "u") {\n              const hex = source.slice(index, index + 4);\n              if (!/^[0-9A-Fa-f]{4}$/u.test(hex)) {\n                error("invalid unicode escape");\n              }\n              out += String.fromCharCode(Number.parseInt(hex, 16));\n              index += 4;\n              continue;\n            }\n            error(`invalid escape ${esc}`);\n          }\n          error("unterminated string literal");\n        }\n        function parseNumber() {\n          const match = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?/u.exec(source.slice(index));\n          if (!match) {\n            error("invalid number");\n          }\n          index += match[0].length;\n          return Number(match[0]);\n        }\n        function parseLiteral(literal, value2) {\n          if (source.slice(index, index + literal.length) !== literal) {\n            error(`expected ${literal}`);\n          }\n          index += literal.length;\n          return value2;\n        }\n        function parseArray() {\n          index++;\n          skipWhitespace();\n          const out = [];\n          if (source[index] === "]") {\n            index++;\n            return out;\n          }\n          while (index < source.length) {\n            out.push(parseValue());\n            skipWhitespace();\n            if (source[index] === "]") {\n              index++;\n              return out;\n            }\n            if (source[index] !== ",") {\n              error("expected , or ]");\n            }\n            index++;\n            skipWhitespace();\n          }\n          error("unterminated array");\n        }\n        function parseObject() {\n          index++;\n          skipWhitespace();\n          const entries = [];\n          if (source[index] === "}") {\n            index++;\n            return pairlists ? _decoratePairList(new PairList()) : _decorateDict({});\n          }\n          while (index < source.length) {\n            if (source[index] !== \'"\') {\n              error("expected object key string");\n            }\n            const key = parseString();\n            skipWhitespace();\n            if (source[index] !== ":") {\n              error("expected :");\n            }\n            index++;\n            skipWhitespace();\n            entries.push([key, parseValue()]);\n            skipWhitespace();\n            if (source[index] === "}") {\n              index++;\n              if (pairlists) {\n                return _decoratePairList(new PairList({ list: entries }));\n              }\n              const out = {};\n              for (const [entryKey, entryValue] of entries) {\n                Object.defineProperty(out, entryKey, {\n                  value: entryValue,\n                  enumerable: true,\n                  configurable: true,\n                  writable: true\n                });\n              }\n              return _decorateDict(out);\n            }\n            if (source[index] !== ",") {\n              error("expected , or }");\n            }\n            index++;\n            skipWhitespace();\n          }\n          error("unterminated object");\n        }\n        function parseValue() {\n          skipWhitespace();\n          const ch = source[index];\n          if (ch === \'"\') {\n            return parseString();\n          }\n          if (ch === "[") {\n            return parseArray();\n          }\n          if (ch === "{") {\n            return parseObject();\n          }\n          if (ch === "t") {\n            return parseLiteral("true", true);\n          }\n          if (ch === "f") {\n            return parseLiteral("false", false);\n          }\n          if (ch === "n") {\n            return parseLiteral("null", null);\n          }\n          return parseNumber();\n        }\n        const value = parseValue();\n        skipWhitespace();\n        if (index !== source.length) {\n          error("unexpected trailing input");\n        }\n        return _decorateValue(value);\n      }\n      function _asPath(value, methodName) {\n        if (value && typeof value.slurp === "function" && typeof value.spew === "function") {\n          return value;\n        }\n        throw new Error(`TypeException: ${methodName} expects Path as first argument`);\n      }\n      var JSONCodec = class {\n        constructor(options = {}, named = {}) {\n          const merged = {\n            ..._optionsObject(options),\n            ..._optionsObject(named)\n          };\n          this.utf8 = Boolean(merged.utf8);\n          this.pretty = Boolean(merged.pretty);\n          this.canonical = Boolean(merged.canonical);\n          this.pairlists = Boolean(merged.pairlists);\n        }\n        encode(value) {\n          return _encodeJson(value, {\n            canonical: this.canonical,\n            pairlists: this.pairlists,\n            pretty: this.pretty\n          });\n        }\n        encode_binarystring(value) {\n          return new BinaryString2(utf8Encoder.encode(this.encode(value)));\n        }\n        decode(text) {\n          return _parseJson(text, this.pairlists);\n        }\n        decode_binarystring(raw) {\n          if (!(raw instanceof BinaryString2)) {\n            throw new Error("TypeException: JSON.decode_binarystring expects BinaryString");\n          }\n          return _parseJson(raw, this.pairlists);\n        }\n        load(pathObj) {\n          const pathValue = _asPath(pathObj, "JSON.load");\n          return this.decode_binarystring(pathValue.slurp());\n        }\n        dump(pathObj, value) {\n          const pathValue = _asPath(pathObj, "JSON.dump");\n          pathValue.spew(this.encode_binarystring(value));\n          return pathObj;\n        }\n      };\n      module2.exports = {\n        JSON: JSONCodec\n      };\n    }\n  });\n\n  // node_modules/js-yaml/lib/common.js\n  var require_common = __commonJS({\n    "node_modules/js-yaml/lib/common.js"(exports2, module2) {\n      "use strict";\n      function isNothing(subject) {\n        return typeof subject === "undefined" || subject === null;\n      }\n      function isObject(subject) {\n        return typeof subject === "object" && subject !== null;\n      }\n      function toArray(sequence) {\n        if (Array.isArray(sequence)) return sequence;\n        else if (isNothing(sequence)) return [];\n        return [sequence];\n      }\n      function extend(target, source) {\n        var index, length, key, sourceKeys;\n        if (source) {\n          sourceKeys = Object.keys(source);\n          for (index = 0, length = sourceKeys.length; index < length; index += 1) {\n            key = sourceKeys[index];\n            target[key] = source[key];\n          }\n        }\n        return target;\n      }\n      function repeat(string, count) {\n        var result = "", cycle;\n        for (cycle = 0; cycle < count; cycle += 1) {\n          result += string;\n        }\n        return result;\n      }\n      function isNegativeZero(number) {\n        return number === 0 && Number.NEGATIVE_INFINITY === 1 / number;\n      }\n      module2.exports.isNothing = isNothing;\n      module2.exports.isObject = isObject;\n      module2.exports.toArray = toArray;\n      module2.exports.repeat = repeat;\n      module2.exports.isNegativeZero = isNegativeZero;\n      module2.exports.extend = extend;\n    }\n  });\n\n  // node_modules/js-yaml/lib/exception.js\n  var require_exception = __commonJS({\n    "node_modules/js-yaml/lib/exception.js"(exports2, module2) {\n      "use strict";\n      function formatError(exception, compact) {\n        var where = "", message = exception.reason || "(unknown reason)";\n        if (!exception.mark) return message;\n        if (exception.mark.name) {\n          where += \'in "\' + exception.mark.name + \'" \';\n        }\n        where += "(" + (exception.mark.line + 1) + ":" + (exception.mark.column + 1) + ")";\n        if (!compact && exception.mark.snippet) {\n          where += "\\n\\n" + exception.mark.snippet;\n        }\n        return message + " " + where;\n      }\n      function YAMLException(reason, mark) {\n        Error.call(this);\n        this.name = "YAMLException";\n        this.reason = reason;\n        this.mark = mark;\n        this.message = formatError(this, false);\n        if (Error.captureStackTrace) {\n          Error.captureStackTrace(this, this.constructor);\n        } else {\n          this.stack = new Error().stack || "";\n        }\n      }\n      YAMLException.prototype = Object.create(Error.prototype);\n      YAMLException.prototype.constructor = YAMLException;\n      YAMLException.prototype.toString = function toString(compact) {\n        return this.name + ": " + formatError(this, compact);\n      };\n      module2.exports = YAMLException;\n    }\n  });\n\n  // node_modules/js-yaml/lib/snippet.js\n  var require_snippet = __commonJS({\n    "node_modules/js-yaml/lib/snippet.js"(exports2, module2) {\n      "use strict";\n      var common = require_common();\n      function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {\n        var head = "";\n        var tail = "";\n        var maxHalfLength = Math.floor(maxLineLength / 2) - 1;\n        if (position - lineStart > maxHalfLength) {\n          head = " ... ";\n          lineStart = position - maxHalfLength + head.length;\n        }\n        if (lineEnd - position > maxHalfLength) {\n          tail = " ...";\n          lineEnd = position + maxHalfLength - tail.length;\n        }\n        return {\n          str: head + buffer.slice(lineStart, lineEnd).replace(/\\t/g, "\\u2192") + tail,\n          pos: position - lineStart + head.length\n          // relative position\n        };\n      }\n      function padStart(string, max) {\n        return common.repeat(" ", max - string.length) + string;\n      }\n      function makeSnippet(mark, options) {\n        options = Object.create(options || null);\n        if (!mark.buffer) return null;\n        if (!options.maxLength) options.maxLength = 79;\n        if (typeof options.indent !== "number") options.indent = 1;\n        if (typeof options.linesBefore !== "number") options.linesBefore = 3;\n        if (typeof options.linesAfter !== "number") options.linesAfter = 2;\n        var re = /\\r?\\n|\\r|\\0/g;\n        var lineStarts = [0];\n        var lineEnds = [];\n        var match;\n        var foundLineNo = -1;\n        while (match = re.exec(mark.buffer)) {\n          lineEnds.push(match.index);\n          lineStarts.push(match.index + match[0].length);\n          if (mark.position <= match.index && foundLineNo < 0) {\n            foundLineNo = lineStarts.length - 2;\n          }\n        }\n        if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;\n        var result = "", i, line;\n        var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;\n        var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);\n        for (i = 1; i <= options.linesBefore; i++) {\n          if (foundLineNo - i < 0) break;\n          line = getLine(\n            mark.buffer,\n            lineStarts[foundLineNo - i],\n            lineEnds[foundLineNo - i],\n            mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),\n            maxLineLength\n          );\n          result = common.repeat(" ", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + " | " + line.str + "\\n" + result;\n        }\n        line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);\n        result += common.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\\n";\n        result += common.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\\n";\n        for (i = 1; i <= options.linesAfter; i++) {\n          if (foundLineNo + i >= lineEnds.length) break;\n          line = getLine(\n            mark.buffer,\n            lineStarts[foundLineNo + i],\n            lineEnds[foundLineNo + i],\n            mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),\n            maxLineLength\n          );\n          result += common.repeat(" ", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + " | " + line.str + "\\n";\n        }\n        return result.replace(/\\n$/, "");\n      }\n      module2.exports = makeSnippet;\n    }\n  });\n\n  // node_modules/js-yaml/lib/type.js\n  var require_type = __commonJS({\n    "node_modules/js-yaml/lib/type.js"(exports2, module2) {\n      "use strict";\n      var YAMLException = require_exception();\n      var TYPE_CONSTRUCTOR_OPTIONS = [\n        "kind",\n        "multi",\n        "resolve",\n        "construct",\n        "instanceOf",\n        "predicate",\n        "represent",\n        "representName",\n        "defaultStyle",\n        "styleAliases"\n      ];\n      var YAML_NODE_KINDS = [\n        "scalar",\n        "sequence",\n        "mapping"\n      ];\n      function compileStyleAliases(map) {\n        var result = {};\n        if (map !== null) {\n          Object.keys(map).forEach(function(style) {\n            map[style].forEach(function(alias) {\n              result[String(alias)] = style;\n            });\n          });\n        }\n        return result;\n      }\n      function Type(tag, options) {\n        options = options || {};\n        Object.keys(options).forEach(function(name2) {\n          if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name2) === -1) {\n            throw new YAMLException(\'Unknown option "\' + name2 + \'" is met in definition of "\' + tag + \'" YAML type.\');\n          }\n        });\n        this.options = options;\n        this.tag = tag;\n        this.kind = options["kind"] || null;\n        this.resolve = options["resolve"] || function() {\n          return true;\n        };\n        this.construct = options["construct"] || function(data) {\n          return data;\n        };\n        this.instanceOf = options["instanceOf"] || null;\n        this.predicate = options["predicate"] || null;\n        this.represent = options["represent"] || null;\n        this.representName = options["representName"] || null;\n        this.defaultStyle = options["defaultStyle"] || null;\n        this.multi = options["multi"] || false;\n        this.styleAliases = compileStyleAliases(options["styleAliases"] || null);\n        if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {\n          throw new YAMLException(\'Unknown kind "\' + this.kind + \'" is specified for "\' + tag + \'" YAML type.\');\n        }\n      }\n      module2.exports = Type;\n    }\n  });\n\n  // node_modules/js-yaml/lib/schema.js\n  var require_schema = __commonJS({\n    "node_modules/js-yaml/lib/schema.js"(exports2, module2) {\n      "use strict";\n      var YAMLException = require_exception();\n      var Type = require_type();\n      function compileList(schema, name2) {\n        var result = [];\n        schema[name2].forEach(function(currentType) {\n          var newIndex = result.length;\n          result.forEach(function(previousType, previousIndex) {\n            if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) {\n              newIndex = previousIndex;\n            }\n          });\n          result[newIndex] = currentType;\n        });\n        return result;\n      }\n      function compileMap() {\n        var result = {\n          scalar: {},\n          sequence: {},\n          mapping: {},\n          fallback: {},\n          multi: {\n            scalar: [],\n            sequence: [],\n            mapping: [],\n            fallback: []\n          }\n        }, index, length;\n        function collectType(type) {\n          if (type.multi) {\n            result.multi[type.kind].push(type);\n            result.multi["fallback"].push(type);\n          } else {\n            result[type.kind][type.tag] = result["fallback"][type.tag] = type;\n          }\n        }\n        for (index = 0, length = arguments.length; index < length; index += 1) {\n          arguments[index].forEach(collectType);\n        }\n        return result;\n      }\n      function Schema(definition) {\n        return this.extend(definition);\n      }\n      Schema.prototype.extend = function extend(definition) {\n        var implicit = [];\n        var explicit = [];\n        if (definition instanceof Type) {\n          explicit.push(definition);\n        } else if (Array.isArray(definition)) {\n          explicit = explicit.concat(definition);\n        } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {\n          if (definition.implicit) implicit = implicit.concat(definition.implicit);\n          if (definition.explicit) explicit = explicit.concat(definition.explicit);\n        } else {\n          throw new YAMLException("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");\n        }\n        implicit.forEach(function(type) {\n          if (!(type instanceof Type)) {\n            throw new YAMLException("Specified list of YAML types (or a single Type object) contains a non-Type object.");\n          }\n          if (type.loadKind && type.loadKind !== "scalar") {\n            throw new YAMLException("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");\n          }\n          if (type.multi) {\n            throw new YAMLException("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.");\n          }\n        });\n        explicit.forEach(function(type) {\n          if (!(type instanceof Type)) {\n            throw new YAMLException("Specified list of YAML types (or a single Type object) contains a non-Type object.");\n          }\n        });\n        var result = Object.create(Schema.prototype);\n        result.implicit = (this.implicit || []).concat(implicit);\n        result.explicit = (this.explicit || []).concat(explicit);\n        result.compiledImplicit = compileList(result, "implicit");\n        result.compiledExplicit = compileList(result, "explicit");\n        result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);\n        return result;\n      };\n      module2.exports = Schema;\n    }\n  });\n\n  // node_modules/js-yaml/lib/type/str.js\n  var require_str = __commonJS({\n    "node_modules/js-yaml/lib/type/str.js"(exports2, module2) {\n      "use strict";\n      var Type = require_type();\n      module2.exports = new Type("tag:yaml.org,2002:str", {\n        kind: "scalar",\n        construct: function(data) {\n          return data !== null ? data : "";\n        }\n      });\n    }\n  });\n\n  // node_modules/js-yaml/lib/type/seq.js\n  var require_seq = __commonJS({\n    "node_modules/js-yaml/lib/type/seq.js"(exports2, module2) {\n      "use strict";\n      var Type = require_type();\n      module2.exports = new Type("tag:yaml.org,2002:seq", {\n        kind: "sequence",\n        construct: function(data) {\n          return data !== null ? data : [];\n        }\n      });\n    }\n  });\n\n  // node_modules/js-yaml/lib/type/map.js\n  var require_map = __commonJS({\n    "node_modules/js-yaml/lib/type/map.js"(exports2, module2) {\n      "use strict";\n      var Type = require_type();\n      module2.exports = new Type("tag:yaml.org,2002:map", {\n        kind: "mapping",\n        construct: function(data) {\n          return data !== null ? data : {};\n        }\n      });\n    }\n  });\n\n  // node_modules/js-yaml/lib/schema/failsafe.js\n  var require_failsafe = __commonJS({\n    "node_modules/js-yaml/lib/schema/failsafe.js"(exports2, module2) {\n      "use strict";\n      var Schema = require_schema();\n      module2.exports = new Schema({\n        explicit: [\n          require_str(),\n          require_seq(),\n          require_map()\n        ]\n      });\n    }\n  });\n\n  // node_modules/js-yaml/lib/type/null.js\n  var require_null = __commonJS({\n    "node_modules/js-yaml/lib/type/null.js"(exports2, module2) {\n      "use strict";\n      var Type = require_type();\n      function resolveYamlNull(data) {\n        if (data === null) return true;\n        var max = data.length;\n        return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL");\n      }\n      function constructYamlNull() {\n        return null;\n      }\n      function isNull(object) {\n        return object === null;\n      }\n      module2.exports = new Type("tag:yaml.org,2002:null", {\n        kind: "scalar",\n        resolve: resolveYamlNull,\n        construct: constructYamlNull,\n        predicate: isNull,\n        represent: {\n          canonical: function() {\n            return "~";\n          },\n          lowercase: function() {\n            return "null";\n          },\n          uppercase: function() {\n            return "NULL";\n          },\n          camelcase: function() {\n            return "Null";\n          },\n          empty: function() {\n            return "";\n          }\n        },\n        defaultStyle: "lowercase"\n      });\n    }\n  });\n\n  // node_modules/js-yaml/lib/type/bool.js\n  var require_bool = __commonJS({\n    "node_modules/js-yaml/lib/type/bool.js"(exports2, module2) {\n      "use strict";\n      var Type = require_type();\n      function resolveYamlBoolean(data) {\n        if (data === null) return false;\n        var max = data.length;\n        return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE");\n      }\n      function constructYamlBoolean(data) {\n        return data === "true" || data === "True" || data === "TRUE";\n      }\n      function isBoolean(object) {\n        return Object.prototype.toString.call(object) === "[object Boolean]";\n      }\n      module2.exports = new Type("tag:yaml.org,2002:bool", {\n        kind: "scalar",\n        resolve: resolveYamlBoolean,\n        construct: constructYamlBoolean,\n        predicate: isBoolean,\n        represent: {\n          lowercase: function(object) {\n            return object ? "true" : "false";\n          },\n          uppercase: function(object) {\n            return object ? "TRUE" : "FALSE";\n          },\n          camelcase: function(object) {\n            return object ? "True" : "False";\n          }\n        },\n        defaultStyle: "lowercase"\n      });\n    }\n  });\n\n  // node_modules/js-yaml/lib/type/int.js\n  var require_int = __commonJS({\n    "node_modules/js-yaml/lib/type/int.js"(exports2, module2) {\n      "use strict";\n      var common = require_common();\n      var Type = require_type();\n      function isHexCode(c) {\n        return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102;\n      }\n      function isOctCode(c) {\n        return 48 <= c && c <= 55;\n      }\n      function isDecCode(c) {\n        return 48 <= c && c <= 57;\n      }\n      function resolveYamlInteger(data) {\n        if (data === null) return false;\n        var max = data.length, index = 0, hasDigits = false, ch;\n        if (!max) return false;\n        ch = data[index];\n        if (ch === "-" || ch === "+") {\n          ch = data[++index];\n        }\n        if (ch === "0") {\n          if (index + 1 === max) return true;\n          ch = data[++index];\n          if (ch === "b") {\n            index++;\n            for (; index < max; index++) {\n              ch = data[index];\n              if (ch === "_") continue;\n              if (ch !== "0" && ch !== "1") return false;\n              hasDigits = true;\n            }\n            return hasDigits && ch !== "_";\n          }\n          if (ch === "x") {\n            index++;\n            for (; index < max; index++) {\n              ch = data[index];\n              if (ch === "_") continue;\n              if (!isHexCode(data.charCodeAt(index))) return false;\n              hasDigits = true;\n            }\n            return hasDigits && ch !== "_";\n          }\n          if (ch === "o") {\n            index++;\n            for (; index < max; index++) {\n              ch = data[index];\n              if (ch === "_") continue;\n              if (!isOctCode(data.charCodeAt(index))) return false;\n              hasDigits = true;\n            }\n            return hasDigits && ch !== "_";\n          }\n        }\n        if (ch === "_") return false;\n        for (; index < max; index++) {\n          ch = data[index];\n          if (ch === "_") continue;\n          if (!isDecCode(data.charCodeAt(index))) {\n            return false;\n          }\n          hasDigits = true;\n        }\n        if (!hasDigits || ch === "_") return false;\n        return true;\n      }\n      function constructYamlInteger(data) {\n        var value = data, sign = 1, ch;\n        if (value.indexOf("_") !== -1) {\n          value = value.replace(/_/g, "");\n        }\n        ch = value[0];\n        if (ch === "-" || ch === "+") {\n          if (ch === "-") sign = -1;\n          value = value.slice(1);\n          ch = value[0];\n        }\n        if (value === "0") return 0;\n        if (ch === "0") {\n          if (value[1] === "b") return sign * parseInt(value.slice(2), 2);\n          if (value[1] === "x") return sign * parseInt(value.slice(2), 16);\n          if (value[1] === "o") return sign * parseInt(value.slice(2), 8);\n        }\n        return sign * parseInt(value, 10);\n      }\n      function isInteger(object) {\n        return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 === 0 && !common.isNegativeZero(object));\n      }\n      module2.exports = new Type("tag:yaml.org,2002:int", {\n        kind: "scalar",\n        resolve: resolveYamlInteger,\n        construct: constructYamlInteger,\n        predicate: isInteger,\n        represent: {\n          binary: function(obj) {\n            return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);\n          },\n          octal: function(obj) {\n            return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1);\n          },\n          decimal: function(obj) {\n            return obj.toString(10);\n          },\n          /* eslint-disable max-len */\n          hexadecimal: function(obj) {\n            return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);\n          }\n        },\n        defaultStyle: "decimal",\n        styleAliases: {\n          binary: [2, "bin"],\n          octal: [8, "oct"],\n          decimal: [10, "dec"],\n          hexadecimal: [16, "hex"]\n        }\n      });\n    }\n  });\n\n  // node_modules/js-yaml/lib/type/float.js\n  var require_float = __commonJS({\n    "node_modules/js-yaml/lib/type/float.js"(exports2, module2) {\n      "use strict";\n      var common = require_common();\n      var Type = require_type();\n      var YAML_FLOAT_PATTERN = new RegExp(\n        // 2.5e4, 2.5 and integers\n        "^(?:[-+]?(?:[0-9][0-9_]*)(?:\\\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\\\.(?:inf|Inf|INF)|\\\\.(?:nan|NaN|NAN))$"\n      );\n      function resolveYamlFloat(data) {\n        if (data === null) return false;\n        if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_`\n        // Probably should update regexp & check speed\n        data[data.length - 1] === "_") {\n          return false;\n        }\n        return true;\n      }\n      function constructYamlFloat(data) {\n        var value, sign;\n        value = data.replace(/_/g, "").toLowerCase();\n        sign = value[0] === "-" ? -1 : 1;\n        if ("+-".indexOf(value[0]) >= 0) {\n          value = value.slice(1);\n        }\n        if (value === ".inf") {\n          return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;\n        } else if (value === ".nan") {\n          return NaN;\n        }\n        return sign * parseFloat(value, 10);\n      }\n      var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;\n      function representYamlFloat(object, style) {\n        var res;\n        if (isNaN(object)) {\n          switch (style) {\n            case "lowercase":\n              return ".nan";\n            case "uppercase":\n              return ".NAN";\n            case "camelcase":\n              return ".NaN";\n          }\n        } else if (Number.POSITIVE_INFINITY === object) {\n          switch (style) {\n            case "lowercase":\n              return ".inf";\n            case "uppercase":\n              return ".INF";\n            case "camelcase":\n              return ".Inf";\n          }\n        } else if (Number.NEGATIVE_INFINITY === object) {\n          switch (style) {\n            case "lowercase":\n              return "-.inf";\n            case "uppercase":\n              return "-.INF";\n            case "camelcase":\n              return "-.Inf";\n          }\n        } else if (common.isNegativeZero(object)) {\n          return "-0.0";\n        }\n        res = object.toString(10);\n        return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;\n      }\n      function isFloat(object) {\n        return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common.isNegativeZero(object));\n      }\n      module2.exports = new Type("tag:yaml.org,2002:float", {\n        kind: "scalar",\n        resolve: resolveYamlFloat,\n        construct: constructYamlFloat,\n        predicate: isFloat,\n        represent: representYamlFloat,\n        defaultStyle: "lowercase"\n      });\n    }\n  });\n\n  // node_modules/js-yaml/lib/schema/json.js\n  var require_json2 = __commonJS({\n    "node_modules/js-yaml/lib/schema/json.js"(exports2, module2) {\n      "use strict";\n      module2.exports = require_failsafe().extend({\n        implicit: [\n          require_null(),\n          require_bool(),\n          require_int(),\n          require_float()\n        ]\n      });\n    }\n  });\n\n  // node_modules/js-yaml/lib/schema/core.js\n  var require_core = __commonJS({\n    "node_modules/js-yaml/lib/schema/core.js"(exports2, module2) {\n      "use strict";\n      module2.exports = require_json2();\n    }\n  });\n\n  // node_modules/js-yaml/lib/type/timestamp.js\n  var require_timestamp = __commonJS({\n    "node_modules/js-yaml/lib/type/timestamp.js"(exports2, module2) {\n      "use strict";\n      var Type = require_type();\n      var YAML_DATE_REGEXP = new RegExp(\n        "^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"\n      );\n      var YAML_TIMESTAMP_REGEXP = new RegExp(\n        "^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\\\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\\\.([0-9]*))?(?:[ \\\\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$"\n      );\n      function resolveYamlTimestamp(data) {\n        if (data === null) return false;\n        if (YAML_DATE_REGEXP.exec(data) !== null) return true;\n        if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;\n        return false;\n      }\n      function constructYamlTimestamp(data) {\n        var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date;\n        match = YAML_DATE_REGEXP.exec(data);\n        if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);\n        if (match === null) throw new Error("Date resolve error");\n        year = +match[1];\n        month = +match[2] - 1;\n        day = +match[3];\n        if (!match[4]) {\n          return new Date(Date.UTC(year, month, day));\n        }\n        hour = +match[4];\n        minute = +match[5];\n        second = +match[6];\n        if (match[7]) {\n          fraction = match[7].slice(0, 3);\n          while (fraction.length < 3) {\n            fraction += "0";\n          }\n          fraction = +fraction;\n        }\n        if (match[9]) {\n          tz_hour = +match[10];\n          tz_minute = +(match[11] || 0);\n          delta = (tz_hour * 60 + tz_minute) * 6e4;\n          if (match[9] === "-") delta = -delta;\n        }\n        date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));\n        if (delta) date.setTime(date.getTime() - delta);\n        return date;\n      }\n      function representYamlTimestamp(object) {\n        return object.toISOString();\n      }\n      module2.exports = new Type("tag:yaml.org,2002:timestamp", {\n        kind: "scalar",\n        resolve: resolveYamlTimestamp,\n        construct: constructYamlTimestamp,\n        instanceOf: Date,\n        represent: representYamlTimestamp\n      });\n    }\n  });\n\n  // node_modules/js-yaml/lib/type/merge.js\n  var require_merge = __commonJS({\n    "node_modules/js-yaml/lib/type/merge.js"(exports2, module2) {\n      "use strict";\n      var Type = require_type();\n      function resolveYamlMerge(data) {\n        return data === "<<" || data === null;\n      }\n      module2.exports = new Type("tag:yaml.org,2002:merge", {\n        kind: "scalar",\n        resolve: resolveYamlMerge\n      });\n    }\n  });\n\n  // node_modules/js-yaml/lib/type/binary.js\n  var require_binary = __commonJS({\n    "node_modules/js-yaml/lib/type/binary.js"(exports2, module2) {\n      "use strict";\n      var Type = require_type();\n      var BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\\n\\r";\n      function resolveYamlBinary(data) {\n        if (data === null) return false;\n        var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;\n        for (idx = 0; idx < max; idx++) {\n          code = map.indexOf(data.charAt(idx));\n          if (code > 64) continue;\n          if (code < 0) return false;\n          bitlen += 6;\n        }\n        return bitlen % 8 === 0;\n      }\n      function constructYamlBinary(data) {\n        var idx, tailbits, input = data.replace(/[\\r\\n=]/g, ""), max = input.length, map = BASE64_MAP, bits = 0, result = [];\n        for (idx = 0; idx < max; idx++) {\n          if (idx % 4 === 0 && idx) {\n            result.push(bits >> 16 & 255);\n            result.push(bits >> 8 & 255);\n            result.push(bits & 255);\n          }\n          bits = bits << 6 | map.indexOf(input.charAt(idx));\n        }\n        tailbits = max % 4 * 6;\n        if (tailbits === 0) {\n          result.push(bits >> 16 & 255);\n          result.push(bits >> 8 & 255);\n          result.push(bits & 255);\n        } else if (tailbits === 18) {\n          result.push(bits >> 10 & 255);\n          result.push(bits >> 2 & 255);\n        } else if (tailbits === 12) {\n          result.push(bits >> 4 & 255);\n        }\n        return new Uint8Array(result);\n      }\n      function representYamlBinary(object) {\n        var result = "", bits = 0, idx, tail, max = object.length, map = BASE64_MAP;\n        for (idx = 0; idx < max; idx++) {\n          if (idx % 3 === 0 && idx) {\n            result += map[bits >> 18 & 63];\n            result += map[bits >> 12 & 63];\n            result += map[bits >> 6 & 63];\n            result += map[bits & 63];\n          }\n          bits = (bits << 8) + object[idx];\n        }\n        tail = max % 3;\n        if (tail === 0) {\n          result += map[bits >> 18 & 63];\n          result += map[bits >> 12 & 63];\n          result += map[bits >> 6 & 63];\n          result += map[bits & 63];\n        } else if (tail === 2) {\n          result += map[bits >> 10 & 63];\n          result += map[bits >> 4 & 63];\n          result += map[bits << 2 & 63];\n          result += map[64];\n        } else if (tail === 1) {\n          result += map[bits >> 2 & 63];\n          result += map[bits << 4 & 63];\n          result += map[64];\n          result += map[64];\n        }\n        return result;\n      }\n      function isBinary(obj) {\n        return Object.prototype.toString.call(obj) === "[object Uint8Array]";\n      }\n      module2.exports = new Type("tag:yaml.org,2002:binary", {\n        kind: "scalar",\n        resolve: resolveYamlBinary,\n        construct: constructYamlBinary,\n        predicate: isBinary,\n        represent: representYamlBinary\n      });\n    }\n  });\n\n  // node_modules/js-yaml/lib/type/omap.js\n  var require_omap = __commonJS({\n    "node_modules/js-yaml/lib/type/omap.js"(exports2, module2) {\n      "use strict";\n      var Type = require_type();\n      var _hasOwnProperty = Object.prototype.hasOwnProperty;\n      var _toString = Object.prototype.toString;\n      function resolveYamlOmap(data) {\n        if (data === null) return true;\n        var objectKeys = [], index, length, pair, pairKey, pairHasKey, object = data;\n        for (index = 0, length = object.length; index < length; index += 1) {\n          pair = object[index];\n          pairHasKey = false;\n          if (_toString.call(pair) !== "[object Object]") return false;\n          for (pairKey in pair) {\n            if (_hasOwnProperty.call(pair, pairKey)) {\n              if (!pairHasKey) pairHasKey = true;\n              else return false;\n            }\n          }\n          if (!pairHasKey) return false;\n          if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);\n          else return false;\n        }\n        return true;\n      }\n      function constructYamlOmap(data) {\n        return data !== null ? data : [];\n      }\n      module2.exports = new Type("tag:yaml.org,2002:omap", {\n        kind: "sequence",\n        resolve: resolveYamlOmap,\n        construct: constructYamlOmap\n      });\n    }\n  });\n\n  // node_modules/js-yaml/lib/type/pairs.js\n  var require_pairs = __commonJS({\n    "node_modules/js-yaml/lib/type/pairs.js"(exports2, module2) {\n      "use strict";\n      var Type = require_type();\n      var _toString = Object.prototype.toString;\n      function resolveYamlPairs(data) {\n        if (data === null) return true;\n        var index, length, pair, keys, result, object = data;\n        result = new Array(object.length);\n        for (index = 0, length = object.length; index < length; index += 1) {\n          pair = object[index];\n          if (_toString.call(pair) !== "[object Object]") return false;\n          keys = Object.keys(pair);\n          if (keys.length !== 1) return false;\n          result[index] = [keys[0], pair[keys[0]]];\n        }\n        return true;\n      }\n      function constructYamlPairs(data) {\n        if (data === null) return [];\n        var index, length, pair, keys, result, object = data;\n        result = new Array(object.length);\n        for (index = 0, length = object.length; index < length; index += 1) {\n          pair = object[index];\n          keys = Object.keys(pair);\n          result[index] = [keys[0], pair[keys[0]]];\n        }\n        return result;\n      }\n      module2.exports = new Type("tag:yaml.org,2002:pairs", {\n        kind: "sequence",\n        resolve: resolveYamlPairs,\n        construct: constructYamlPairs\n      });\n    }\n  });\n\n  // node_modules/js-yaml/lib/type/set.js\n  var require_set = __commonJS({\n    "node_modules/js-yaml/lib/type/set.js"(exports2, module2) {\n      "use strict";\n      var Type = require_type();\n      var _hasOwnProperty = Object.prototype.hasOwnProperty;\n      function resolveYamlSet(data) {\n        if (data === null) return true;\n        var key, object = data;\n        for (key in object) {\n          if (_hasOwnProperty.call(object, key)) {\n            if (object[key] !== null) return false;\n          }\n        }\n        return true;\n      }\n      function constructYamlSet(data) {\n        return data !== null ? data : {};\n      }\n      module2.exports = new Type("tag:yaml.org,2002:set", {\n        kind: "mapping",\n        resolve: resolveYamlSet,\n        construct: constructYamlSet\n      });\n    }\n  });\n\n  // node_modules/js-yaml/lib/schema/default.js\n  var require_default = __commonJS({\n    "node_modules/js-yaml/lib/schema/default.js"(exports2, module2) {\n      "use strict";\n      module2.exports = require_core().extend({\n        implicit: [\n          require_timestamp(),\n          require_merge()\n        ],\n        explicit: [\n          require_binary(),\n          require_omap(),\n          require_pairs(),\n          require_set()\n        ]\n      });\n    }\n  });\n\n  // node_modules/js-yaml/lib/loader.js\n  var require_loader = __commonJS({\n    "node_modules/js-yaml/lib/loader.js"(exports2, module2) {\n      "use strict";\n      var common = require_common();\n      var YAMLException = require_exception();\n      var makeSnippet = require_snippet();\n      var DEFAULT_SCHEMA = require_default();\n      var _hasOwnProperty = Object.prototype.hasOwnProperty;\n      var CONTEXT_FLOW_IN = 1;\n      var CONTEXT_FLOW_OUT = 2;\n      var CONTEXT_BLOCK_IN = 3;\n      var CONTEXT_BLOCK_OUT = 4;\n      var CHOMPING_CLIP = 1;\n      var CHOMPING_STRIP = 2;\n      var CHOMPING_KEEP = 3;\n      var PATTERN_NON_PRINTABLE = /[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x84\\x86-\\x9F\\uFFFE\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/;\n      var PATTERN_NON_ASCII_LINE_BREAKS = /[\\x85\\u2028\\u2029]/;\n      var PATTERN_FLOW_INDICATORS = /[,\\[\\]\\{\\}]/;\n      var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\\-]+!)$/i;\n      var PATTERN_TAG_URI = /^(?:!|[^,\\[\\]\\{\\}])(?:%[0-9a-f]{2}|[0-9a-z\\-#;\\/\\?:@&=\\+\\$,_\\.!~\\*\'\\(\\)\\[\\]])*$/i;\n      function _class(obj) {\n        return Object.prototype.toString.call(obj);\n      }\n      function is_EOL(c) {\n        return c === 10 || c === 13;\n      }\n      function is_WHITE_SPACE(c) {\n        return c === 9 || c === 32;\n      }\n      function is_WS_OR_EOL(c) {\n        return c === 9 || c === 32 || c === 10 || c === 13;\n      }\n      function is_FLOW_INDICATOR(c) {\n        return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;\n      }\n      function fromHexCode(c) {\n        var lc;\n        if (48 <= c && c <= 57) {\n          return c - 48;\n        }\n        lc = c | 32;\n        if (97 <= lc && lc <= 102) {\n          return lc - 97 + 10;\n        }\n        return -1;\n      }\n      function escapedHexLen(c) {\n        if (c === 120) {\n          return 2;\n        }\n        if (c === 117) {\n          return 4;\n        }\n        if (c === 85) {\n          return 8;\n        }\n        return 0;\n      }\n      function fromDecimalCode(c) {\n        if (48 <= c && c <= 57) {\n          return c - 48;\n        }\n        return -1;\n      }\n      function simpleEscapeSequence(c) {\n        return c === 48 ? "\\0" : c === 97 ? "\\x07" : c === 98 ? "\\b" : c === 116 ? "	" : c === 9 ? "	" : c === 110 ? "\\n" : c === 118 ? "\\v" : c === 102 ? "\\f" : c === 114 ? "\\r" : c === 101 ? "\\x1B" : c === 32 ? " " : c === 34 ? \'"\' : c === 47 ? "/" : c === 92 ? "\\\\" : c === 78 ? "\\x85" : c === 95 ? "\\xA0" : c === 76 ? "\\u2028" : c === 80 ? "\\u2029" : "";\n      }\n      function charFromCodepoint(c) {\n        if (c <= 65535) {\n          return String.fromCharCode(c);\n        }\n        return String.fromCharCode(\n          (c - 65536 >> 10) + 55296,\n          (c - 65536 & 1023) + 56320\n        );\n      }\n      function setProperty(object, key, value) {\n        if (key === "__proto__") {\n          Object.defineProperty(object, key, {\n            configurable: true,\n            enumerable: true,\n            writable: true,\n            value\n          });\n        } else {\n          object[key] = value;\n        }\n      }\n      var simpleEscapeCheck = new Array(256);\n      var simpleEscapeMap = new Array(256);\n      for (i = 0; i < 256; i++) {\n        simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;\n        simpleEscapeMap[i] = simpleEscapeSequence(i);\n      }\n      var i;\n      function State(input, options) {\n        this.input = input;\n        this.filename = options["filename"] || null;\n        this.schema = options["schema"] || DEFAULT_SCHEMA;\n        this.onWarning = options["onWarning"] || null;\n        this.legacy = options["legacy"] || false;\n        this.json = options["json"] || false;\n        this.listener = options["listener"] || null;\n        this.implicitTypes = this.schema.compiledImplicit;\n        this.typeMap = this.schema.compiledTypeMap;\n        this.length = input.length;\n        this.position = 0;\n        this.line = 0;\n        this.lineStart = 0;\n        this.lineIndent = 0;\n        this.firstTabInLine = -1;\n        this.documents = [];\n      }\n      function generateError(state, message) {\n        var mark = {\n          name: state.filename,\n          buffer: state.input.slice(0, -1),\n          // omit trailing \\0\n          position: state.position,\n          line: state.line,\n          column: state.position - state.lineStart\n        };\n        mark.snippet = makeSnippet(mark);\n        return new YAMLException(message, mark);\n      }\n      function throwError(state, message) {\n        throw generateError(state, message);\n      }\n      function throwWarning(state, message) {\n        if (state.onWarning) {\n          state.onWarning.call(null, generateError(state, message));\n        }\n      }\n      var directiveHandlers = {\n        YAML: function handleYamlDirective(state, name2, args) {\n          var match, major, minor;\n          if (state.version !== null) {\n            throwError(state, "duplication of %YAML directive");\n          }\n          if (args.length !== 1) {\n            throwError(state, "YAML directive accepts exactly one argument");\n          }\n          match = /^([0-9]+)\\.([0-9]+)$/.exec(args[0]);\n          if (match === null) {\n            throwError(state, "ill-formed argument of the YAML directive");\n          }\n          major = parseInt(match[1], 10);\n          minor = parseInt(match[2], 10);\n          if (major !== 1) {\n            throwError(state, "unacceptable YAML version of the document");\n          }\n          state.version = args[0];\n          state.checkLineBreaks = minor < 2;\n          if (minor !== 1 && minor !== 2) {\n            throwWarning(state, "unsupported YAML version of the document");\n          }\n        },\n        TAG: function handleTagDirective(state, name2, args) {\n          var handle, prefix;\n          if (args.length !== 2) {\n            throwError(state, "TAG directive accepts exactly two arguments");\n          }\n          handle = args[0];\n          prefix = args[1];\n          if (!PATTERN_TAG_HANDLE.test(handle)) {\n            throwError(state, "ill-formed tag handle (first argument) of the TAG directive");\n          }\n          if (_hasOwnProperty.call(state.tagMap, handle)) {\n            throwError(state, \'there is a previously declared suffix for "\' + handle + \'" tag handle\');\n          }\n          if (!PATTERN_TAG_URI.test(prefix)) {\n            throwError(state, "ill-formed tag prefix (second argument) of the TAG directive");\n          }\n          try {\n            prefix = decodeURIComponent(prefix);\n          } catch (err) {\n            throwError(state, "tag prefix is malformed: " + prefix);\n          }\n          state.tagMap[handle] = prefix;\n        }\n      };\n      function captureSegment(state, start, end, checkJson) {\n        var _position, _length, _character, _result;\n        if (start < end) {\n          _result = state.input.slice(start, end);\n          if (checkJson) {\n            for (_position = 0, _length = _result.length; _position < _length; _position += 1) {\n              _character = _result.charCodeAt(_position);\n              if (!(_character === 9 || 32 <= _character && _character <= 1114111)) {\n                throwError(state, "expected valid JSON character");\n              }\n            }\n          } else if (PATTERN_NON_PRINTABLE.test(_result)) {\n            throwError(state, "the stream contains non-printable characters");\n          }\n          state.result += _result;\n        }\n      }\n      function mergeMappings(state, destination, source, overridableKeys) {\n        var sourceKeys, key, index, quantity;\n        if (!common.isObject(source)) {\n          throwError(state, "cannot merge mappings; the provided source object is unacceptable");\n        }\n        sourceKeys = Object.keys(source);\n        for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {\n          key = sourceKeys[index];\n          if (!_hasOwnProperty.call(destination, key)) {\n            setProperty(destination, key, source[key]);\n            overridableKeys[key] = true;\n          }\n        }\n      }\n      function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) {\n        var index, quantity;\n        if (Array.isArray(keyNode)) {\n          keyNode = Array.prototype.slice.call(keyNode);\n          for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {\n            if (Array.isArray(keyNode[index])) {\n              throwError(state, "nested arrays are not supported inside keys");\n            }\n            if (typeof keyNode === "object" && _class(keyNode[index]) === "[object Object]") {\n              keyNode[index] = "[object Object]";\n            }\n          }\n        }\n        if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") {\n          keyNode = "[object Object]";\n        }\n        keyNode = String(keyNode);\n        if (_result === null) {\n          _result = {};\n        }\n        if (keyTag === "tag:yaml.org,2002:merge") {\n          if (Array.isArray(valueNode)) {\n            for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {\n              mergeMappings(state, _result, valueNode[index], overridableKeys);\n            }\n          } else {\n            mergeMappings(state, _result, valueNode, overridableKeys);\n          }\n        } else {\n          if (!state.json && !_hasOwnProperty.call(overridableKeys, keyNode) && _hasOwnProperty.call(_result, keyNode)) {\n            state.line = startLine || state.line;\n            state.lineStart = startLineStart || state.lineStart;\n            state.position = startPos || state.position;\n            throwError(state, "duplicated mapping key");\n          }\n          setProperty(_result, keyNode, valueNode);\n          delete overridableKeys[keyNode];\n        }\n        return _result;\n      }\n      function readLineBreak(state) {\n        var ch;\n        ch = state.input.charCodeAt(state.position);\n        if (ch === 10) {\n          state.position++;\n        } else if (ch === 13) {\n          state.position++;\n          if (state.input.charCodeAt(state.position) === 10) {\n            state.position++;\n          }\n        } else {\n          throwError(state, "a line break is expected");\n        }\n        state.line += 1;\n        state.lineStart = state.position;\n        state.firstTabInLine = -1;\n      }\n      function skipSeparationSpace(state, allowComments, checkIndent) {\n        var lineBreaks = 0, ch = state.input.charCodeAt(state.position);\n        while (ch !== 0) {\n          while (is_WHITE_SPACE(ch)) {\n            if (ch === 9 && state.firstTabInLine === -1) {\n              state.firstTabInLine = state.position;\n            }\n            ch = state.input.charCodeAt(++state.position);\n          }\n          if (allowComments && ch === 35) {\n            do {\n              ch = state.input.charCodeAt(++state.position);\n            } while (ch !== 10 && ch !== 13 && ch !== 0);\n          }\n          if (is_EOL(ch)) {\n            readLineBreak(state);\n            ch = state.input.charCodeAt(state.position);\n            lineBreaks++;\n            state.lineIndent = 0;\n            while (ch === 32) {\n              state.lineIndent++;\n              ch = state.input.charCodeAt(++state.position);\n            }\n          } else {\n            break;\n          }\n        }\n        if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {\n          throwWarning(state, "deficient indentation");\n        }\n        return lineBreaks;\n      }\n      function testDocumentSeparator(state) {\n        var _position = state.position, ch;\n        ch = state.input.charCodeAt(_position);\n        if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) {\n          _position += 3;\n          ch = state.input.charCodeAt(_position);\n          if (ch === 0 || is_WS_OR_EOL(ch)) {\n            return true;\n          }\n        }\n        return false;\n      }\n      function writeFoldedLines(state, count) {\n        if (count === 1) {\n          state.result += " ";\n        } else if (count > 1) {\n          state.result += common.repeat("\\n", count - 1);\n        }\n      }\n      function readPlainScalar(state, nodeIndent, withinFlowCollection) {\n        var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch;\n        ch = state.input.charCodeAt(state.position);\n        if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) {\n          return false;\n        }\n        if (ch === 63 || ch === 45) {\n          following = state.input.charCodeAt(state.position + 1);\n          if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {\n            return false;\n          }\n        }\n        state.kind = "scalar";\n        state.result = "";\n        captureStart = captureEnd = state.position;\n        hasPendingContent = false;\n        while (ch !== 0) {\n          if (ch === 58) {\n            following = state.input.charCodeAt(state.position + 1);\n            if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {\n              break;\n            }\n          } else if (ch === 35) {\n            preceding = state.input.charCodeAt(state.position - 1);\n            if (is_WS_OR_EOL(preceding)) {\n              break;\n            }\n          } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && is_FLOW_INDICATOR(ch)) {\n            break;\n          } else if (is_EOL(ch)) {\n            _line = state.line;\n            _lineStart = state.lineStart;\n            _lineIndent = state.lineIndent;\n            skipSeparationSpace(state, false, -1);\n            if (state.lineIndent >= nodeIndent) {\n              hasPendingContent = true;\n              ch = state.input.charCodeAt(state.position);\n              continue;\n            } else {\n              state.position = captureEnd;\n              state.line = _line;\n              state.lineStart = _lineStart;\n              state.lineIndent = _lineIndent;\n              break;\n            }\n          }\n          if (hasPendingContent) {\n            captureSegment(state, captureStart, captureEnd, false);\n            writeFoldedLines(state, state.line - _line);\n            captureStart = captureEnd = state.position;\n            hasPendingContent = false;\n          }\n          if (!is_WHITE_SPACE(ch)) {\n            captureEnd = state.position + 1;\n          }\n          ch = state.input.charCodeAt(++state.position);\n        }\n        captureSegment(state, captureStart, captureEnd, false);\n        if (state.result) {\n          return true;\n        }\n        state.kind = _kind;\n        state.result = _result;\n        return false;\n      }\n      function readSingleQuotedScalar(state, nodeIndent) {\n        var ch, captureStart, captureEnd;\n        ch = state.input.charCodeAt(state.position);\n        if (ch !== 39) {\n          return false;\n        }\n        state.kind = "scalar";\n        state.result = "";\n        state.position++;\n        captureStart = captureEnd = state.position;\n        while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n          if (ch === 39) {\n            captureSegment(state, captureStart, state.position, true);\n            ch = state.input.charCodeAt(++state.position);\n            if (ch === 39) {\n              captureStart = state.position;\n              state.position++;\n              captureEnd = state.position;\n            } else {\n              return true;\n            }\n          } else if (is_EOL(ch)) {\n            captureSegment(state, captureStart, captureEnd, true);\n            writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));\n            captureStart = captureEnd = state.position;\n          } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n            throwError(state, "unexpected end of the document within a single quoted scalar");\n          } else {\n            state.position++;\n            captureEnd = state.position;\n          }\n        }\n        throwError(state, "unexpected end of the stream within a single quoted scalar");\n      }\n      function readDoubleQuotedScalar(state, nodeIndent) {\n        var captureStart, captureEnd, hexLength, hexResult, tmp, ch;\n        ch = state.input.charCodeAt(state.position);\n        if (ch !== 34) {\n          return false;\n        }\n        state.kind = "scalar";\n        state.result = "";\n        state.position++;\n        captureStart = captureEnd = state.position;\n        while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n          if (ch === 34) {\n            captureSegment(state, captureStart, state.position, true);\n            state.position++;\n            return true;\n          } else if (ch === 92) {\n            captureSegment(state, captureStart, state.position, true);\n            ch = state.input.charCodeAt(++state.position);\n            if (is_EOL(ch)) {\n              skipSeparationSpace(state, false, nodeIndent);\n            } else if (ch < 256 && simpleEscapeCheck[ch]) {\n              state.result += simpleEscapeMap[ch];\n              state.position++;\n            } else if ((tmp = escapedHexLen(ch)) > 0) {\n              hexLength = tmp;\n              hexResult = 0;\n              for (; hexLength > 0; hexLength--) {\n                ch = state.input.charCodeAt(++state.position);\n                if ((tmp = fromHexCode(ch)) >= 0) {\n                  hexResult = (hexResult << 4) + tmp;\n                } else {\n                  throwError(state, "expected hexadecimal character");\n                }\n              }\n              state.result += charFromCodepoint(hexResult);\n              state.position++;\n            } else {\n              throwError(state, "unknown escape sequence");\n            }\n            captureStart = captureEnd = state.position;\n          } else if (is_EOL(ch)) {\n            captureSegment(state, captureStart, captureEnd, true);\n            writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));\n            captureStart = captureEnd = state.position;\n          } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n            throwError(state, "unexpected end of the document within a double quoted scalar");\n          } else {\n            state.position++;\n            captureEnd = state.position;\n          }\n        }\n        throwError(state, "unexpected end of the stream within a double quoted scalar");\n      }\n      function readFlowCollection(state, nodeIndent) {\n        var readNext = true, _line, _lineStart, _pos, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = /* @__PURE__ */ Object.create(null), keyNode, keyTag, valueNode, ch;\n        ch = state.input.charCodeAt(state.position);\n        if (ch === 91) {\n          terminator = 93;\n          isMapping = false;\n          _result = [];\n        } else if (ch === 123) {\n          terminator = 125;\n          isMapping = true;\n          _result = {};\n        } else {\n          return false;\n        }\n        if (state.anchor !== null) {\n          state.anchorMap[state.anchor] = _result;\n        }\n        ch = state.input.charCodeAt(++state.position);\n        while (ch !== 0) {\n          skipSeparationSpace(state, true, nodeIndent);\n          ch = state.input.charCodeAt(state.position);\n          if (ch === terminator) {\n            state.position++;\n            state.tag = _tag;\n            state.anchor = _anchor;\n            state.kind = isMapping ? "mapping" : "sequence";\n            state.result = _result;\n            return true;\n          } else if (!readNext) {\n            throwError(state, "missed comma between flow collection entries");\n          } else if (ch === 44) {\n            throwError(state, "expected the node content, but found \',\'");\n          }\n          keyTag = keyNode = valueNode = null;\n          isPair = isExplicitPair = false;\n          if (ch === 63) {\n            following = state.input.charCodeAt(state.position + 1);\n            if (is_WS_OR_EOL(following)) {\n              isPair = isExplicitPair = true;\n              state.position++;\n              skipSeparationSpace(state, true, nodeIndent);\n            }\n          }\n          _line = state.line;\n          _lineStart = state.lineStart;\n          _pos = state.position;\n          composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);\n          keyTag = state.tag;\n          keyNode = state.result;\n          skipSeparationSpace(state, true, nodeIndent);\n          ch = state.input.charCodeAt(state.position);\n          if ((isExplicitPair || state.line === _line) && ch === 58) {\n            isPair = true;\n            ch = state.input.charCodeAt(++state.position);\n            skipSeparationSpace(state, true, nodeIndent);\n            composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);\n            valueNode = state.result;\n          }\n          if (isMapping) {\n            storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);\n          } else if (isPair) {\n            _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));\n          } else {\n            _result.push(keyNode);\n          }\n          skipSeparationSpace(state, true, nodeIndent);\n          ch = state.input.charCodeAt(state.position);\n          if (ch === 44) {\n            readNext = true;\n            ch = state.input.charCodeAt(++state.position);\n          } else {\n            readNext = false;\n          }\n        }\n        throwError(state, "unexpected end of the stream within a flow collection");\n      }\n      function readBlockScalar(state, nodeIndent) {\n        var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch;\n        ch = state.input.charCodeAt(state.position);\n        if (ch === 124) {\n          folding = false;\n        } else if (ch === 62) {\n          folding = true;\n        } else {\n          return false;\n        }\n        state.kind = "scalar";\n        state.result = "";\n        while (ch !== 0) {\n          ch = state.input.charCodeAt(++state.position);\n          if (ch === 43 || ch === 45) {\n            if (CHOMPING_CLIP === chomping) {\n              chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP;\n            } else {\n              throwError(state, "repeat of a chomping mode identifier");\n            }\n          } else if ((tmp = fromDecimalCode(ch)) >= 0) {\n            if (tmp === 0) {\n              throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one");\n            } else if (!detectedIndent) {\n              textIndent = nodeIndent + tmp - 1;\n              detectedIndent = true;\n            } else {\n              throwError(state, "repeat of an indentation width identifier");\n            }\n          } else {\n            break;\n          }\n        }\n        if (is_WHITE_SPACE(ch)) {\n          do {\n            ch = state.input.charCodeAt(++state.position);\n          } while (is_WHITE_SPACE(ch));\n          if (ch === 35) {\n            do {\n              ch = state.input.charCodeAt(++state.position);\n            } while (!is_EOL(ch) && ch !== 0);\n          }\n        }\n        while (ch !== 0) {\n          readLineBreak(state);\n          state.lineIndent = 0;\n          ch = state.input.charCodeAt(state.position);\n          while ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) {\n            state.lineIndent++;\n            ch = state.input.charCodeAt(++state.position);\n          }\n          if (!detectedIndent && state.lineIndent > textIndent) {\n            textIndent = state.lineIndent;\n          }\n          if (is_EOL(ch)) {\n            emptyLines++;\n            continue;\n          }\n          if (state.lineIndent < textIndent) {\n            if (chomping === CHOMPING_KEEP) {\n              state.result += common.repeat("\\n", didReadContent ? 1 + emptyLines : emptyLines);\n            } else if (chomping === CHOMPING_CLIP) {\n              if (didReadContent) {\n                state.result += "\\n";\n              }\n            }\n            break;\n          }\n          if (folding) {\n            if (is_WHITE_SPACE(ch)) {\n              atMoreIndented = true;\n              state.result += common.repeat("\\n", didReadContent ? 1 + emptyLines : emptyLines);\n            } else if (atMoreIndented) {\n              atMoreIndented = false;\n              state.result += common.repeat("\\n", emptyLines + 1);\n            } else if (emptyLines === 0) {\n              if (didReadContent) {\n                state.result += " ";\n              }\n            } else {\n              state.result += common.repeat("\\n", emptyLines);\n            }\n          } else {\n            state.result += common.repeat("\\n", didReadContent ? 1 + emptyLines : emptyLines);\n          }\n          didReadContent = true;\n          detectedIndent = true;\n          emptyLines = 0;\n          captureStart = state.position;\n          while (!is_EOL(ch) && ch !== 0) {\n            ch = state.input.charCodeAt(++state.position);\n          }\n          captureSegment(state, captureStart, state.position, false);\n        }\n        return true;\n      }\n      function readBlockSequence(state, nodeIndent) {\n        var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch;\n        if (state.firstTabInLine !== -1) return false;\n        if (state.anchor !== null) {\n          state.anchorMap[state.anchor] = _result;\n        }\n        ch = state.input.charCodeAt(state.position);\n        while (ch !== 0) {\n          if (state.firstTabInLine !== -1) {\n            state.position = state.firstTabInLine;\n            throwError(state, "tab characters must not be used in indentation");\n          }\n          if (ch !== 45) {\n            break;\n          }\n          following = state.input.charCodeAt(state.position + 1);\n          if (!is_WS_OR_EOL(following)) {\n            break;\n          }\n          detected = true;\n          state.position++;\n          if (skipSeparationSpace(state, true, -1)) {\n            if (state.lineIndent <= nodeIndent) {\n              _result.push(null);\n              ch = state.input.charCodeAt(state.position);\n              continue;\n            }\n          }\n          _line = state.line;\n          composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);\n          _result.push(state.result);\n          skipSeparationSpace(state, true, -1);\n          ch = state.input.charCodeAt(state.position);\n          if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {\n            throwError(state, "bad indentation of a sequence entry");\n          } else if (state.lineIndent < nodeIndent) {\n            break;\n          }\n        }\n        if (detected) {\n          state.tag = _tag;\n          state.anchor = _anchor;\n          state.kind = "sequence";\n          state.result = _result;\n          return true;\n        }\n        return false;\n      }\n      function readBlockMapping(state, nodeIndent, flowIndent) {\n        var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = /* @__PURE__ */ Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch;\n        if (state.firstTabInLine !== -1) return false;\n        if (state.anchor !== null) {\n          state.anchorMap[state.anchor] = _result;\n        }\n        ch = state.input.charCodeAt(state.position);\n        while (ch !== 0) {\n          if (!atExplicitKey && state.firstTabInLine !== -1) {\n            state.position = state.firstTabInLine;\n            throwError(state, "tab characters must not be used in indentation");\n          }\n          following = state.input.charCodeAt(state.position + 1);\n          _line = state.line;\n          if ((ch === 63 || ch === 58) && is_WS_OR_EOL(following)) {\n            if (ch === 63) {\n              if (atExplicitKey) {\n                storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);\n                keyTag = keyNode = valueNode = null;\n              }\n              detected = true;\n              atExplicitKey = true;\n              allowCompact = true;\n            } else if (atExplicitKey) {\n              atExplicitKey = false;\n              allowCompact = true;\n            } else {\n              throwError(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");\n            }\n            state.position += 1;\n            ch = following;\n          } else {\n            _keyLine = state.line;\n            _keyLineStart = state.lineStart;\n            _keyPos = state.position;\n            if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {\n              break;\n            }\n            if (state.line === _line) {\n              ch = state.input.charCodeAt(state.position);\n              while (is_WHITE_SPACE(ch)) {\n                ch = state.input.charCodeAt(++state.position);\n              }\n              if (ch === 58) {\n                ch = state.input.charCodeAt(++state.position);\n                if (!is_WS_OR_EOL(ch)) {\n                  throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");\n                }\n                if (atExplicitKey) {\n                  storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);\n                  keyTag = keyNode = valueNode = null;\n                }\n                detected = true;\n                atExplicitKey = false;\n                allowCompact = false;\n                keyTag = state.tag;\n                keyNode = state.result;\n              } else if (detected) {\n                throwError(state, "can not read an implicit mapping pair; a colon is missed");\n              } else {\n                state.tag = _tag;\n                state.anchor = _anchor;\n                return true;\n              }\n            } else if (detected) {\n              throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key");\n            } else {\n              state.tag = _tag;\n              state.anchor = _anchor;\n              return true;\n            }\n          }\n          if (state.line === _line || state.lineIndent > nodeIndent) {\n            if (atExplicitKey) {\n              _keyLine = state.line;\n              _keyLineStart = state.lineStart;\n              _keyPos = state.position;\n            }\n            if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {\n              if (atExplicitKey) {\n                keyNode = state.result;\n              } else {\n                valueNode = state.result;\n              }\n            }\n            if (!atExplicitKey) {\n              storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);\n              keyTag = keyNode = valueNode = null;\n            }\n            skipSeparationSpace(state, true, -1);\n            ch = state.input.charCodeAt(state.position);\n          }\n          if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {\n            throwError(state, "bad indentation of a mapping entry");\n          } else if (state.lineIndent < nodeIndent) {\n            break;\n          }\n        }\n        if (atExplicitKey) {\n          storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);\n        }\n        if (detected) {\n          state.tag = _tag;\n          state.anchor = _anchor;\n          state.kind = "mapping";\n          state.result = _result;\n        }\n        return detected;\n      }\n      function readTagProperty(state) {\n        var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch;\n        ch = state.input.charCodeAt(state.position);\n        if (ch !== 33) return false;\n        if (state.tag !== null) {\n          throwError(state, "duplication of a tag property");\n        }\n        ch = state.input.charCodeAt(++state.position);\n        if (ch === 60) {\n          isVerbatim = true;\n          ch = state.input.charCodeAt(++state.position);\n        } else if (ch === 33) {\n          isNamed = true;\n          tagHandle = "!!";\n          ch = state.input.charCodeAt(++state.position);\n        } else {\n          tagHandle = "!";\n        }\n        _position = state.position;\n        if (isVerbatim) {\n          do {\n            ch = state.input.charCodeAt(++state.position);\n          } while (ch !== 0 && ch !== 62);\n          if (state.position < state.length) {\n            tagName = state.input.slice(_position, state.position);\n            ch = state.input.charCodeAt(++state.position);\n          } else {\n            throwError(state, "unexpected end of the stream within a verbatim tag");\n          }\n        } else {\n          while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n            if (ch === 33) {\n              if (!isNamed) {\n                tagHandle = state.input.slice(_position - 1, state.position + 1);\n                if (!PATTERN_TAG_HANDLE.test(tagHandle)) {\n                  throwError(state, "named tag handle cannot contain such characters");\n                }\n                isNamed = true;\n                _position = state.position + 1;\n              } else {\n                throwError(state, "tag suffix cannot contain exclamation marks");\n              }\n            }\n            ch = state.input.charCodeAt(++state.position);\n          }\n          tagName = state.input.slice(_position, state.position);\n          if (PATTERN_FLOW_INDICATORS.test(tagName)) {\n            throwError(state, "tag suffix cannot contain flow indicator characters");\n          }\n        }\n        if (tagName && !PATTERN_TAG_URI.test(tagName)) {\n          throwError(state, "tag name cannot contain such characters: " + tagName);\n        }\n        try {\n          tagName = decodeURIComponent(tagName);\n        } catch (err) {\n          throwError(state, "tag name is malformed: " + tagName);\n        }\n        if (isVerbatim) {\n          state.tag = tagName;\n        } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {\n          state.tag = state.tagMap[tagHandle] + tagName;\n        } else if (tagHandle === "!") {\n          state.tag = "!" + tagName;\n        } else if (tagHandle === "!!") {\n          state.tag = "tag:yaml.org,2002:" + tagName;\n        } else {\n          throwError(state, \'undeclared tag handle "\' + tagHandle + \'"\');\n        }\n        return true;\n      }\n      function readAnchorProperty(state) {\n        var _position, ch;\n        ch = state.input.charCodeAt(state.position);\n        if (ch !== 38) return false;\n        if (state.anchor !== null) {\n          throwError(state, "duplication of an anchor property");\n        }\n        ch = state.input.charCodeAt(++state.position);\n        _position = state.position;\n        while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {\n          ch = state.input.charCodeAt(++state.position);\n        }\n        if (state.position === _position) {\n          throwError(state, "name of an anchor node must contain at least one character");\n        }\n        state.anchor = state.input.slice(_position, state.position);\n        return true;\n      }\n      function readAlias(state) {\n        var _position, alias, ch;\n        ch = state.input.charCodeAt(state.position);\n        if (ch !== 42) return false;\n        ch = state.input.charCodeAt(++state.position);\n        _position = state.position;\n        while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {\n          ch = state.input.charCodeAt(++state.position);\n        }\n        if (state.position === _position) {\n          throwError(state, "name of an alias node must contain at least one character");\n        }\n        alias = state.input.slice(_position, state.position);\n        if (!_hasOwnProperty.call(state.anchorMap, alias)) {\n          throwError(state, \'unidentified alias "\' + alias + \'"\');\n        }\n        state.result = state.anchorMap[alias];\n        skipSeparationSpace(state, true, -1);\n        return true;\n      }\n      function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {\n        var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, typeIndex, typeQuantity, typeList, type, flowIndent, blockIndent;\n        if (state.listener !== null) {\n          state.listener("open", state);\n        }\n        state.tag = null;\n        state.anchor = null;\n        state.kind = null;\n        state.result = null;\n        allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;\n        if (allowToSeek) {\n          if (skipSeparationSpace(state, true, -1)) {\n            atNewLine = true;\n            if (state.lineIndent > parentIndent) {\n              indentStatus = 1;\n            } else if (state.lineIndent === parentIndent) {\n              indentStatus = 0;\n            } else if (state.lineIndent < parentIndent) {\n              indentStatus = -1;\n            }\n          }\n        }\n        if (indentStatus === 1) {\n          while (readTagProperty(state) || readAnchorProperty(state)) {\n            if (skipSeparationSpace(state, true, -1)) {\n              atNewLine = true;\n              allowBlockCollections = allowBlockStyles;\n              if (state.lineIndent > parentIndent) {\n                indentStatus = 1;\n              } else if (state.lineIndent === parentIndent) {\n                indentStatus = 0;\n              } else if (state.lineIndent < parentIndent) {\n                indentStatus = -1;\n              }\n            } else {\n              allowBlockCollections = false;\n            }\n          }\n        }\n        if (allowBlockCollections) {\n          allowBlockCollections = atNewLine || allowCompact;\n        }\n        if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {\n          if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {\n            flowIndent = parentIndent;\n          } else {\n            flowIndent = parentIndent + 1;\n          }\n          blockIndent = state.position - state.lineStart;\n          if (indentStatus === 1) {\n            if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) {\n              hasContent = true;\n            } else {\n              if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) {\n                hasContent = true;\n              } else if (readAlias(state)) {\n                hasContent = true;\n                if (state.tag !== null || state.anchor !== null) {\n                  throwError(state, "alias node should not have any properties");\n                }\n              } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {\n                hasContent = true;\n                if (state.tag === null) {\n                  state.tag = "?";\n                }\n              }\n              if (state.anchor !== null) {\n                state.anchorMap[state.anchor] = state.result;\n              }\n            }\n          } else if (indentStatus === 0) {\n            hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);\n          }\n        }\n        if (state.tag === null) {\n          if (state.anchor !== null) {\n            state.anchorMap[state.anchor] = state.result;\n          }\n        } else if (state.tag === "?") {\n          if (state.result !== null && state.kind !== "scalar") {\n            throwError(state, \'unacceptable node kind for !<?> tag; it should be "scalar", not "\' + state.kind + \'"\');\n          }\n          for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {\n            type = state.implicitTypes[typeIndex];\n            if (type.resolve(state.result)) {\n              state.result = type.construct(state.result);\n              state.tag = type.tag;\n              if (state.anchor !== null) {\n                state.anchorMap[state.anchor] = state.result;\n              }\n              break;\n            }\n          }\n        } else if (state.tag !== "!") {\n          if (_hasOwnProperty.call(state.typeMap[state.kind || "fallback"], state.tag)) {\n            type = state.typeMap[state.kind || "fallback"][state.tag];\n          } else {\n            type = null;\n            typeList = state.typeMap.multi[state.kind || "fallback"];\n            for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {\n              if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {\n                type = typeList[typeIndex];\n                break;\n              }\n            }\n          }\n          if (!type) {\n            throwError(state, "unknown tag !<" + state.tag + ">");\n          }\n          if (state.result !== null && type.kind !== state.kind) {\n            throwError(state, "unacceptable node kind for !<" + state.tag + \'> tag; it should be "\' + type.kind + \'", not "\' + state.kind + \'"\');\n          }\n          if (!type.resolve(state.result, state.tag)) {\n            throwError(state, "cannot resolve a node with !<" + state.tag + "> explicit tag");\n          } else {\n            state.result = type.construct(state.result, state.tag);\n            if (state.anchor !== null) {\n              state.anchorMap[state.anchor] = state.result;\n            }\n          }\n        }\n        if (state.listener !== null) {\n          state.listener("close", state);\n        }\n        return state.tag !== null || state.anchor !== null || hasContent;\n      }\n      function readDocument(state) {\n        var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch;\n        state.version = null;\n        state.checkLineBreaks = state.legacy;\n        state.tagMap = /* @__PURE__ */ Object.create(null);\n        state.anchorMap = /* @__PURE__ */ Object.create(null);\n        while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n          skipSeparationSpace(state, true, -1);\n          ch = state.input.charCodeAt(state.position);\n          if (state.lineIndent > 0 || ch !== 37) {\n            break;\n          }\n          hasDirectives = true;\n          ch = state.input.charCodeAt(++state.position);\n          _position = state.position;\n          while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n            ch = state.input.charCodeAt(++state.position);\n          }\n          directiveName = state.input.slice(_position, state.position);\n          directiveArgs = [];\n          if (directiveName.length < 1) {\n            throwError(state, "directive name must not be less than one character in length");\n          }\n          while (ch !== 0) {\n            while (is_WHITE_SPACE(ch)) {\n              ch = state.input.charCodeAt(++state.position);\n            }\n            if (ch === 35) {\n              do {\n                ch = state.input.charCodeAt(++state.position);\n              } while (ch !== 0 && !is_EOL(ch));\n              break;\n            }\n            if (is_EOL(ch)) break;\n            _position = state.position;\n            while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n              ch = state.input.charCodeAt(++state.position);\n            }\n            directiveArgs.push(state.input.slice(_position, state.position));\n          }\n          if (ch !== 0) readLineBreak(state);\n          if (_hasOwnProperty.call(directiveHandlers, directiveName)) {\n            directiveHandlers[directiveName](state, directiveName, directiveArgs);\n          } else {\n            throwWarning(state, \'unknown document directive "\' + directiveName + \'"\');\n          }\n        }\n        skipSeparationSpace(state, true, -1);\n        if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) {\n          state.position += 3;\n          skipSeparationSpace(state, true, -1);\n        } else if (hasDirectives) {\n          throwError(state, "directives end mark is expected");\n        }\n        composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);\n        skipSeparationSpace(state, true, -1);\n        if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {\n          throwWarning(state, "non-ASCII line breaks are interpreted as content");\n        }\n        state.documents.push(state.result);\n        if (state.position === state.lineStart && testDocumentSeparator(state)) {\n          if (state.input.charCodeAt(state.position) === 46) {\n            state.position += 3;\n            skipSeparationSpace(state, true, -1);\n          }\n          return;\n        }\n        if (state.position < state.length - 1) {\n          throwError(state, "end of the stream or a document separator is expected");\n        } else {\n          return;\n        }\n      }\n      function loadDocuments(input, options) {\n        input = String(input);\n        options = options || {};\n        if (input.length !== 0) {\n          if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) {\n            input += "\\n";\n          }\n          if (input.charCodeAt(0) === 65279) {\n            input = input.slice(1);\n          }\n        }\n        var state = new State(input, options);\n        var nullpos = input.indexOf("\\0");\n        if (nullpos !== -1) {\n          state.position = nullpos;\n          throwError(state, "null byte is not allowed in input");\n        }\n        state.input += "\\0";\n        while (state.input.charCodeAt(state.position) === 32) {\n          state.lineIndent += 1;\n          state.position += 1;\n        }\n        while (state.position < state.length - 1) {\n          readDocument(state);\n        }\n        return state.documents;\n      }\n      function loadAll(input, iterator, options) {\n        if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") {\n          options = iterator;\n          iterator = null;\n        }\n        var documents = loadDocuments(input, options);\n        if (typeof iterator !== "function") {\n          return documents;\n        }\n        for (var index = 0, length = documents.length; index < length; index += 1) {\n          iterator(documents[index]);\n        }\n      }\n      function load(input, options) {\n        var documents = loadDocuments(input, options);\n        if (documents.length === 0) {\n          return void 0;\n        } else if (documents.length === 1) {\n          return documents[0];\n        }\n        throw new YAMLException("expected a single document in the stream, but found more");\n      }\n      module2.exports.loadAll = loadAll;\n      module2.exports.load = load;\n    }\n  });\n\n  // node_modules/js-yaml/lib/dumper.js\n  var require_dumper = __commonJS({\n    "node_modules/js-yaml/lib/dumper.js"(exports2, module2) {\n      "use strict";\n      var common = require_common();\n      var YAMLException = require_exception();\n      var DEFAULT_SCHEMA = require_default();\n      var _toString = Object.prototype.toString;\n      var _hasOwnProperty = Object.prototype.hasOwnProperty;\n      var CHAR_BOM = 65279;\n      var CHAR_TAB = 9;\n      var CHAR_LINE_FEED = 10;\n      var CHAR_CARRIAGE_RETURN = 13;\n      var CHAR_SPACE = 32;\n      var CHAR_EXCLAMATION = 33;\n      var CHAR_DOUBLE_QUOTE = 34;\n      var CHAR_SHARP = 35;\n      var CHAR_PERCENT = 37;\n      var CHAR_AMPERSAND = 38;\n      var CHAR_SINGLE_QUOTE = 39;\n      var CHAR_ASTERISK = 42;\n      var CHAR_COMMA = 44;\n      var CHAR_MINUS = 45;\n      var CHAR_COLON = 58;\n      var CHAR_EQUALS = 61;\n      var CHAR_GREATER_THAN = 62;\n      var CHAR_QUESTION = 63;\n      var CHAR_COMMERCIAL_AT = 64;\n      var CHAR_LEFT_SQUARE_BRACKET = 91;\n      var CHAR_RIGHT_SQUARE_BRACKET = 93;\n      var CHAR_GRAVE_ACCENT = 96;\n      var CHAR_LEFT_CURLY_BRACKET = 123;\n      var CHAR_VERTICAL_LINE = 124;\n      var CHAR_RIGHT_CURLY_BRACKET = 125;\n      var ESCAPE_SEQUENCES = {};\n      ESCAPE_SEQUENCES[0] = "\\\\0";\n      ESCAPE_SEQUENCES[7] = "\\\\a";\n      ESCAPE_SEQUENCES[8] = "\\\\b";\n      ESCAPE_SEQUENCES[9] = "\\\\t";\n      ESCAPE_SEQUENCES[10] = "\\\\n";\n      ESCAPE_SEQUENCES[11] = "\\\\v";\n      ESCAPE_SEQUENCES[12] = "\\\\f";\n      ESCAPE_SEQUENCES[13] = "\\\\r";\n      ESCAPE_SEQUENCES[27] = "\\\\e";\n      ESCAPE_SEQUENCES[34] = \'\\\\"\';\n      ESCAPE_SEQUENCES[92] = "\\\\\\\\";\n      ESCAPE_SEQUENCES[133] = "\\\\N";\n      ESCAPE_SEQUENCES[160] = "\\\\_";\n      ESCAPE_SEQUENCES[8232] = "\\\\L";\n      ESCAPE_SEQUENCES[8233] = "\\\\P";\n      var DEPRECATED_BOOLEANS_SYNTAX = [\n        "y",\n        "Y",\n        "yes",\n        "Yes",\n        "YES",\n        "on",\n        "On",\n        "ON",\n        "n",\n        "N",\n        "no",\n        "No",\n        "NO",\n        "off",\n        "Off",\n        "OFF"\n      ];\n      var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\\.[0-9_]*)?$/;\n      function compileStyleMap(schema, map) {\n        var result, keys, index, length, tag, style, type;\n        if (map === null) return {};\n        result = {};\n        keys = Object.keys(map);\n        for (index = 0, length = keys.length; index < length; index += 1) {\n          tag = keys[index];\n          style = String(map[tag]);\n          if (tag.slice(0, 2) === "!!") {\n            tag = "tag:yaml.org,2002:" + tag.slice(2);\n          }\n          type = schema.compiledTypeMap["fallback"][tag];\n          if (type && _hasOwnProperty.call(type.styleAliases, style)) {\n            style = type.styleAliases[style];\n          }\n          result[tag] = style;\n        }\n        return result;\n      }\n      function encodeHex(character) {\n        var string, handle, length;\n        string = character.toString(16).toUpperCase();\n        if (character <= 255) {\n          handle = "x";\n          length = 2;\n        } else if (character <= 65535) {\n          handle = "u";\n          length = 4;\n        } else if (character <= 4294967295) {\n          handle = "U";\n          length = 8;\n        } else {\n          throw new YAMLException("code point within a string may not be greater than 0xFFFFFFFF");\n        }\n        return "\\\\" + handle + common.repeat("0", length - string.length) + string;\n      }\n      var QUOTING_TYPE_SINGLE = 1;\n      var QUOTING_TYPE_DOUBLE = 2;\n      function State(options) {\n        this.schema = options["schema"] || DEFAULT_SCHEMA;\n        this.indent = Math.max(1, options["indent"] || 2);\n        this.noArrayIndent = options["noArrayIndent"] || false;\n        this.skipInvalid = options["skipInvalid"] || false;\n        this.flowLevel = common.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"];\n        this.styleMap = compileStyleMap(this.schema, options["styles"] || null);\n        this.sortKeys = options["sortKeys"] || false;\n        this.lineWidth = options["lineWidth"] || 80;\n        this.noRefs = options["noRefs"] || false;\n        this.noCompatMode = options["noCompatMode"] || false;\n        this.condenseFlow = options["condenseFlow"] || false;\n        this.quotingType = options["quotingType"] === \'"\' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;\n        this.forceQuotes = options["forceQuotes"] || false;\n        this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null;\n        this.implicitTypes = this.schema.compiledImplicit;\n        this.explicitTypes = this.schema.compiledExplicit;\n        this.tag = null;\n        this.result = "";\n        this.duplicates = [];\n        this.usedDuplicates = null;\n      }\n      function indentString(string, spaces) {\n        var ind = common.repeat(" ", spaces), position = 0, next = -1, result = "", line, length = string.length;\n        while (position < length) {\n          next = string.indexOf("\\n", position);\n          if (next === -1) {\n            line = string.slice(position);\n            position = length;\n          } else {\n            line = string.slice(position, next + 1);\n            position = next + 1;\n          }\n          if (line.length && line !== "\\n") result += ind;\n          result += line;\n        }\n        return result;\n      }\n      function generateNextLine(state, level) {\n        return "\\n" + common.repeat(" ", state.indent * level);\n      }\n      function testImplicitResolving(state, str) {\n        var index, length, type;\n        for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {\n          type = state.implicitTypes[index];\n          if (type.resolve(str)) {\n            return true;\n          }\n        }\n        return false;\n      }\n      function isWhitespace(c) {\n        return c === CHAR_SPACE || c === CHAR_TAB;\n      }\n      function isPrintable(c) {\n        return 32 <= c && c <= 126 || 161 <= c && c <= 55295 && c !== 8232 && c !== 8233 || 57344 <= c && c <= 65533 && c !== CHAR_BOM || 65536 <= c && c <= 1114111;\n      }\n      function isNsCharOrWhitespace(c) {\n        return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;\n      }\n      function isPlainSafe(c, prev, inblock) {\n        var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);\n        var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);\n        return (\n          // ns-plain-safe\n          (inblock ? (\n            // c = flow-in\n            cIsNsCharOrWhitespace\n          ) : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar\n        );\n      }\n      function isPlainSafeFirst(c) {\n        return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;\n      }\n      function isPlainSafeLast(c) {\n        return !isWhitespace(c) && c !== CHAR_COLON;\n      }\n      function codePointAt(string, pos) {\n        var first = string.charCodeAt(pos), second;\n        if (first >= 55296 && first <= 56319 && pos + 1 < string.length) {\n          second = string.charCodeAt(pos + 1);\n          if (second >= 56320 && second <= 57343) {\n            return (first - 55296) * 1024 + second - 56320 + 65536;\n          }\n        }\n        return first;\n      }\n      function needIndentIndicator(string) {\n        var leadingSpaceRe = /^\\n* /;\n        return leadingSpaceRe.test(string);\n      }\n      var STYLE_PLAIN = 1;\n      var STYLE_SINGLE = 2;\n      var STYLE_LITERAL = 3;\n      var STYLE_FOLDED = 4;\n      var STYLE_DOUBLE = 5;\n      function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) {\n        var i;\n        var char = 0;\n        var prevChar = null;\n        var hasLineBreak = false;\n        var hasFoldableLine = false;\n        var shouldTrackWidth = lineWidth !== -1;\n        var previousLineBreak = -1;\n        var plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));\n        if (singleLineOnly || forceQuotes) {\n          for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {\n            char = codePointAt(string, i);\n            if (!isPrintable(char)) {\n              return STYLE_DOUBLE;\n            }\n            plain = plain && isPlainSafe(char, prevChar, inblock);\n            prevChar = char;\n          }\n        } else {\n          for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {\n            char = codePointAt(string, i);\n            if (char === CHAR_LINE_FEED) {\n              hasLineBreak = true;\n              if (shouldTrackWidth) {\n                hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented.\n                i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ";\n                previousLineBreak = i;\n              }\n            } else if (!isPrintable(char)) {\n              return STYLE_DOUBLE;\n            }\n            plain = plain && isPlainSafe(char, prevChar, inblock);\n            prevChar = char;\n          }\n          hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");\n        }\n        if (!hasLineBreak && !hasFoldableLine) {\n          if (plain && !forceQuotes && !testAmbiguousType(string)) {\n            return STYLE_PLAIN;\n          }\n          return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;\n        }\n        if (indentPerLevel > 9 && needIndentIndicator(string)) {\n          return STYLE_DOUBLE;\n        }\n        if (!forceQuotes) {\n          return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;\n        }\n        return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;\n      }\n      function writeScalar(state, string, level, iskey, inblock) {\n        state.dump = (function() {\n          if (string.length === 0) {\n            return state.quotingType === QUOTING_TYPE_DOUBLE ? \'""\' : "\'\'";\n          }\n          if (!state.noCompatMode) {\n            if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {\n              return state.quotingType === QUOTING_TYPE_DOUBLE ? \'"\' + string + \'"\' : "\'" + string + "\'";\n            }\n          }\n          var indent = state.indent * Math.max(1, level);\n          var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);\n          var singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel;\n          function testAmbiguity(string2) {\n            return testImplicitResolving(state, string2);\n          }\n          switch (chooseScalarStyle(\n            string,\n            singleLineOnly,\n            state.indent,\n            lineWidth,\n            testAmbiguity,\n            state.quotingType,\n            state.forceQuotes && !iskey,\n            inblock\n          )) {\n            case STYLE_PLAIN:\n              return string;\n            case STYLE_SINGLE:\n              return "\'" + string.replace(/\'/g, "\'\'") + "\'";\n            case STYLE_LITERAL:\n              return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));\n            case STYLE_FOLDED:\n              return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));\n            case STYLE_DOUBLE:\n              return \'"\' + escapeString(string, lineWidth) + \'"\';\n            default:\n              throw new YAMLException("impossible error: invalid scalar style");\n          }\n        })();\n      }\n      function blockHeader(string, indentPerLevel) {\n        var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : "";\n        var clip = string[string.length - 1] === "\\n";\n        var keep = clip && (string[string.length - 2] === "\\n" || string === "\\n");\n        var chomp = keep ? "+" : clip ? "" : "-";\n        return indentIndicator + chomp + "\\n";\n      }\n      function dropEndingNewline(string) {\n        return string[string.length - 1] === "\\n" ? string.slice(0, -1) : string;\n      }\n      function foldString(string, width) {\n        var lineRe = /(\\n+)([^\\n]*)/g;\n        var result = (function() {\n          var nextLF = string.indexOf("\\n");\n          nextLF = nextLF !== -1 ? nextLF : string.length;\n          lineRe.lastIndex = nextLF;\n          return foldLine(string.slice(0, nextLF), width);\n        })();\n        var prevMoreIndented = string[0] === "\\n" || string[0] === " ";\n        var moreIndented;\n        var match;\n        while (match = lineRe.exec(string)) {\n          var prefix = match[1], line = match[2];\n          moreIndented = line[0] === " ";\n          result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\\n" : "") + foldLine(line, width);\n          prevMoreIndented = moreIndented;\n        }\n        return result;\n      }\n      function foldLine(line, width) {\n        if (line === "" || line[0] === " ") return line;\n        var breakRe = / [^ ]/g;\n        var match;\n        var start = 0, end, curr = 0, next = 0;\n        var result = "";\n        while (match = breakRe.exec(line)) {\n          next = match.index;\n          if (next - start > width) {\n            end = curr > start ? curr : next;\n            result += "\\n" + line.slice(start, end);\n            start = end + 1;\n          }\n          curr = next;\n        }\n        result += "\\n";\n        if (line.length - start > width && curr > start) {\n          result += line.slice(start, curr) + "\\n" + line.slice(curr + 1);\n        } else {\n          result += line.slice(start);\n        }\n        return result.slice(1);\n      }\n      function escapeString(string) {\n        var result = "";\n        var char = 0;\n        var escapeSeq;\n        for (var i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {\n          char = codePointAt(string, i);\n          escapeSeq = ESCAPE_SEQUENCES[char];\n          if (!escapeSeq && isPrintable(char)) {\n            result += string[i];\n            if (char >= 65536) result += string[i + 1];\n          } else {\n            result += escapeSeq || encodeHex(char);\n          }\n        }\n        return result;\n      }\n      function writeFlowSequence(state, level, object) {\n        var _result = "", _tag = state.tag, index, length, value;\n        for (index = 0, length = object.length; index < length; index += 1) {\n          value = object[index];\n          if (state.replacer) {\n            value = state.replacer.call(object, String(index), value);\n          }\n          if (writeNode(state, level, value, false, false) || typeof value === "undefined" && writeNode(state, level, null, false, false)) {\n            if (_result !== "") _result += "," + (!state.condenseFlow ? " " : "");\n            _result += state.dump;\n          }\n        }\n        state.tag = _tag;\n        state.dump = "[" + _result + "]";\n      }\n      function writeBlockSequence(state, level, object, compact) {\n        var _result = "", _tag = state.tag, index, length, value;\n        for (index = 0, length = object.length; index < length; index += 1) {\n          value = object[index];\n          if (state.replacer) {\n            value = state.replacer.call(object, String(index), value);\n          }\n          if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true)) {\n            if (!compact || _result !== "") {\n              _result += generateNextLine(state, level);\n            }\n            if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n              _result += "-";\n            } else {\n              _result += "- ";\n            }\n            _result += state.dump;\n          }\n        }\n        state.tag = _tag;\n        state.dump = _result || "[]";\n      }\n      function writeFlowMapping(state, level, object) {\n        var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, pairBuffer;\n        for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n          pairBuffer = "";\n          if (_result !== "") pairBuffer += ", ";\n          if (state.condenseFlow) pairBuffer += \'"\';\n          objectKey = objectKeyList[index];\n          objectValue = object[objectKey];\n          if (state.replacer) {\n            objectValue = state.replacer.call(object, objectKey, objectValue);\n          }\n          if (!writeNode(state, level, objectKey, false, false)) {\n            continue;\n          }\n          if (state.dump.length > 1024) pairBuffer += "? ";\n          pairBuffer += state.dump + (state.condenseFlow ? \'"\' : "") + ":" + (state.condenseFlow ? "" : " ");\n          if (!writeNode(state, level, objectValue, false, false)) {\n            continue;\n          }\n          pairBuffer += state.dump;\n          _result += pairBuffer;\n        }\n        state.tag = _tag;\n        state.dump = "{" + _result + "}";\n      }\n      function writeBlockMapping(state, level, object, compact) {\n        var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, explicitPair, pairBuffer;\n        if (state.sortKeys === true) {\n          objectKeyList.sort();\n        } else if (typeof state.sortKeys === "function") {\n          objectKeyList.sort(state.sortKeys);\n        } else if (state.sortKeys) {\n          throw new YAMLException("sortKeys must be a boolean or a function");\n        }\n        for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n          pairBuffer = "";\n          if (!compact || _result !== "") {\n            pairBuffer += generateNextLine(state, level);\n          }\n          objectKey = objectKeyList[index];\n          objectValue = object[objectKey];\n          if (state.replacer) {\n            objectValue = state.replacer.call(object, objectKey, objectValue);\n          }\n          if (!writeNode(state, level + 1, objectKey, true, true, true)) {\n            continue;\n          }\n          explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024;\n          if (explicitPair) {\n            if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n              pairBuffer += "?";\n            } else {\n              pairBuffer += "? ";\n            }\n          }\n          pairBuffer += state.dump;\n          if (explicitPair) {\n            pairBuffer += generateNextLine(state, level);\n          }\n          if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {\n            continue;\n          }\n          if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n            pairBuffer += ":";\n          } else {\n            pairBuffer += ": ";\n          }\n          pairBuffer += state.dump;\n          _result += pairBuffer;\n        }\n        state.tag = _tag;\n        state.dump = _result || "{}";\n      }\n      function detectType(state, object, explicit) {\n        var _result, typeList, index, length, type, style;\n        typeList = explicit ? state.explicitTypes : state.implicitTypes;\n        for (index = 0, length = typeList.length; index < length; index += 1) {\n          type = typeList[index];\n          if ((type.instanceOf || type.predicate) && (!type.instanceOf || typeof object === "object" && object instanceof type.instanceOf) && (!type.predicate || type.predicate(object))) {\n            if (explicit) {\n              if (type.multi && type.representName) {\n                state.tag = type.representName(object);\n              } else {\n                state.tag = type.tag;\n              }\n            } else {\n              state.tag = "?";\n            }\n            if (type.represent) {\n              style = state.styleMap[type.tag] || type.defaultStyle;\n              if (_toString.call(type.represent) === "[object Function]") {\n                _result = type.represent(object, style);\n              } else if (_hasOwnProperty.call(type.represent, style)) {\n                _result = type.represent[style](object, style);\n              } else {\n                throw new YAMLException("!<" + type.tag + \'> tag resolver accepts not "\' + style + \'" style\');\n              }\n              state.dump = _result;\n            }\n            return true;\n          }\n        }\n        return false;\n      }\n      function writeNode(state, level, object, block, compact, iskey, isblockseq) {\n        state.tag = null;\n        state.dump = object;\n        if (!detectType(state, object, false)) {\n          detectType(state, object, true);\n        }\n        var type = _toString.call(state.dump);\n        var inblock = block;\n        var tagStr;\n        if (block) {\n          block = state.flowLevel < 0 || state.flowLevel > level;\n        }\n        var objectOrArray = type === "[object Object]" || type === "[object Array]", duplicateIndex, duplicate;\n        if (objectOrArray) {\n          duplicateIndex = state.duplicates.indexOf(object);\n          duplicate = duplicateIndex !== -1;\n        }\n        if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) {\n          compact = false;\n        }\n        if (duplicate && state.usedDuplicates[duplicateIndex]) {\n          state.dump = "*ref_" + duplicateIndex;\n        } else {\n          if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {\n            state.usedDuplicates[duplicateIndex] = true;\n          }\n          if (type === "[object Object]") {\n            if (block && Object.keys(state.dump).length !== 0) {\n              writeBlockMapping(state, level, state.dump, compact);\n              if (duplicate) {\n                state.dump = "&ref_" + duplicateIndex + state.dump;\n              }\n            } else {\n              writeFlowMapping(state, level, state.dump);\n              if (duplicate) {\n                state.dump = "&ref_" + duplicateIndex + " " + state.dump;\n              }\n            }\n          } else if (type === "[object Array]") {\n            if (block && state.dump.length !== 0) {\n              if (state.noArrayIndent && !isblockseq && level > 0) {\n                writeBlockSequence(state, level - 1, state.dump, compact);\n              } else {\n                writeBlockSequence(state, level, state.dump, compact);\n              }\n              if (duplicate) {\n                state.dump = "&ref_" + duplicateIndex + state.dump;\n              }\n            } else {\n              writeFlowSequence(state, level, state.dump);\n              if (duplicate) {\n                state.dump = "&ref_" + duplicateIndex + " " + state.dump;\n              }\n            }\n          } else if (type === "[object String]") {\n            if (state.tag !== "?") {\n              writeScalar(state, state.dump, level, iskey, inblock);\n            }\n          } else if (type === "[object Undefined]") {\n            return false;\n          } else {\n            if (state.skipInvalid) return false;\n            throw new YAMLException("unacceptable kind of an object to dump " + type);\n          }\n          if (state.tag !== null && state.tag !== "?") {\n            tagStr = encodeURI(\n              state.tag[0] === "!" ? state.tag.slice(1) : state.tag\n            ).replace(/!/g, "%21");\n            if (state.tag[0] === "!") {\n              tagStr = "!" + tagStr;\n            } else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") {\n              tagStr = "!!" + tagStr.slice(18);\n            } else {\n              tagStr = "!<" + tagStr + ">";\n            }\n            state.dump = tagStr + " " + state.dump;\n          }\n        }\n        return true;\n      }\n      function getDuplicateReferences(object, state) {\n        var objects = [], duplicatesIndexes = [], index, length;\n        inspectNode(object, objects, duplicatesIndexes);\n        for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {\n          state.duplicates.push(objects[duplicatesIndexes[index]]);\n        }\n        state.usedDuplicates = new Array(length);\n      }\n      function inspectNode(object, objects, duplicatesIndexes) {\n        var objectKeyList, index, length;\n        if (object !== null && typeof object === "object") {\n          index = objects.indexOf(object);\n          if (index !== -1) {\n            if (duplicatesIndexes.indexOf(index) === -1) {\n              duplicatesIndexes.push(index);\n            }\n          } else {\n            objects.push(object);\n            if (Array.isArray(object)) {\n              for (index = 0, length = object.length; index < length; index += 1) {\n                inspectNode(object[index], objects, duplicatesIndexes);\n              }\n            } else {\n              objectKeyList = Object.keys(object);\n              for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n                inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);\n              }\n            }\n          }\n        }\n      }\n      function dump(input, options) {\n        options = options || {};\n        var state = new State(options);\n        if (!state.noRefs) getDuplicateReferences(input, state);\n        var value = input;\n        if (state.replacer) {\n          value = state.replacer.call({ "": value }, "", value);\n        }\n        if (writeNode(state, 0, value, true, true)) return state.dump + "\\n";\n        return "";\n      }\n      module2.exports.dump = dump;\n    }\n  });\n\n  // node_modules/js-yaml/index.js\n  var require_js_yaml = __commonJS({\n    "node_modules/js-yaml/index.js"(exports2, module2) {\n      "use strict";\n      var loader = require_loader();\n      var dumper = require_dumper();\n      function renamed(from, to) {\n        return function() {\n          throw new Error("Function yaml." + from + " is removed in js-yaml 4. Use yaml." + to + " instead, which is now safe by default.");\n        };\n      }\n      module2.exports.Type = require_type();\n      module2.exports.Schema = require_schema();\n      module2.exports.FAILSAFE_SCHEMA = require_failsafe();\n      module2.exports.JSON_SCHEMA = require_json2();\n      module2.exports.CORE_SCHEMA = require_core();\n      module2.exports.DEFAULT_SCHEMA = require_default();\n      module2.exports.load = loader.load;\n      module2.exports.loadAll = loader.loadAll;\n      module2.exports.dump = dumper.dump;\n      module2.exports.YAMLException = require_exception();\n      module2.exports.types = {\n        binary: require_binary(),\n        float: require_float(),\n        map: require_map(),\n        null: require_null(),\n        pairs: require_pairs(),\n        set: require_set(),\n        timestamp: require_timestamp(),\n        bool: require_bool(),\n        int: require_int(),\n        merge: require_merge(),\n        omap: require_omap(),\n        seq: require_seq(),\n        str: require_str()\n      };\n      module2.exports.safeLoad = renamed("safeLoad", "load");\n      module2.exports.safeLoadAll = renamed("safeLoadAll", "loadAll");\n      module2.exports.safeDump = renamed("safeDump", "dump");\n    }\n  });\n\n  // modules/std/data/yaml.js\n  var require_yaml = __commonJS({\n    "modules/std/data/yaml.js"(exports2, module2) {\n      "use strict";\n      var yaml = require_js_yaml();\n      var { Pair, PairList, ZuzuBag } = require_collections();\n      var { BinaryString: BinaryString2 } = require_runtime_helpers();\n      var utf8Decoder = new TextDecoder("utf-8", { fatal: true });\n      var utf8Encoder = new TextEncoder();\n      function isPlainObject2(value) {\n        return value != null && typeof value === "object" && !Array.isArray(value) && !(value instanceof PairList) && !(value instanceof ZuzuBag) && Object.prototype.toString.call(value) !== "[object Set]";\n      }\n      function isPath(value) {\n        return value && value.constructor && value.constructor.name === "Path" && typeof value.slurp === "function" && typeof value.spew === "function";\n      }\n      function normalizeValue(value) {\n        if (value instanceof PairList) {\n          const out = {};\n          for (const [key, inner] of value.list) {\n            if (!Object.prototype.hasOwnProperty.call(out, String(key))) {\n              out[String(key)] = normalizeValue(inner);\n            }\n          }\n          return out;\n        }\n        if (value && Array.isArray(value.items) && typeof value.to_Array === "function") {\n          return normalizeValue(\n            value.to_Array().slice().sort((left, right) => String(left).localeCompare(String(right)))\n          );\n        }\n        if (value && value.constructor && value.constructor.name === "Set" && typeof value.to_Array === "function") {\n          return normalizeValue(\n            value.to_Array().slice().sort((left, right) => String(left).localeCompare(String(right)))\n          );\n        }\n        if (value && value.constructor && value.constructor.name === "ZuzuBag" && typeof value.to_Array === "function") {\n          return normalizeValue(\n            value.to_Array().slice().sort((left, right) => String(left).localeCompare(String(right)))\n          );\n        }\n        if (value && value.constructor && ["Set", "ZuzuBag", "PairList"].includes(value.constructor.name) && typeof value.to_Array === "function") {\n          return normalizeValue(value.to_Array());\n        }\n        if (Array.isArray(value)) {\n          return value.map((item) => normalizeValue(item));\n        }\n        if (value && value.constructor && value.constructor.name === "Object") {\n          const out = {};\n          for (const key of Object.keys(value).sort()) {\n            out[key] = normalizeValue(value[key]);\n          }\n          return out;\n        }\n        return value;\n      }\n      function decorateValue(value) {\n        if (Array.isArray(value)) {\n          for (let i = 0; i < value.length; i++) {\n            value[i] = decorateValue(value[i]);\n          }\n          return value;\n        }\n        if (!isPlainObject2(value)) {\n          return value;\n        }\n        const sortedKeys = () => Object.keys(value).sort();\n        for (const [name2, fn2] of [\n          ["length", function _length() {\n            return Object.keys(this).length;\n          }],\n          ["count", function _count() {\n            return Object.keys(this).length;\n          }],\n          ["empty", function _empty() {\n            return Object.keys(this).length === 0 ? 1 : 0;\n          }],\n          ["keys", function _keys() {\n            return new Set(sortedKeys());\n          }],\n          ["values", function _values() {\n            return new ZuzuBag(sortedKeys().map((key) => this[key]));\n          }],\n          [\n            "enumerate",\n            function _enumerate() {\n              return new ZuzuBag(\n                sortedKeys().map(\n                  (key) => new Pair({ pair: [key, this[key]] })\n                )\n              );\n            }\n          ],\n          ["has", function _has(key) {\n            return Object.prototype.hasOwnProperty.call(this, String(key)) ? 1 : 0;\n          }],\n          ["contains", function _contains(key) {\n            return this.has(key);\n          }],\n          ["exists", function _exists(key) {\n            return this.has(key);\n          }],\n          ["defined", function _defined(key) {\n            return this.has(key) && this[String(key)] != null ? 1 : 0;\n          }],\n          ["get", function _get(key, fallback = null) {\n            return this.has(key) ? this[String(key)] : fallback;\n          }],\n          ["add", function _add(key, inner) {\n            this[String(key)] = inner;\n            return this;\n          }],\n          ["set", function _set(key, inner) {\n            return this.add(key, inner);\n          }],\n          [\n            "kv",\n            function _kv() {\n              const out = [];\n              for (const key of sortedKeys()) {\n                out.push(key, this[key]);\n              }\n              return out;\n            }\n          ],\n          ["sorted_keys", function _sorted_keys() {\n            return sortedKeys();\n          }],\n          [\n            "to_Array",\n            function _to_array() {\n              return sortedKeys().map(\n                (key) => new Pair({ pair: [key, this[key]] })\n              );\n            }\n          ],\n          ["to_Iterator", function _to_iterator() {\n            return sortedKeys()[Symbol.iterator]();\n          }],\n          [\n            "for_each_key",\n            function _for_each_key(fn3) {\n              for (const key of sortedKeys()) {\n                fn3(key);\n              }\n              return this;\n            }\n          ],\n          [\n            "for_each_value",\n            function _for_each_value(fn3) {\n              for (const key of sortedKeys()) {\n                fn3(this[key]);\n              }\n              return this;\n            }\n          ],\n          [\n            "for_each_pair",\n            function _for_each_pair(fn3) {\n              for (const key of sortedKeys()) {\n                fn3(new Pair({ pair: [key, this[key]] }));\n              }\n              return this;\n            }\n          ],\n          [\n            "remove",\n            function _remove(key) {\n              delete this[String(key)];\n              return this;\n            }\n          ],\n          [\n            "clear",\n            function _clear() {\n              for (const key of Object.keys(this)) {\n                delete this[key];\n              }\n              return this;\n            }\n          ]\n        ]) {\n          if (!Object.prototype.hasOwnProperty.call(value, name2)) {\n            Object.defineProperty(value, name2, {\n              value: fn2,\n              enumerable: false,\n              configurable: true,\n              writable: true\n            });\n          }\n        }\n        for (const key of Object.keys(value)) {\n          value[key] = decorateValue(value[key]);\n        }\n        return value;\n      }\n      var YAML = class {\n        constructor(options = {}) {\n          const merged = options instanceof PairList ? Object.fromEntries(options.list.map(([key, value]) => [String(key), value])) : options;\n          this.pretty = !!merged.pretty;\n          this.canonical = !!merged.canonical;\n        }\n        encode(value) {\n          const text = yaml.dump(normalizeValue(value), {\n            lineWidth: -1,\n            noArrayIndent: true,\n            noRefs: true,\n            sortKeys: true\n          });\n          return this.pretty ? text : text.replace(/\\n$/u, "");\n        }\n        encode_binarystring(value) {\n          return new BinaryString2(utf8Encoder.encode(this.encode(value)));\n        }\n        decode(text) {\n          const value = yaml.load(String(text));\n          return value === void 0 ? null : decorateValue(value);\n        }\n        decode_binarystring(raw) {\n          if (!(raw instanceof BinaryString2)) {\n            throw new Error("TypeException: YAML.decode_binarystring expects BinaryString");\n          }\n          return this.decode(utf8Decoder.decode(raw.bytes));\n        }\n        dump(pathValue, value) {\n          if (!isPath(pathValue)) {\n            throw new Error("TypeException: YAML.dump expects Path as first argument");\n          }\n          pathValue.spew(this.encode_binarystring(value));\n          return pathValue;\n        }\n        load(pathValue) {\n          if (!isPath(pathValue)) {\n            throw new Error("TypeException: YAML.load expects Path as first argument");\n          }\n          return this.decode_binarystring(pathValue.slurp());\n        }\n      };\n      module2.exports = {\n        YAML\n      };\n    }\n  });\n\n  // modules/std/data/csv.js\n  var require_csv = __commonJS({\n    "modules/std/data/csv.js"(exports2, module2) {\n      "use strict";\n      var { PairList } = require_collections();\n      var { BinaryString: BinaryString2 } = require_runtime_helpers();\n      var utf8Decoder = new TextDecoder("utf-8", { fatal: true });\n      var utf8Encoder = new TextEncoder();\n      var runtimePolicy2 = {\n        deny_fs: false,\n        deny_db: false,\n        host_name: "node"\n      };\n      var nodeFs;\n      var nodeFsLoaded = false;\n      var PathClass;\n      var PathClassLoaded = false;\n      var DatabaseHandleClass;\n      var DatabaseHandleClassLoaded = false;\n      function _safeRequire(moduleName) {\n        if (typeof __require !== "function") {\n          return null;\n        }\n        try {\n          return __require(moduleName);\n        } catch (_err) {\n          return null;\n        }\n      }\n      function _nodeFs() {\n        if (nodeFsLoaded) {\n          return nodeFs;\n        }\n        nodeFsLoaded = true;\n        nodeFs = _safeRequire("node:fs");\n        return nodeFs;\n      }\n      function _PathClass() {\n        if (PathClassLoaded) {\n          return PathClass;\n        }\n        PathClassLoaded = true;\n        const loaded = _safeRequire("../io.js");\n        PathClass = loaded && loaded.Path ? loaded.Path : null;\n        return PathClass;\n      }\n      function _DatabaseHandleClass() {\n        if (DatabaseHandleClassLoaded) {\n          return DatabaseHandleClass;\n        }\n        DatabaseHandleClassLoaded = true;\n        const loaded = _safeRequire("../db.js");\n        DatabaseHandleClass = loaded && loaded.DatabaseHandle ? loaded.DatabaseHandle : null;\n        return DatabaseHandleClass;\n      }\n      function assertCapability(capability, message) {\n        if (runtimePolicy2[`deny_${capability}`]) {\n          throw new Error(message);\n        }\n      }\n      function bool(value) {\n        return value ? 1 : 0;\n      }\n      function isPlainObject2(value) {\n        return value != null && typeof value === "object" && !Array.isArray(value) && !(value instanceof PairList);\n      }\n      function isPath(value) {\n        if (value == null || typeof value !== "object") {\n          return false;\n        }\n        const Path = _PathClass();\n        return Path ? value instanceof Path : false;\n      }\n      function isDbHandle(value) {\n        if (value == null || typeof value !== "object") {\n          return false;\n        }\n        const DatabaseHandle = _DatabaseHandleClass();\n        return DatabaseHandle ? value instanceof DatabaseHandle : false;\n      }\n      function optionsObject(value) {\n        if (value instanceof PairList) {\n          return Object.fromEntries(\n            value.list.map(([key, inner]) => [String(key), inner])\n          );\n        }\n        if (isPlainObject2(value)) {\n          return { ...value };\n        }\n        return {};\n      }\n      function arrayValue(value) {\n        if (Array.isArray(value)) {\n          return value.slice();\n        }\n        return [];\n      }\n      function objectValue(value) {\n        return isPlainObject2(value) ? { ...value } : {};\n      }\n      function normalizeConfig(...parts) {\n        const out = {};\n        for (const part of parts) {\n          Object.assign(out, optionsObject(part));\n        }\n        return out;\n      }\n      function runtimeConfig(...parts) {\n        const config = normalizeConfig(...parts);\n        for (const key of ["columns", "required_columns", "sniff_candidates"]) {\n          if (key in config) {\n            config[key] = arrayValue(config[key]);\n          }\n        }\n        for (const key of [\n          "defaults",\n          "rename_headers",\n          "column_map",\n          "column_types",\n          "types",\n          "parsers",\n          "formatters"\n        ]) {\n          if (key in config) {\n            config[key] = objectValue(config[key]);\n          }\n        }\n        return config;\n      }\n      function columnNamesFromConfig(config) {\n        if (Array.isArray(config.columns)) {\n          return config.columns.map((name2) => String(name2 ?? ""));\n        }\n        return null;\n      }\n      function defaultColumnsForRow(row) {\n        const out = [];\n        for (let i = 0; i < row.length; i++) {\n          out.push(`column${i + 1}`);\n        }\n        return out;\n      }\n      function normalizeFieldValue(value, config) {\n        if (value === "" && config.blank_is_undef) {\n          return null;\n        }\n        if (value === "" && config.empty_is_undef) {\n          return null;\n        }\n        return value;\n      }\n      function headerName(raw, config) {\n        let value = String(raw ?? "");\n        if (config.trim_headers) {\n          value = value.trim();\n        }\n        if (config.lowercase_headers) {\n          value = value.toLowerCase();\n        }\n        if (config.rename_headers && Object.prototype.hasOwnProperty.call(config.rename_headers, value)) {\n          value = String(config.rename_headers[value]);\n        }\n        return value;\n      }\n      function normalizeHeaders(headers, config) {\n        if (!Array.isArray(headers)) {\n          return [];\n        }\n        const seen = /* @__PURE__ */ new Map();\n        const out = [];\n        const policy = String(config.duplicate_headers || "overwrite").toLowerCase();\n        for (const raw of headers) {\n          let name2 = headerName(raw, config);\n          if (seen.has(name2)) {\n            if (policy === "error") {\n              throw new Error(`Duplicate CSV header \'${name2}\'`);\n            }\n            if (policy === "suffix") {\n              const next = seen.get(name2) + 1;\n              seen.set(name2, next);\n              name2 = `${name2}_${next}`;\n            } else {\n              seen.set(name2, seen.get(name2) + 1);\n            }\n          } else {\n            seen.set(name2, 1);\n          }\n          out.push(name2);\n        }\n        return out;\n      }\n      function requireColumns(headers, config) {\n        const required = arrayValue(config.required_columns);\n        if (required.length === 0) {\n          return;\n        }\n        const have = new Set(headers || []);\n        for (const name2 of required) {\n          if (!have.has(name2)) {\n            throw new Error(`Required CSV column \'${name2}\' missing`);\n          }\n        }\n      }\n      function typeForColumn(config, headers, index) {\n        const types = config.types;\n        if (Array.isArray(types)) {\n          return types[index];\n        }\n        if (isPlainObject2(types) && Array.isArray(headers)) {\n          return types[headers[index]];\n        }\n        return void 0;\n      }\n      function coerceScalar(value, type) {\n        if (type == null) {\n          return value;\n        }\n        const name2 = String(type).toLowerCase();\n        if (name2 === "null") {\n          return null;\n        }\n        if (value == null) {\n          return name2 === "string" ? "" : null;\n        }\n        if (name2 === "integer" || name2 === "int") {\n          return parseInt(String(value), 10) || 0;\n        }\n        if (["number", "float", "real"].includes(name2)) {\n          return Number(value) || 0;\n        }\n        if (name2 === "boolean" || name2 === "bool") {\n          const text = String(value).toLowerCase();\n          if (/^(1|true|yes|on)$/u.test(text)) {\n            return 1;\n          }\n          if (/^(0|false|no|off)?$/u.test(text)) {\n            return 0;\n          }\n          return bool(value);\n        }\n        return String(value);\n      }\n      function applyRowRules(row, headers, config, state = {}) {\n        const working = row.slice();\n        if (Array.isArray(headers)) {\n          const expected = headers.length;\n          const actual = working.length;\n          const ragged = String(config.ragged || "allow").toLowerCase();\n          if (actual < expected) {\n            if (ragged === "fill") {\n              while (working.length < expected) {\n                working.push(config.fill_value ?? null);\n              }\n            } else if (ragged === "error") {\n              throw new Error(`CSV row has too few fields at line ${state.line_number ?? "?"}`);\n            }\n          } else if (actual > expected) {\n            if (ragged === "truncate") {\n              working.length = expected;\n            } else if (ragged === "error") {\n              throw new Error(`CSV row has too many fields at line ${state.line_number ?? "?"}`);\n            }\n          }\n        }\n        for (let i = 0; i < working.length; i++) {\n          working[i] = coerceScalar(\n            normalizeFieldValue(working[i], config),\n            typeForColumn(config, headers, i)\n          );\n        }\n        if (Array.isArray(headers)) {\n          const out = {};\n          for (let i = 0; i < headers.length; i++) {\n            out[headers[i]] = working[i];\n          }\n          for (const [key, value] of Object.entries(objectValue(config.defaults))) {\n            if (out[key] == null || out[key] === "") {\n              out[key] = value;\n            }\n          }\n          if (String(config.unknown_columns || "keep").toLowerCase() === "ignore") {\n            const allowed = new Set(headers);\n            for (const key of Object.keys(out)) {\n              if (!allowed.has(key)) {\n                delete out[key];\n              }\n            }\n          }\n          return out;\n        }\n        return working;\n      }\n      var UnterminatedQuoteError = class extends Error {\n      };\n      function parseRecord(record, config) {\n        const sep = String(config.sep_char ?? ",");\n        const quote = String(config.quote_char ?? \'"\');\n        const escape = String(config.escape_char ?? quote);\n        const allowWhitespace = !!config.allow_whitespace;\n        const row = [];\n        let field = "";\n        let inQuotes = false;\n        let afterQuote = false;\n        for (let i = 0; i < record.length; i++) {\n          const ch = record[i];\n          if (inQuotes) {\n            if (ch === quote) {\n              if (escape === quote && record[i + 1] === quote) {\n                field += quote;\n                i++;\n              } else {\n                inQuotes = false;\n                afterQuote = true;\n              }\n              continue;\n            }\n            if (escape !== quote && ch === escape && i + 1 < record.length) {\n              field += record[i + 1];\n              i++;\n              continue;\n            }\n            field += ch;\n            continue;\n          }\n          if (afterQuote) {\n            if (ch === sep) {\n              row.push(normalizeFieldValue(field, config));\n              field = "";\n              afterQuote = false;\n              continue;\n            }\n            if (ch === "\\n") {\n              row.push(normalizeFieldValue(field, config));\n              return row;\n            }\n            if (ch === "\\r") {\n              continue;\n            }\n            if (allowWhitespace && /\\s/u.test(ch)) {\n              continue;\n            }\n            throw new Error(`unexpected trailing text after closing quote near column ${row.length + 1}`);\n          }\n          if (ch === sep) {\n            row.push(normalizeFieldValue(field, config));\n            field = "";\n            continue;\n          }\n          if (ch === quote && field === "") {\n            inQuotes = true;\n            continue;\n          }\n          if (ch === "\\n") {\n            row.push(normalizeFieldValue(field, config));\n            return row;\n          }\n          if (ch === "\\r") {\n            continue;\n          }\n          field += ch;\n        }\n        if (inQuotes) {\n          throw new UnterminatedQuoteError("unterminated quoted field");\n        }\n        row.push(normalizeFieldValue(field, config));\n        return row;\n      }\n      function csvErrorDetail(error, state = {}) {\n        const parts = [];\n        if (state.line_number != null) {\n          parts.push(`line ${state.line_number}`);\n        }\n        if (state.column_number != null) {\n          parts.push(`column ${state.column_number}`);\n        }\n        if (state.raw_line != null) {\n          parts.push(`row ${state.raw_line}`);\n        }\n        return {\n          message: parts.length > 0 ? `${error.message} (${parts.join(", ")})` : error.message,\n          line_number: state.line_number ?? null,\n          column_number: state.column_number ?? null,\n          raw_line: state.raw_line ?? null\n        };\n      }\n      function sourceLinesFromText(text) {\n        const source = String(text ?? "");\n        let index = 0;\n        return function nextLine() {\n          if (index >= source.length) {\n            return null;\n          }\n          let end = source.indexOf("\\n", index);\n          if (end === -1) {\n            end = source.length;\n          } else {\n            end += 1;\n          }\n          const line = source.slice(index, end);\n          index = end;\n          return line;\n        };\n      }\n      var FileLineSource = class {\n        constructor(target) {\n          const fs = _nodeFs();\n          if (!fs) {\n            throw new Error("CSV file access requires filesystem support");\n          }\n          this.fd = fs.openSync(target.to_String(), "r");\n          this.buffer = "";\n          this.eof = false;\n        }\n        nextLine() {\n          const fs = _nodeFs();\n          while (true) {\n            const idx = this.buffer.indexOf("\\n");\n            if (idx >= 0) {\n              const line = this.buffer.slice(0, idx + 1);\n              this.buffer = this.buffer.slice(idx + 1);\n              return line;\n            }\n            if (this.eof) {\n              if (this.buffer === "") {\n                return null;\n              }\n              const tail = this.buffer;\n              this.buffer = "";\n              return tail;\n            }\n            const chunk = Buffer.allocUnsafe(8192);\n            const bytesRead = fs.readSync(this.fd, chunk, 0, chunk.length, null);\n            if (bytesRead === 0) {\n              this.eof = true;\n            } else {\n              this.buffer += chunk.toString("utf8", 0, bytesRead);\n            }\n          }\n        }\n        close() {\n          if (this.fd != null) {\n            const fs = _nodeFs();\n            fs.closeSync(this.fd);\n            this.fd = null;\n          }\n        }\n      };\n      var CSVReader = class {\n        constructor(target, options = {}) {\n          if (!isPath(target)) {\n            throw new Error("TypeException: CSV.open expects Path as first argument");\n          }\n          this.config = runtimeConfig(options);\n          this.source = new FileLineSource(target);\n          this.headersList = columnNamesFromConfig(this.config);\n          this.mode = this.headersList ? "dict" : "array";\n          this.lineNumberValue = 0;\n          this.rowNumberValue = 0;\n          this.errorsList = [];\n          this.recordBuffer = "";\n          this.recordStartLine = null;\n          this.skipRemaining = Number(this.config.skip_lines || 0);\n          this.closed = false;\n          if (!this.headersList && this.config.headers) {\n            const headerRow = this._readNextArray(true);\n            this.headersList = normalizeHeaders(headerRow || [], this.config);\n            requireColumns(this.headersList, this.config);\n            this.mode = "dict";\n          } else if (this.headersList) {\n            requireColumns(this.headersList, this.config);\n          }\n        }\n        _state() {\n          return {\n            line_number: this.recordStartLine ?? this.lineNumberValue,\n            row_number: this.rowNumberValue,\n            raw_line: this.recordBuffer\n          };\n        }\n        _nextPhysicalLine() {\n          const line = this.source.nextLine();\n          if (line != null) {\n            this.lineNumberValue++;\n          }\n          return line;\n        }\n        _readNextArray(internal = false) {\n          while (true) {\n            const line = this._nextPhysicalLine();\n            if (line == null) {\n              if (this.recordBuffer === "") {\n                return null;\n              }\n              try {\n                const finalRow = parseRecord(this.recordBuffer, this.config);\n                this.recordBuffer = "";\n                return finalRow;\n              } catch (error) {\n                if (error instanceof UnterminatedQuoteError) {\n                  const detail = csvErrorDetail(error, this._state());\n                  this.errorsList.push(detail);\n                  if (internal || String(this.config.on_error || "die").toLowerCase() !== "collect") {\n                    throw new Error(detail.message);\n                  }\n                  this.recordBuffer = "";\n                  return null;\n                }\n                throw error;\n              }\n            }\n            if (this.recordBuffer === "") {\n              if (this.skipRemaining > 0) {\n                this.skipRemaining--;\n                continue;\n              }\n              if (this.config.comment_char && line.startsWith(String(this.config.comment_char))) {\n                continue;\n              }\n              if (this.config.skip_empty_rows && /^\\s*$/u.test(line)) {\n                continue;\n              }\n              this.recordStartLine = this.lineNumberValue;\n            }\n            this.recordBuffer += line;\n            try {\n              const row = parseRecord(this.recordBuffer, this.config);\n              this.recordBuffer = "";\n              return row;\n            } catch (error) {\n              if (error instanceof UnterminatedQuoteError) {\n                continue;\n              }\n              const detail = csvErrorDetail(error, this._state());\n              this.errorsList.push(detail);\n              this.recordBuffer = "";\n              if (internal || String(this.config.on_error || "die").toLowerCase() !== "collect") {\n                throw new Error(detail.message);\n              }\n            }\n          }\n        }\n        next_array() {\n          while (true) {\n            const row = this._readNextArray(false);\n            if (row == null) {\n              return null;\n            }\n            const result = applyRowRules(\n              row,\n              this.headersList,\n              this.config,\n              {\n                line_number: this.recordStartLine,\n                row_number: this.rowNumberValue + 1,\n                raw_line: this.recordBuffer\n              }\n            );\n            this.rowNumberValue++;\n            if (Array.isArray(result)) {\n              return result;\n            }\n            return (this.headersList || []).map((name2) => result[name2]);\n          }\n        }\n        next_dict() {\n          if (!Array.isArray(this.headersList) || this.headersList.length === 0) {\n            throw new Error("CSVReader.next_dict requires headers or columns");\n          }\n          const row = this._readNextArray(false);\n          if (row == null) {\n            return null;\n          }\n          this.rowNumberValue++;\n          const result = applyRowRules(\n            row,\n            this.headersList,\n            this.config,\n            {\n              line_number: this.recordStartLine,\n              row_number: this.rowNumberValue,\n              raw_line: this.recordBuffer\n            }\n          );\n          return Array.isArray(result) ? Object.fromEntries(this.headersList.map((name2, index) => [name2, result[index]])) : result;\n        }\n        next() {\n          return this.mode === "dict" ? this.next_dict() : this.next_array();\n        }\n        all_array() {\n          const out = [];\n          let row;\n          while ((row = this.next_array()) !== null) {\n            out.push(row);\n          }\n          return out;\n        }\n        all_dict() {\n          const out = [];\n          let row;\n          while ((row = this.next_dict()) !== null) {\n            out.push(row);\n          }\n          return out;\n        }\n        headers() {\n          return this.headersList ? this.headersList.slice() : null;\n        }\n        columns() {\n          return this.headers();\n        }\n        set_columns(columns) {\n          this.headersList = arrayValue(columns).map((name2) => String(name2));\n          this.mode = "dict";\n          return this.headers();\n        }\n        row_number() {\n          return this.rowNumberValue;\n        }\n        skip_lines(count) {\n          let skipped = 0;\n          while (skipped < Number(count || 0)) {\n            if (this._nextPhysicalLine() == null) {\n              break;\n            }\n            skipped++;\n          }\n          return skipped;\n        }\n        errors() {\n          return this.errorsList.slice();\n        }\n        close() {\n          if (!this.closed) {\n            this.closed = true;\n            this.source.close();\n          }\n          return 1;\n        }\n        *[Symbol.iterator]() {\n          let row;\n          while ((row = this.next()) !== null) {\n            yield row;\n          }\n        }\n        to_Iterator() {\n          return this[Symbol.iterator]();\n        }\n      };\n      function outputColumnsFromRows(rows, config) {\n        const configured = columnNamesFromConfig(config);\n        if (configured && configured.length > 0) {\n          return configured;\n        }\n        for (const row of rows) {\n          if (Array.isArray(row)) {\n            return config.headers ? defaultColumnsForRow(row) : null;\n          }\n          if (isPlainObject2(row)) {\n            const keys = Object.keys(row);\n            if (config.sort_columns) {\n              keys.sort((left, right) => left.localeCompare(right));\n            }\n            return keys;\n          }\n        }\n        return null;\n      }\n      function formatOutputRow(row, columns) {\n        if (Array.isArray(row)) {\n          return row.slice();\n        }\n        if (isPlainObject2(row)) {\n          return (columns || Object.keys(row)).map((name2) => row[name2]);\n        }\n        return [row];\n      }\n      function encodeCell(value, config) {\n        if (value == null) {\n          return "";\n        }\n        const sep = String(config.sep_char ?? ",");\n        const quote = String(config.quote_char ?? \'"\');\n        const escape = String(config.escape_char ?? quote);\n        let text = String(value);\n        const needsQuote = config.always_quote || text.includes(sep) || text.includes("\\n") || text.includes("\\r") || text.includes(quote) || config.quote_space && /^\\s|\\s$/u.test(text) || config.quote_empty && text === "";\n        if (!needsQuote) {\n          return text;\n        }\n        if (escape === quote) {\n          text = text.replaceAll(quote, quote + quote);\n        } else {\n          text = text.replaceAll(escape, escape + escape);\n          text = text.replaceAll(quote, escape + quote);\n        }\n        return `${quote}${text}${quote}`;\n      }\n      function quotedIdentifier(name2) {\n        return `"${String(name2).replaceAll(\'"\', \'""\')}"`;\n      }\n      var CSVWriter = class {\n        constructor(target, options = {}) {\n          if (!isPath(target)) {\n            throw new Error("TypeException: CSV.open_writer expects Path as first argument");\n          }\n          const fs = _nodeFs();\n          if (!fs) {\n            throw new Error("CSV file access requires filesystem support");\n          }\n          this.config = runtimeConfig(options);\n          this.columnsList = columnNamesFromConfig(this.config);\n          this.rowNumberValue = 0;\n          this.wroteHeader = !!this.config.append;\n          const flag = this.config.append ? "a" : "w";\n          this.fd = fs.openSync(target.to_String(), flag);\n          this.closed = false;\n        }\n        _writeText(text) {\n          const fs = _nodeFs();\n          fs.writeSync(this.fd, text, null, "utf8");\n        }\n        columns() {\n          return this.columnsList ? this.columnsList.slice() : null;\n        }\n        write_header(columns = null) {\n          if (columns != null) {\n            this.columnsList = arrayValue(columns).map((name2) => String(name2));\n          }\n          if (!Array.isArray(this.columnsList)) {\n            this.columnsList = [];\n          }\n          this._writeText(\n            this.columnsList.map((value) => encodeCell(value, this.config)).join(String(this.config.sep_char ?? ",")) + String(this.config.eol ?? "\\n")\n          );\n          this.wroteHeader = true;\n          return this.columns();\n        }\n        write_row(row) {\n          if (this.closed) {\n            throw new Error("CSVWriter is closed");\n          }\n          if (!this.columnsList) {\n            if (Array.isArray(row) && this.config.headers) {\n              this.columnsList = defaultColumnsForRow(row);\n            } else if (isPlainObject2(row)) {\n              this.columnsList = Object.keys(row);\n              if (this.config.sort_columns) {\n                this.columnsList.sort((left, right) => left.localeCompare(right));\n              }\n            }\n          }\n          if (this.config.headers && !this.wroteHeader && this.columnsList) {\n            this.write_header(this.columnsList);\n          }\n          const fields = formatOutputRow(row, this.columnsList);\n          this._writeText(\n            fields.map((value) => encodeCell(value, this.config)).join(String(this.config.sep_char ?? ",")) + String(this.config.eol ?? "\\n")\n          );\n          this.rowNumberValue++;\n          return fields;\n        }\n        print_row(row) {\n          return this.write_row(row);\n        }\n        row_number() {\n          return this.rowNumberValue;\n        }\n        close() {\n          if (!this.closed) {\n            this.closed = true;\n            const fs = _nodeFs();\n            fs.closeSync(this.fd);\n          }\n          return 1;\n        }\n      };\n      function sniffCounts(text, char) {\n        return String(text ?? "").split(/\\r?\\n/u).filter((line) => line !== "").slice(0, 5).reduce((count, line) => count + (line.split(char).length - 1), 0);\n      }\n      function sniffText(source, config = {}) {\n        const candidates = arrayValue(config.sniff_candidates);\n        const chars = candidates.length > 0 ? candidates : [",", "	", ";", "|"];\n        let best = chars[0];\n        let bestScore = -1;\n        for (const char of chars) {\n          const score = sniffCounts(source, char);\n          if (score > bestScore) {\n            bestScore = score;\n            best = char;\n          }\n        }\n        const first = String(source ?? "").split(/\\r?\\n/u).find((line) => /\\S/u.test(line)) || "";\n        let headers = 0;\n        if (first !== "") {\n          const parts = first.split(best);\n          headers = parts.length > 0 && parts.every((part) => !/^-?(?:\\d+(?:\\.\\d+)?)$/u.test(part)) ? 1 : 0;\n        }\n        return {\n          sep_char: best,\n          headers,\n          quote_char: \'"\'\n        };\n      }\n      var CSV = class _CSV {\n        constructor(options = {}) {\n          this.config = runtimeConfig(options);\n        }\n        sniff(source) {\n          if (isPath(source)) {\n            assertCapability("fs", "CSV.sniff is denied by runtime policy");\n            return this.sniff_binarystring(source.slurp());\n          }\n          return sniffText(source, this.config);\n        }\n        sniff_binarystring(source) {\n          if (!(source instanceof BinaryString2)) {\n            throw new Error("TypeException: CSV.sniff_binarystring expects BinaryString");\n          }\n          return sniffText(utf8Decoder.decode(source.bytes), this.config);\n        }\n        transpose(rows) {\n          const matrix = Array.isArray(rows) ? rows : [];\n          let max = 0;\n          for (const row of matrix) {\n            max = Math.max(max, Array.isArray(row) ? row.length : 1);\n          }\n          const out = [];\n          for (let i = 0; i < max; i++) {\n            const next = [];\n            for (const row of matrix) {\n              next.push(Array.isArray(row) ? row[i] : i === 0 ? row : null);\n            }\n            out.push(next);\n          }\n          return out;\n        }\n        decode(text) {\n          const report = this.decode_report(text);\n          if (report.errors.length > 0 && String(this.config.on_error || "die").toLowerCase() !== "collect") {\n            throw new Error(report.errors[0].message);\n          }\n          return report.rows;\n        }\n        decode_binarystring(raw) {\n          if (!(raw instanceof BinaryString2)) {\n            throw new Error("TypeException: CSV.decode_binarystring expects BinaryString");\n          }\n          return this.decode(utf8Decoder.decode(raw.bytes));\n        }\n        decode_report(text) {\n          const config = runtimeConfig(this.config, { on_error: "collect" });\n          const rows = [];\n          const errors = [];\n          const nextLine = sourceLinesFromText(text);\n          let headers = columnNamesFromConfig(config);\n          let lineNumber = 0;\n          let rowNumber = 0;\n          let buffer = "";\n          let recordStartLine = null;\n          let skipRemaining = Number(config.skip_lines || 0);\n          while (true) {\n            const line = nextLine();\n            if (line == null) {\n              break;\n            }\n            lineNumber++;\n            if (buffer === "") {\n              if (skipRemaining > 0) {\n                skipRemaining--;\n                continue;\n              }\n              if (config.comment_char && line.startsWith(String(config.comment_char))) {\n                continue;\n              }\n              if (config.skip_empty_rows && /^\\s*$/u.test(line)) {\n                continue;\n              }\n              recordStartLine = lineNumber;\n            }\n            buffer += line;\n            let row;\n            try {\n              row = parseRecord(buffer, config);\n            } catch (error) {\n              if (error instanceof UnterminatedQuoteError) {\n                continue;\n              }\n              errors.push(\n                csvErrorDetail(\n                  error,\n                  {\n                    line_number: recordStartLine,\n                    row_number: rowNumber + 1,\n                    raw_line: buffer\n                  }\n                )\n              );\n              buffer = "";\n              break;\n            }\n            buffer = "";\n            if (!headers && config.headers) {\n              headers = normalizeHeaders(row, config);\n              requireColumns(headers, config);\n              continue;\n            }\n            try {\n              rowNumber++;\n              rows.push(\n                applyRowRules(\n                  row,\n                  headers,\n                  config,\n                  {\n                    line_number: recordStartLine,\n                    row_number: rowNumber,\n                    raw_line: line\n                  }\n                )\n              );\n            } catch (error) {\n              errors.push(\n                csvErrorDetail(\n                  error,\n                  {\n                    line_number: recordStartLine,\n                    row_number: rowNumber,\n                    raw_line: line\n                  }\n                )\n              );\n              buffer = "";\n            }\n          }\n          if (buffer !== "") {\n            try {\n              const row = parseRecord(buffer, config);\n              if (!headers && config.headers) {\n                headers = normalizeHeaders(row, config);\n                requireColumns(headers, config);\n              } else {\n                rowNumber++;\n                rows.push(\n                  applyRowRules(\n                    row,\n                    headers,\n                    config,\n                    {\n                      line_number: recordStartLine,\n                      row_number: rowNumber,\n                      raw_line: buffer\n                    }\n                  )\n                );\n              }\n            } catch (error) {\n              errors.push(\n                csvErrorDetail(\n                  error,\n                  {\n                    line_number: recordStartLine,\n                    row_number: rowNumber + 1,\n                    raw_line: buffer\n                  }\n                )\n              );\n            }\n          }\n          return { rows, errors };\n        }\n        decode_report_binarystring(raw) {\n          if (!(raw instanceof BinaryString2)) {\n            throw new Error(\n              "TypeException: CSV.decode_report_binarystring expects BinaryString"\n            );\n          }\n          return this.decode_report(utf8Decoder.decode(raw.bytes));\n        }\n        encode(rows) {\n          const input = Array.isArray(rows) ? rows : [];\n          const columns = outputColumnsFromRows(input, this.config);\n          const lines = [];\n          if (this.config.headers && columns) {\n            lines.push(this.encode_row(columns).replace(/\\n$/u, ""));\n          }\n          for (const row of input) {\n            lines.push(\n              formatOutputRow(row, columns).map((value) => encodeCell(value, this.config)).join(String(this.config.sep_char ?? ","))\n            );\n          }\n          return lines.join(String(this.config.eol ?? "\\n")) + (lines.length > 0 ? String(this.config.eol ?? "\\n") : "");\n        }\n        encode_binarystring(rows) {\n          return new BinaryString2(utf8Encoder.encode(this.encode(rows)));\n        }\n        encode_row(row) {\n          const fields = formatOutputRow(row, null);\n          return fields.map((value) => encodeCell(value, this.config)).join(String(this.config.sep_char ?? ",")) + String(this.config.eol ?? "\\n");\n        }\n        encode_row_binarystring(row) {\n          return new BinaryString2(utf8Encoder.encode(this.encode_row(row)));\n        }\n        load(pathValue) {\n          if (!isPath(pathValue)) {\n            throw new Error("TypeException: CSV.load expects Path as first argument");\n          }\n          assertCapability("fs", "CSV.load is denied by runtime policy");\n          return this.decode_binarystring(pathValue.slurp());\n        }\n        load_report(pathValue) {\n          if (!isPath(pathValue)) {\n            throw new Error("TypeException: CSV.load_report expects Path as first argument");\n          }\n          assertCapability("fs", "CSV.load_report is denied by runtime policy");\n          return this.decode_report_binarystring(pathValue.slurp());\n        }\n        dump(pathValue, rows) {\n          if (!isPath(pathValue)) {\n            throw new Error("TypeException: CSV.dump expects Path as first argument");\n          }\n          assertCapability("fs", "CSV.dump is denied by runtime policy");\n          pathValue.spew(this.encode_binarystring(rows));\n          return pathValue;\n        }\n        open(pathValue) {\n          if (!isPath(pathValue)) {\n            throw new Error("TypeException: CSV.open expects Path as first argument");\n          }\n          assertCapability("fs", "CSV.open is denied by runtime policy");\n          return new CSVReader(pathValue, this.config);\n        }\n        open_writer(pathValue, options = {}) {\n          if (!isPath(pathValue)) {\n            throw new Error("TypeException: CSV.open_writer expects Path as first argument");\n          }\n          assertCapability("fs", "CSV.open_writer is denied by runtime policy");\n          return new CSVWriter(pathValue, normalizeConfig(this.config, options));\n        }\n        dump_query(pathValue, dbh, sql, bind = [], options = {}) {\n          if (!isPath(pathValue)) {\n            throw new Error("TypeException: CSV.dump_query expects Path as first argument");\n          }\n          if (!isDbHandle(dbh)) {\n            throw new Error("TypeException: CSV.dump_query expects DatabaseHandle");\n          }\n          assertCapability("fs", "CSV.dump_query is denied by runtime policy");\n          assertCapability("db", "CSV.dump_query is denied by runtime policy");\n          const stmt = dbh.prepare(String(sql));\n          stmt.execute(...Array.isArray(bind) ? bind : []);\n          const rows = stmt.all_dict();\n          const config = normalizeConfig(this.config, { headers: true }, options);\n          return new _CSV(config).dump(pathValue, rows);\n        }\n        dump_table(pathValue, dbh, table, options = {}) {\n          return this.dump_query(\n            pathValue,\n            dbh,\n            `select * from ${quotedIdentifier(table)}`,\n            [],\n            normalizeConfig({ headers: true }, options)\n          );\n        }\n        load_table(pathValue, dbh, table, options = {}) {\n          if (!isPath(pathValue)) {\n            throw new Error("TypeException: CSV.load_table expects Path as first argument");\n          }\n          if (!isDbHandle(dbh)) {\n            throw new Error("TypeException: CSV.load_table expects DatabaseHandle");\n          }\n          assertCapability("fs", "CSV.load_table is denied by runtime policy");\n          assertCapability("db", "CSV.load_table is denied by runtime policy");\n          const config = normalizeConfig(this.config, options);\n          const reader = new _CSV(config).open(pathValue);\n          let sourceColumns = reader.columns();\n          let firstRow = sourceColumns ? reader.next_dict() : reader.next_array();\n          if (firstRow == null) {\n            reader.close();\n            return 0;\n          }\n          if (!sourceColumns) {\n            sourceColumns = Array.isArray(firstRow) ? defaultColumnsForRow(firstRow) : Object.keys(firstRow);\n            reader.set_columns(sourceColumns);\n            if (Array.isArray(firstRow)) {\n              firstRow = Object.fromEntries(\n                sourceColumns.map((name2, index) => [name2, firstRow[index]])\n              );\n            }\n          }\n          const targetColumns = sourceColumns.map(\n            (name2) => config.column_map && Object.prototype.hasOwnProperty.call(config.column_map, name2) ? config.column_map[name2] : name2\n          );\n          if (config.create_table) {\n            if (String(config.if_exists || "append").toLowerCase() === "replace") {\n              dbh.prepare(`drop table if exists ${quotedIdentifier(table)}`).execute();\n            }\n            const defs = targetColumns.map((name2, index) => {\n              let type = "TEXT";\n              if (Array.isArray(config.column_types)) {\n                type = String(config.column_types[index] || "TEXT");\n              } else if (isPlainObject2(config.column_types)) {\n                type = String(config.column_types[name2] || "TEXT");\n              }\n              return `${quotedIdentifier(name2)} ${type}`;\n            });\n            const ifNotExists = String(config.if_exists || "append").toLowerCase() === "append" ? " if not exists" : "";\n            dbh.prepare(\n              `create table${ifNotExists} ${quotedIdentifier(table)} (${defs.join(", ")})`\n            ).execute();\n          }\n          const conflict = String(config.conflict || "").trim();\n          const insertPrefix = conflict === "" || conflict.toLowerCase() === "default" ? "insert" : `insert or ${conflict.toUpperCase()}`;\n          const placeholders = targetColumns.map(() => "?").join(", ");\n          const stmt = dbh.prepare(\n            `${insertPrefix} into ${quotedIdentifier(table)} (${targetColumns.map(quotedIdentifier).join(", ")}) values (${placeholders})`\n          );\n          const transactionEnabled = config.transaction !== false;\n          const commitInterval = Number(config.commit_interval || 0);\n          let count = 0;\n          if (transactionEnabled) {\n            dbh.begin();\n          }\n          try {\n            const writeRow = (row2) => {\n              const dict = Array.isArray(row2) ? Object.fromEntries(sourceColumns.map((name2, index) => [name2, row2[index]])) : row2;\n              const values = sourceColumns.map((name2) => dict[name2]);\n              stmt.execute(...values);\n              count++;\n              if (transactionEnabled && commitInterval > 0 && count % commitInterval === 0) {\n                dbh.commit();\n                dbh.begin();\n              }\n            };\n            writeRow(firstRow);\n            let row;\n            while ((row = reader.next_dict()) !== null) {\n              writeRow(row);\n            }\n            if (transactionEnabled) {\n              dbh.commit();\n            }\n          } catch (error) {\n            if (transactionEnabled) {\n              dbh.rollback();\n            }\n            reader.close();\n            throw error;\n          }\n          reader.close();\n          return count;\n        }\n      };\n      module2.exports = {\n        CSV,\n        CSVReader,\n        CSVWriter,\n        __zuzu_set_runtime_policy(policy = {}) {\n          runtimePolicy2 = { ...runtimePolicy2, ...policy };\n        }\n      };\n    }\n  });\n\n  // node_modules/@xmldom/xmldom/lib/conventions.js\n  var require_conventions = __commonJS({\n    "node_modules/@xmldom/xmldom/lib/conventions.js"(exports2) {\n      "use strict";\n      function find(list, predicate, ac) {\n        if (ac === void 0) {\n          ac = Array.prototype;\n        }\n        if (list && typeof ac.find === "function") {\n          return ac.find.call(list, predicate);\n        }\n        for (var i = 0; i < list.length; i++) {\n          if (hasOwn(list, i)) {\n            var item = list[i];\n            if (predicate.call(void 0, item, i, list)) {\n              return item;\n            }\n          }\n        }\n      }\n      function freeze(object, oc) {\n        if (oc === void 0) {\n          oc = Object;\n        }\n        if (oc && typeof oc.getOwnPropertyDescriptors === "function") {\n          object = oc.create(null, oc.getOwnPropertyDescriptors(object));\n        }\n        return oc && typeof oc.freeze === "function" ? oc.freeze(object) : object;\n      }\n      function hasOwn(object, key) {\n        return Object.prototype.hasOwnProperty.call(object, key);\n      }\n      function assign(target, source) {\n        if (target === null || typeof target !== "object") {\n          throw new TypeError("target is not an object");\n        }\n        for (var key in source) {\n          if (hasOwn(source, key)) {\n            target[key] = source[key];\n          }\n        }\n        return target;\n      }\n      var HTML_BOOLEAN_ATTRIBUTES = freeze({\n        allowfullscreen: true,\n        async: true,\n        autofocus: true,\n        autoplay: true,\n        checked: true,\n        controls: true,\n        default: true,\n        defer: true,\n        disabled: true,\n        formnovalidate: true,\n        hidden: true,\n        ismap: true,\n        itemscope: true,\n        loop: true,\n        multiple: true,\n        muted: true,\n        nomodule: true,\n        novalidate: true,\n        open: true,\n        playsinline: true,\n        readonly: true,\n        required: true,\n        reversed: true,\n        selected: true\n      });\n      function isHTMLBooleanAttribute(name2) {\n        return hasOwn(HTML_BOOLEAN_ATTRIBUTES, name2.toLowerCase());\n      }\n      var HTML_VOID_ELEMENTS = freeze({\n        area: true,\n        base: true,\n        br: true,\n        col: true,\n        embed: true,\n        hr: true,\n        img: true,\n        input: true,\n        link: true,\n        meta: true,\n        param: true,\n        source: true,\n        track: true,\n        wbr: true\n      });\n      function isHTMLVoidElement(tagName) {\n        return hasOwn(HTML_VOID_ELEMENTS, tagName.toLowerCase());\n      }\n      var HTML_RAW_TEXT_ELEMENTS = freeze({\n        script: false,\n        style: false,\n        textarea: true,\n        title: true\n      });\n      function isHTMLRawTextElement(tagName) {\n        var key = tagName.toLowerCase();\n        return hasOwn(HTML_RAW_TEXT_ELEMENTS, key) && !HTML_RAW_TEXT_ELEMENTS[key];\n      }\n      function isHTMLEscapableRawTextElement(tagName) {\n        var key = tagName.toLowerCase();\n        return hasOwn(HTML_RAW_TEXT_ELEMENTS, key) && HTML_RAW_TEXT_ELEMENTS[key];\n      }\n      function isHTMLMimeType(mimeType) {\n        return mimeType === MIME_TYPE.HTML;\n      }\n      function hasDefaultHTMLNamespace(mimeType) {\n        return isHTMLMimeType(mimeType) || mimeType === MIME_TYPE.XML_XHTML_APPLICATION;\n      }\n      var MIME_TYPE = freeze({\n        /**\n         * `text/html`, the only mime type that triggers treating an XML document as HTML.\n         *\n         * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration\n         * @see https://en.wikipedia.org/wiki/HTML Wikipedia\n         * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN\n         * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring\n         *      WHATWG HTML Spec\n         */\n        HTML: "text/html",\n        /**\n         * `application/xml`, the standard mime type for XML documents.\n         *\n         * @see https://www.iana.org/assignments/media-types/application/xml IANA MimeType\n         *      registration\n         * @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303\n         * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia\n         */\n        XML_APPLICATION: "application/xml",\n        /**\n         * `text/xml`, an alias for `application/xml`.\n         *\n         * @see https://tools.ietf.org/html/rfc7303#section-9.2 RFC 7303\n         * @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration\n         * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia\n         */\n        XML_TEXT: "text/xml",\n        /**\n         * `application/xhtml+xml`, indicates an XML document that has the default HTML namespace,\n         * but is parsed as an XML document.\n         *\n         * @see https://www.iana.org/assignments/media-types/application/xhtml+xml IANA MimeType\n         *      registration\n         * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec\n         * @see https://en.wikipedia.org/wiki/XHTML Wikipedia\n         */\n        XML_XHTML_APPLICATION: "application/xhtml+xml",\n        /**\n         * `image/svg+xml`,\n         *\n         * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration\n         * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1\n         * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia\n         */\n        XML_SVG_IMAGE: "image/svg+xml"\n      });\n      var _MIME_TYPES = Object.keys(MIME_TYPE).map(function(key) {\n        return MIME_TYPE[key];\n      });\n      function isValidMimeType(mimeType) {\n        return _MIME_TYPES.indexOf(mimeType) > -1;\n      }\n      var NAMESPACE = freeze({\n        /**\n         * The XHTML namespace.\n         *\n         * @see http://www.w3.org/1999/xhtml\n         */\n        HTML: "http://www.w3.org/1999/xhtml",\n        /**\n         * The SVG namespace.\n         *\n         * @see http://www.w3.org/2000/svg\n         */\n        SVG: "http://www.w3.org/2000/svg",\n        /**\n         * The `xml:` namespace.\n         *\n         * @see http://www.w3.org/XML/1998/namespace\n         */\n        XML: "http://www.w3.org/XML/1998/namespace",\n        /**\n         * The `xmlns:` namespace.\n         *\n         * @see https://www.w3.org/2000/xmlns/\n         */\n        XMLNS: "http://www.w3.org/2000/xmlns/"\n      });\n      exports2.assign = assign;\n      exports2.find = find;\n      exports2.freeze = freeze;\n      exports2.HTML_BOOLEAN_ATTRIBUTES = HTML_BOOLEAN_ATTRIBUTES;\n      exports2.HTML_RAW_TEXT_ELEMENTS = HTML_RAW_TEXT_ELEMENTS;\n      exports2.HTML_VOID_ELEMENTS = HTML_VOID_ELEMENTS;\n      exports2.hasDefaultHTMLNamespace = hasDefaultHTMLNamespace;\n      exports2.hasOwn = hasOwn;\n      exports2.isHTMLBooleanAttribute = isHTMLBooleanAttribute;\n      exports2.isHTMLRawTextElement = isHTMLRawTextElement;\n      exports2.isHTMLEscapableRawTextElement = isHTMLEscapableRawTextElement;\n      exports2.isHTMLMimeType = isHTMLMimeType;\n      exports2.isHTMLVoidElement = isHTMLVoidElement;\n      exports2.isValidMimeType = isValidMimeType;\n      exports2.MIME_TYPE = MIME_TYPE;\n      exports2.NAMESPACE = NAMESPACE;\n    }\n  });\n\n  // node_modules/@xmldom/xmldom/lib/errors.js\n  var require_errors2 = __commonJS({\n    "node_modules/@xmldom/xmldom/lib/errors.js"(exports2) {\n      "use strict";\n      var conventions = require_conventions();\n      function extendError(constructor, writableName) {\n        constructor.prototype = Object.create(Error.prototype, {\n          constructor: { value: constructor },\n          name: { value: constructor.name, enumerable: true, writable: writableName }\n        });\n      }\n      var DOMExceptionName = conventions.freeze({\n        /**\n         * the default value as defined by the spec\n         */\n        Error: "Error",\n        /**\n         * @deprecated\n         * Use RangeError instead.\n         */\n        IndexSizeError: "IndexSizeError",\n        /**\n         * @deprecated\n         * Just to match the related static code, not part of the spec.\n         */\n        DomstringSizeError: "DomstringSizeError",\n        HierarchyRequestError: "HierarchyRequestError",\n        WrongDocumentError: "WrongDocumentError",\n        InvalidCharacterError: "InvalidCharacterError",\n        /**\n         * @deprecated\n         * Just to match the related static code, not part of the spec.\n         */\n        NoDataAllowedError: "NoDataAllowedError",\n        NoModificationAllowedError: "NoModificationAllowedError",\n        NotFoundError: "NotFoundError",\n        NotSupportedError: "NotSupportedError",\n        InUseAttributeError: "InUseAttributeError",\n        InvalidStateError: "InvalidStateError",\n        SyntaxError: "SyntaxError",\n        InvalidModificationError: "InvalidModificationError",\n        NamespaceError: "NamespaceError",\n        /**\n         * @deprecated\n         * Use TypeError for invalid arguments,\n         * "NotSupportedError" DOMException for unsupported operations,\n         * and "NotAllowedError" DOMException for denied requests instead.\n         */\n        InvalidAccessError: "InvalidAccessError",\n        /**\n         * @deprecated\n         * Just to match the related static code, not part of the spec.\n         */\n        ValidationError: "ValidationError",\n        /**\n         * @deprecated\n         * Use TypeError instead.\n         */\n        TypeMismatchError: "TypeMismatchError",\n        SecurityError: "SecurityError",\n        NetworkError: "NetworkError",\n        AbortError: "AbortError",\n        /**\n         * @deprecated\n         * Just to match the related static code, not part of the spec.\n         */\n        URLMismatchError: "URLMismatchError",\n        QuotaExceededError: "QuotaExceededError",\n        TimeoutError: "TimeoutError",\n        InvalidNodeTypeError: "InvalidNodeTypeError",\n        DataCloneError: "DataCloneError",\n        EncodingError: "EncodingError",\n        NotReadableError: "NotReadableError",\n        UnknownError: "UnknownError",\n        ConstraintError: "ConstraintError",\n        DataError: "DataError",\n        TransactionInactiveError: "TransactionInactiveError",\n        ReadOnlyError: "ReadOnlyError",\n        VersionError: "VersionError",\n        OperationError: "OperationError",\n        NotAllowedError: "NotAllowedError",\n        OptOutError: "OptOutError"\n      });\n      var DOMExceptionNames = Object.keys(DOMExceptionName);\n      function isValidDomExceptionCode(value) {\n        return typeof value === "number" && value >= 1 && value <= 25;\n      }\n      function endsWithError(value) {\n        return typeof value === "string" && value.substring(value.length - DOMExceptionName.Error.length) === DOMExceptionName.Error;\n      }\n      function DOMException(messageOrCode, nameOrMessage) {\n        if (isValidDomExceptionCode(messageOrCode)) {\n          this.name = DOMExceptionNames[messageOrCode];\n          this.message = nameOrMessage || "";\n        } else {\n          this.message = messageOrCode;\n          this.name = endsWithError(nameOrMessage) ? nameOrMessage : DOMExceptionName.Error;\n        }\n        if (Error.captureStackTrace) Error.captureStackTrace(this, DOMException);\n      }\n      extendError(DOMException, true);\n      Object.defineProperties(DOMException.prototype, {\n        code: {\n          enumerable: true,\n          get: function() {\n            var code = DOMExceptionNames.indexOf(this.name);\n            if (isValidDomExceptionCode(code)) return code;\n            return 0;\n          }\n        }\n      });\n      var ExceptionCode = {\n        INDEX_SIZE_ERR: 1,\n        DOMSTRING_SIZE_ERR: 2,\n        HIERARCHY_REQUEST_ERR: 3,\n        WRONG_DOCUMENT_ERR: 4,\n        INVALID_CHARACTER_ERR: 5,\n        NO_DATA_ALLOWED_ERR: 6,\n        NO_MODIFICATION_ALLOWED_ERR: 7,\n        NOT_FOUND_ERR: 8,\n        NOT_SUPPORTED_ERR: 9,\n        INUSE_ATTRIBUTE_ERR: 10,\n        INVALID_STATE_ERR: 11,\n        SYNTAX_ERR: 12,\n        INVALID_MODIFICATION_ERR: 13,\n        NAMESPACE_ERR: 14,\n        INVALID_ACCESS_ERR: 15,\n        VALIDATION_ERR: 16,\n        TYPE_MISMATCH_ERR: 17,\n        SECURITY_ERR: 18,\n        NETWORK_ERR: 19,\n        ABORT_ERR: 20,\n        URL_MISMATCH_ERR: 21,\n        QUOTA_EXCEEDED_ERR: 22,\n        TIMEOUT_ERR: 23,\n        INVALID_NODE_TYPE_ERR: 24,\n        DATA_CLONE_ERR: 25\n      };\n      var entries = Object.entries(ExceptionCode);\n      for (i = 0; i < entries.length; i++) {\n        key = entries[i][0];\n        DOMException[key] = entries[i][1];\n      }\n      var key;\n      var i;\n      function ParseError(message, locator) {\n        this.message = message;\n        this.locator = locator;\n        if (Error.captureStackTrace) Error.captureStackTrace(this, ParseError);\n      }\n      extendError(ParseError);\n      exports2.DOMException = DOMException;\n      exports2.DOMExceptionName = DOMExceptionName;\n      exports2.ExceptionCode = ExceptionCode;\n      exports2.ParseError = ParseError;\n    }\n  });\n\n  // node_modules/@xmldom/xmldom/lib/grammar.js\n  var require_grammar = __commonJS({\n    "node_modules/@xmldom/xmldom/lib/grammar.js"(exports2) {\n      "use strict";\n      function detectUnicodeSupport(RegExpImpl) {\n        try {\n          if (typeof RegExpImpl !== "function") {\n            RegExpImpl = RegExp;\n          }\n          var match = new RegExpImpl("\\u{1D306}", "u").exec("\\u{1D306}");\n          return !!match && match[0].length === 2;\n        } catch (error) {\n        }\n        return false;\n      }\n      var UNICODE_SUPPORT = detectUnicodeSupport();\n      function chars(regexp) {\n        if (regexp.source[0] !== "[") {\n          throw new Error(regexp + " can not be used with chars");\n        }\n        return regexp.source.slice(1, regexp.source.lastIndexOf("]"));\n      }\n      function chars_without(regexp, search) {\n        if (regexp.source[0] !== "[") {\n          throw new Error("/" + regexp.source + "/ can not be used with chars_without");\n        }\n        if (!search || typeof search !== "string") {\n          throw new Error(JSON.stringify(search) + " is not a valid search");\n        }\n        if (regexp.source.indexOf(search) === -1) {\n          throw new Error(\'"\' + search + \'" is not is /\' + regexp.source + "/");\n        }\n        if (search === "-" && regexp.source.indexOf(search) !== 1) {\n          throw new Error(\'"\' + search + \'" is not at the first postion of /\' + regexp.source + "/");\n        }\n        return new RegExp(regexp.source.replace(search, ""), UNICODE_SUPPORT ? "u" : "");\n      }\n      function reg(args) {\n        var self = this;\n        return new RegExp(\n          Array.prototype.slice.call(arguments).map(function(part) {\n            var isStr = typeof part === "string";\n            if (isStr && self === void 0 && part === "|") {\n              throw new Error("use regg instead of reg to wrap expressions with `|`!");\n            }\n            return isStr ? part : part.source;\n          }).join(""),\n          UNICODE_SUPPORT ? "mu" : "m"\n        );\n      }\n      function regg(args) {\n        if (arguments.length === 0) {\n          throw new Error("no parameters provided");\n        }\n        return reg.apply(regg, ["(?:"].concat(Array.prototype.slice.call(arguments), [")"]));\n      }\n      var UNICODE_REPLACEMENT_CHARACTER = "\\uFFFD";\n      var Char = /[-\\x09\\x0A\\x0D\\x20-\\x2C\\x2E-\\uD7FF\\uE000-\\uFFFD]/;\n      if (UNICODE_SUPPORT) {\n        Char = reg("[", chars(Char), "\\\\u{10000}-\\\\u{10FFFF}", "]");\n      }\n      var InvalidChar = new RegExp("[^" + chars(Char) + "]", UNICODE_SUPPORT ? "u" : "");\n      var _SChar = /[\\x20\\x09\\x0D\\x0A]/;\n      var SChar_s = chars(_SChar);\n      var S = reg(_SChar, "+");\n      var S_OPT = reg(_SChar, "*");\n      var NameStartChar = /[:_a-zA-Z\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02FF\\u0370-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]/;\n      if (UNICODE_SUPPORT) {\n        NameStartChar = reg("[", chars(NameStartChar), "\\\\u{10000}-\\\\u{10FFFF}", "]");\n      }\n      var NameStartChar_s = chars(NameStartChar);\n      var NameChar = reg("[", NameStartChar_s, chars(/[-.0-9\\xB7]/), chars(/[\\u0300-\\u036F\\u203F-\\u2040]/), "]");\n      var Name = reg(NameStartChar, NameChar, "*");\n      var Nmtoken = reg(NameChar, "+");\n      var EntityRef = reg("&", Name, ";");\n      var CharRef = regg(/&#[0-9]+;|&#x[0-9a-fA-F]+;/);\n      var Reference = regg(EntityRef, "|", CharRef);\n      var PEReference = reg("%", Name, ";");\n      var EntityValue = regg(\n        reg(\'"\', regg(/[^%&"]/, "|", PEReference, "|", Reference), "*", \'"\'),\n        "|",\n        reg("\'", regg(/[^%&\']/, "|", PEReference, "|", Reference), "*", "\'")\n      );\n      var AttValue = regg(\'"\', regg(/[^<&"]/, "|", Reference), "*", \'"\', "|", "\'", regg(/[^<&\']/, "|", Reference), "*", "\'");\n      var NCNameStartChar = chars_without(NameStartChar, ":");\n      var NCNameChar = chars_without(NameChar, ":");\n      var NCName = reg(NCNameStartChar, NCNameChar, "*");\n      var QName = reg(NCName, regg(":", NCName), "?");\n      var QName_exact = reg("^", QName, "$");\n      var QName_group = reg("(", QName, ")");\n      var SystemLiteral = regg(/"[^"]*"|\'[^\']*\'/);\n      var PI = reg(/^<\\?/, "(", Name, ")", regg(S, "(", Char, "*?)"), "?", /\\?>/);\n      var PubidChar = /[\\x20\\x0D\\x0Aa-zA-Z0-9-\'()+,./:=?;!*#@$_%]/;\n      var PubidLiteral = regg(\'"\', PubidChar, \'*"\', "|", "\'", chars_without(PubidChar, "\'"), "*\'");\n      var COMMENT_START = "<!--";\n      var COMMENT_END = "-->";\n      var Comment = reg(COMMENT_START, regg(chars_without(Char, "-"), "|", reg("-", chars_without(Char, "-"))), "*", COMMENT_END);\n      var PCDATA = "#PCDATA";\n      var Mixed = regg(\n        reg(/\\(/, S_OPT, PCDATA, regg(S_OPT, /\\|/, S_OPT, QName), "*", S_OPT, /\\)\\*/),\n        "|",\n        reg(/\\(/, S_OPT, PCDATA, S_OPT, /\\)/)\n      );\n      var _children_quantity = /[?*+]?/;\n      var children = reg(\n        /\\([^>]+\\)/,\n        _children_quantity\n        /*regg(choice, \'|\', seq), _children_quantity*/\n      );\n      var contentspec = regg("EMPTY", "|", "ANY", "|", Mixed, "|", children);\n      var ELEMENTDECL_START = "<!ELEMENT";\n      var elementdecl = reg(ELEMENTDECL_START, S, regg(QName, "|", PEReference), S, regg(contentspec, "|", PEReference), S_OPT, ">");\n      var NotationType = reg("NOTATION", S, /\\(/, S_OPT, Name, regg(S_OPT, /\\|/, S_OPT, Name), "*", S_OPT, /\\)/);\n      var Enumeration = reg(/\\(/, S_OPT, Nmtoken, regg(S_OPT, /\\|/, S_OPT, Nmtoken), "*", S_OPT, /\\)/);\n      var EnumeratedType = regg(NotationType, "|", Enumeration);\n      var AttType = regg(/CDATA|ID|IDREF|IDREFS|ENTITY|ENTITIES|NMTOKEN|NMTOKENS/, "|", EnumeratedType);\n      var DefaultDecl = regg(/#REQUIRED|#IMPLIED/, "|", regg(regg("#FIXED", S), "?", AttValue));\n      var AttDef = regg(S, Name, S, AttType, S, DefaultDecl);\n      var ATTLIST_DECL_START = "<!ATTLIST";\n      var AttlistDecl = reg(ATTLIST_DECL_START, S, Name, AttDef, "*", S_OPT, ">");\n      var ABOUT_LEGACY_COMPAT = "about:legacy-compat";\n      var ABOUT_LEGACY_COMPAT_SystemLiteral = regg(\'"\' + ABOUT_LEGACY_COMPAT + \'"\', "|", "\'" + ABOUT_LEGACY_COMPAT + "\'");\n      var SYSTEM = "SYSTEM";\n      var PUBLIC = "PUBLIC";\n      var ExternalID = regg(regg(SYSTEM, S, SystemLiteral), "|", regg(PUBLIC, S, PubidLiteral, S, SystemLiteral));\n      var ExternalID_match = reg(\n        "^",\n        regg(\n          regg(SYSTEM, S, "(?<SystemLiteralOnly>", SystemLiteral, ")"),\n          "|",\n          regg(PUBLIC, S, "(?<PubidLiteral>", PubidLiteral, ")", S, "(?<SystemLiteral>", SystemLiteral, ")")\n        )\n      );\n      var PubidLiteral_match = reg("^", PubidLiteral, "$");\n      var SystemLiteral_match = reg("^", SystemLiteral, "$");\n      var NDataDecl = regg(S, "NDATA", S, Name);\n      var EntityDef = regg(EntityValue, "|", regg(ExternalID, NDataDecl, "?"));\n      var ENTITY_DECL_START = "<!ENTITY";\n      var GEDecl = reg(ENTITY_DECL_START, S, Name, S, EntityDef, S_OPT, ">");\n      var PEDef = regg(EntityValue, "|", ExternalID);\n      var PEDecl = reg(ENTITY_DECL_START, S, "%", S, Name, S, PEDef, S_OPT, ">");\n      var EntityDecl = regg(GEDecl, "|", PEDecl);\n      var PublicID = reg(PUBLIC, S, PubidLiteral);\n      var NotationDecl = reg("<!NOTATION", S, Name, S, regg(ExternalID, "|", PublicID), S_OPT, ">");\n      var Eq = reg(S_OPT, "=", S_OPT);\n      var VersionNum = /1[.]\\d+/;\n      var VersionInfo = reg(S, "version", Eq, regg("\'", VersionNum, "\'", "|", \'"\', VersionNum, \'"\'));\n      var EncName = /[A-Za-z][-A-Za-z0-9._]*/;\n      var EncodingDecl = regg(S, "encoding", Eq, regg(\'"\', EncName, \'"\', "|", "\'", EncName, "\'"));\n      var SDDecl = regg(S, "standalone", Eq, regg("\'", regg("yes", "|", "no"), "\'", "|", \'"\', regg("yes", "|", "no"), \'"\'));\n      var XMLDecl = reg(/^<\\?xml/, VersionInfo, EncodingDecl, "?", SDDecl, "?", S_OPT, /\\?>/);\n      var DOCTYPE_DECL_START = "<!DOCTYPE";\n      var CDATA_START = "<![CDATA[";\n      var CDATA_END = "]]>";\n      var CDStart = /<!\\[CDATA\\[/;\n      var CDEnd = /\\]\\]>/;\n      var CData = reg(Char, "*?", CDEnd);\n      var CDSect = reg(CDStart, CData);\n      exports2.chars = chars;\n      exports2.chars_without = chars_without;\n      exports2.detectUnicodeSupport = detectUnicodeSupport;\n      exports2.reg = reg;\n      exports2.regg = regg;\n      exports2.ABOUT_LEGACY_COMPAT = ABOUT_LEGACY_COMPAT;\n      exports2.ABOUT_LEGACY_COMPAT_SystemLiteral = ABOUT_LEGACY_COMPAT_SystemLiteral;\n      exports2.AttlistDecl = AttlistDecl;\n      exports2.CDATA_START = CDATA_START;\n      exports2.CDATA_END = CDATA_END;\n      exports2.CDSect = CDSect;\n      exports2.Char = Char;\n      exports2.Comment = Comment;\n      exports2.COMMENT_START = COMMENT_START;\n      exports2.COMMENT_END = COMMENT_END;\n      exports2.DOCTYPE_DECL_START = DOCTYPE_DECL_START;\n      exports2.elementdecl = elementdecl;\n      exports2.EntityDecl = EntityDecl;\n      exports2.EntityValue = EntityValue;\n      exports2.ExternalID = ExternalID;\n      exports2.ExternalID_match = ExternalID_match;\n      exports2.Name = Name;\n      exports2.NotationDecl = NotationDecl;\n      exports2.Reference = Reference;\n      exports2.PEReference = PEReference;\n      exports2.PI = PI;\n      exports2.PUBLIC = PUBLIC;\n      exports2.PubidLiteral = PubidLiteral;\n      exports2.PubidLiteral_match = PubidLiteral_match;\n      exports2.QName = QName;\n      exports2.QName_exact = QName_exact;\n      exports2.QName_group = QName_group;\n      exports2.S = S;\n      exports2.SChar_s = SChar_s;\n      exports2.S_OPT = S_OPT;\n      exports2.SYSTEM = SYSTEM;\n      exports2.SystemLiteral = SystemLiteral;\n      exports2.SystemLiteral_match = SystemLiteral_match;\n      exports2.InvalidChar = InvalidChar;\n      exports2.UNICODE_REPLACEMENT_CHARACTER = UNICODE_REPLACEMENT_CHARACTER;\n      exports2.UNICODE_SUPPORT = UNICODE_SUPPORT;\n      exports2.XMLDecl = XMLDecl;\n    }\n  });\n\n  // node_modules/@xmldom/xmldom/lib/dom.js\n  var require_dom = __commonJS({\n    "node_modules/@xmldom/xmldom/lib/dom.js"(exports2) {\n      "use strict";\n      var conventions = require_conventions();\n      var find = conventions.find;\n      var hasDefaultHTMLNamespace = conventions.hasDefaultHTMLNamespace;\n      var hasOwn = conventions.hasOwn;\n      var isHTMLMimeType = conventions.isHTMLMimeType;\n      var isHTMLRawTextElement = conventions.isHTMLRawTextElement;\n      var isHTMLVoidElement = conventions.isHTMLVoidElement;\n      var MIME_TYPE = conventions.MIME_TYPE;\n      var NAMESPACE = conventions.NAMESPACE;\n      var PDC = /* @__PURE__ */ Symbol();\n      var errors = require_errors2();\n      var DOMException = errors.DOMException;\n      var DOMExceptionName = errors.DOMExceptionName;\n      var g = require_grammar();\n      function checkSymbol(symbol) {\n        if (symbol !== PDC) {\n          throw new TypeError("Illegal constructor");\n        }\n      }\n      function notEmptyString(input) {\n        return input !== "";\n      }\n      function splitOnASCIIWhitespace(input) {\n        return input ? input.split(/[\\t\\n\\f\\r ]+/).filter(notEmptyString) : [];\n      }\n      function orderedSetReducer(current, element) {\n        if (!hasOwn(current, element)) {\n          current[element] = true;\n        }\n        return current;\n      }\n      function toOrderedSet(input) {\n        if (!input) return [];\n        var list = splitOnASCIIWhitespace(input);\n        return Object.keys(list.reduce(orderedSetReducer, {}));\n      }\n      function arrayIncludes(list) {\n        return function(element) {\n          return list && list.indexOf(element) !== -1;\n        };\n      }\n      function validateQualifiedName(qualifiedName) {\n        if (!g.QName_exact.test(qualifiedName)) {\n          throw new DOMException(DOMException.INVALID_CHARACTER_ERR, \'invalid character in qualified name "\' + qualifiedName + \'"\');\n        }\n      }\n      function validateAndExtract(namespace, qualifiedName) {\n        validateQualifiedName(qualifiedName);\n        namespace = namespace || null;\n        var prefix = null;\n        var localName = qualifiedName;\n        if (qualifiedName.indexOf(":") >= 0) {\n          var splitResult = qualifiedName.split(":");\n          prefix = splitResult[0];\n          localName = splitResult[1];\n        }\n        if (prefix !== null && namespace === null) {\n          throw new DOMException(DOMException.NAMESPACE_ERR, "prefix is non-null and namespace is null");\n        }\n        if (prefix === "xml" && namespace !== conventions.NAMESPACE.XML) {\n          throw new DOMException(DOMException.NAMESPACE_ERR, \'prefix is "xml" and namespace is not the XML namespace\');\n        }\n        if ((prefix === "xmlns" || qualifiedName === "xmlns") && namespace !== conventions.NAMESPACE.XMLNS) {\n          throw new DOMException(\n            DOMException.NAMESPACE_ERR,\n            \'either qualifiedName or prefix is "xmlns" and namespace is not the XMLNS namespace\'\n          );\n        }\n        if (namespace === conventions.NAMESPACE.XMLNS && prefix !== "xmlns" && qualifiedName !== "xmlns") {\n          throw new DOMException(\n            DOMException.NAMESPACE_ERR,\n            \'namespace is the XMLNS namespace and neither qualifiedName nor prefix is "xmlns"\'\n          );\n        }\n        return [namespace, prefix, localName];\n      }\n      function copy(src, dest) {\n        for (var p in src) {\n          if (hasOwn(src, p)) {\n            dest[p] = src[p];\n          }\n        }\n      }\n      function _extends(Class, Super) {\n        var pt = Class.prototype;\n        if (!(pt instanceof Super)) {\n          let t = function() {\n          };\n          t.prototype = Super.prototype;\n          t = new t();\n          copy(pt, t);\n          Class.prototype = pt = t;\n        }\n        if (pt.constructor != Class) {\n          if (typeof Class != "function") {\n            console.error("unknown Class:" + Class);\n          }\n          pt.constructor = Class;\n        }\n      }\n      var NodeType = {};\n      var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;\n      var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;\n      var TEXT_NODE = NodeType.TEXT_NODE = 3;\n      var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;\n      var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;\n      var ENTITY_NODE = NodeType.ENTITY_NODE = 6;\n      var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;\n      var COMMENT_NODE = NodeType.COMMENT_NODE = 8;\n      var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;\n      var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;\n      var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;\n      var NOTATION_NODE = NodeType.NOTATION_NODE = 12;\n      var DocumentPosition = conventions.freeze({\n        DOCUMENT_POSITION_DISCONNECTED: 1,\n        DOCUMENT_POSITION_PRECEDING: 2,\n        DOCUMENT_POSITION_FOLLOWING: 4,\n        DOCUMENT_POSITION_CONTAINS: 8,\n        DOCUMENT_POSITION_CONTAINED_BY: 16,\n        DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 32\n      });\n      function commonAncestor(a, b) {\n        if (b.length < a.length) return commonAncestor(b, a);\n        var c = null;\n        for (var n in a) {\n          if (a[n] !== b[n]) return c;\n          c = a[n];\n        }\n        return c;\n      }\n      function docGUID(doc) {\n        if (!doc.guid) doc.guid = Math.random();\n        return doc.guid;\n      }\n      function NodeList() {\n      }\n      NodeList.prototype = {\n        /**\n         * The number of nodes in the list. The range of valid child node indices is 0 to length-1\n         * inclusive.\n         *\n         * @type {number}\n         */\n        length: 0,\n        /**\n         * Returns the item at `index`. If index is greater than or equal to the number of nodes in\n         * the list, this returns null.\n         *\n         * @param index\n         * Unsigned long Index into the collection.\n         * @returns {Node | null}\n         * The node at position `index` in the NodeList,\n         * or null if that is not a valid index.\n         */\n        item: function(index) {\n          return index >= 0 && index < this.length ? this[index] : null;\n        },\n        /**\n         * Returns a string representation of the NodeList.\n         *\n         * Accepts the same `options` object as `XMLSerializer.prototype.serializeToString`\n         * (`requireWellFormed`, `splitCDATASections`, `nodeFilter`). Passing a function is treated as\n         * a legacy `nodeFilter` for backward compatibility.\n         *\n         * @param {Object | function} [options]\n         * @param {boolean} [options.requireWellFormed=false]\n         * @param {boolean} [options.splitCDATASections=true]\n         * @param {function} [options.nodeFilter]\n         * @returns {string}\n         */\n        toString: function(options) {\n          var opts;\n          if (typeof options === "function") {\n            opts = { requireWellFormed: false, splitCDATASections: true, nodeFilter: options };\n          } else if (!!options) {\n            opts = {\n              requireWellFormed: !!options.requireWellFormed,\n              splitCDATASections: options.splitCDATASections !== false,\n              nodeFilter: options.nodeFilter || null\n            };\n          } else {\n            opts = { requireWellFormed: false, splitCDATASections: true, nodeFilter: null };\n          }\n          for (var buf = [], i = 0; i < this.length; i++) {\n            serializeToString(this[i], buf, null, opts);\n          }\n          return buf.join("");\n        },\n        /**\n         * Filters the NodeList based on a predicate.\n         *\n         * @param {function(Node): boolean} predicate\n         * - A predicate function to filter the NodeList.\n         * @returns {Node[]}\n         * An array of nodes that satisfy the predicate.\n         * @private\n         */\n        filter: function(predicate) {\n          return Array.prototype.filter.call(this, predicate);\n        },\n        /**\n         * Returns the first index at which a given node can be found in the NodeList, or -1 if it is\n         * not present.\n         *\n         * @param {Node} item\n         * - The Node item to locate in the NodeList.\n         * @returns {number}\n         * The first index of the node in the NodeList; -1 if not found.\n         * @private\n         */\n        indexOf: function(item) {\n          return Array.prototype.indexOf.call(this, item);\n        }\n      };\n      NodeList.prototype[Symbol.iterator] = function() {\n        var me = this;\n        var index = 0;\n        return {\n          next: function() {\n            if (index < me.length) {\n              return {\n                value: me[index++],\n                done: false\n              };\n            } else {\n              return {\n                done: true\n              };\n            }\n          },\n          return: function() {\n            return {\n              done: true\n            };\n          }\n        };\n      };\n      function LiveNodeList(node, refresh) {\n        this._node = node;\n        this._refresh = refresh;\n        _updateLiveList(this);\n      }\n      function _updateLiveList(list) {\n        var inc = list._node._inc || list._node.ownerDocument._inc;\n        if (list._inc !== inc) {\n          var ls = list._refresh(list._node);\n          __set__(list, "length", ls.length);\n          if (!list.$$length || ls.length < list.$$length) {\n            for (var i = ls.length; i in list; i++) {\n              if (hasOwn(list, i)) {\n                delete list[i];\n              }\n            }\n          }\n          copy(ls, list);\n          list._inc = inc;\n        }\n      }\n      LiveNodeList.prototype.item = function(i) {\n        _updateLiveList(this);\n        return this[i] || null;\n      };\n      _extends(LiveNodeList, NodeList);\n      function NamedNodeMap() {\n      }\n      function _findNodeIndex(list, node) {\n        var i = 0;\n        while (i < list.length) {\n          if (list[i] === node) {\n            return i;\n          }\n          i++;\n        }\n      }\n      function _addNamedNode(el, list, newAttr, oldAttr) {\n        if (oldAttr) {\n          list[_findNodeIndex(list, oldAttr)] = newAttr;\n        } else {\n          list[list.length] = newAttr;\n          list.length++;\n        }\n        if (el) {\n          newAttr.ownerElement = el;\n          var doc = el.ownerDocument;\n          if (doc) {\n            oldAttr && _onRemoveAttribute(doc, el, oldAttr);\n            _onAddAttribute(doc, el, newAttr);\n          }\n        }\n      }\n      function _removeNamedNode(el, list, attr) {\n        var i = _findNodeIndex(list, attr);\n        if (i >= 0) {\n          var lastIndex = list.length - 1;\n          while (i <= lastIndex) {\n            list[i] = list[++i];\n          }\n          list.length = lastIndex;\n          if (el) {\n            var doc = el.ownerDocument;\n            if (doc) {\n              _onRemoveAttribute(doc, el, attr);\n            }\n            attr.ownerElement = null;\n          }\n        }\n      }\n      NamedNodeMap.prototype = {\n        length: 0,\n        item: NodeList.prototype.item,\n        /**\n         * Get an attribute by name. Note: Name is in lower case in case of HTML namespace and\n         * document.\n         *\n         * @param {string} localName\n         * The local name of the attribute.\n         * @returns {Attr | null}\n         * The attribute with the given local name, or null if no such attribute exists.\n         * @see https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name\n         */\n        getNamedItem: function(localName) {\n          if (this._ownerElement && this._ownerElement._isInHTMLDocumentAndNamespace()) {\n            localName = localName.toLowerCase();\n          }\n          var i = 0;\n          while (i < this.length) {\n            var attr = this[i];\n            if (attr.nodeName === localName) {\n              return attr;\n            }\n            i++;\n          }\n          return null;\n        },\n        /**\n         * Set an attribute.\n         *\n         * @param {Attr} attr\n         * The attribute to set.\n         * @returns {Attr | null}\n         * The old attribute with the same local name and namespace URI as the new one, or null if no\n         * such attribute exists.\n         * @throws {DOMException}\n         * With code:\n         * - {@link INUSE_ATTRIBUTE_ERR} - If the attribute is already an attribute of another\n         * element.\n         * @see https://dom.spec.whatwg.org/#concept-element-attributes-set\n         */\n        setNamedItem: function(attr) {\n          var el = attr.ownerElement;\n          if (el && el !== this._ownerElement) {\n            throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR);\n          }\n          var oldAttr = this.getNamedItemNS(attr.namespaceURI, attr.localName);\n          if (oldAttr === attr) {\n            return attr;\n          }\n          _addNamedNode(this._ownerElement, this, attr, oldAttr);\n          return oldAttr;\n        },\n        /**\n         * Set an attribute, replacing an existing attribute with the same local name and namespace\n         * URI if one exists.\n         *\n         * @param {Attr} attr\n         * The attribute to set.\n         * @returns {Attr | null}\n         * The old attribute with the same local name and namespace URI as the new one, or null if no\n         * such attribute exists.\n         * @throws {DOMException}\n         * Throws a DOMException with the name "InUseAttributeError" if the attribute is already an\n         * attribute of another element.\n         * @see https://dom.spec.whatwg.org/#concept-element-attributes-set\n         */\n        setNamedItemNS: function(attr) {\n          return this.setNamedItem(attr);\n        },\n        /**\n         * Removes an attribute specified by the local name.\n         *\n         * @param {string} localName\n         * The local name of the attribute to be removed.\n         * @returns {Attr}\n         * The attribute node that was removed.\n         * @throws {DOMException}\n         * With code:\n         * - {@link DOMException.NOT_FOUND_ERR} if no attribute with the given name is found.\n         * @see https://dom.spec.whatwg.org/#dom-namednodemap-removenameditem\n         * @see https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-name\n         */\n        removeNamedItem: function(localName) {\n          var attr = this.getNamedItem(localName);\n          if (!attr) {\n            throw new DOMException(DOMException.NOT_FOUND_ERR, localName);\n          }\n          _removeNamedNode(this._ownerElement, this, attr);\n          return attr;\n        },\n        /**\n         * Removes an attribute specified by the namespace and local name.\n         *\n         * @param {string | null} namespaceURI\n         * The namespace URI of the attribute to be removed.\n         * @param {string} localName\n         * The local name of the attribute to be removed.\n         * @returns {Attr}\n         * The attribute node that was removed.\n         * @throws {DOMException}\n         * With code:\n         * - {@link DOMException.NOT_FOUND_ERR} if no attribute with the given namespace URI and local\n         * name is found.\n         * @see https://dom.spec.whatwg.org/#dom-namednodemap-removenameditemns\n         * @see https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-namespace\n         */\n        removeNamedItemNS: function(namespaceURI, localName) {\n          var attr = this.getNamedItemNS(namespaceURI, localName);\n          if (!attr) {\n            throw new DOMException(DOMException.NOT_FOUND_ERR, namespaceURI ? namespaceURI + " : " + localName : localName);\n          }\n          _removeNamedNode(this._ownerElement, this, attr);\n          return attr;\n        },\n        /**\n         * Get an attribute by namespace and local name.\n         *\n         * @param {string | null} namespaceURI\n         * The namespace URI of the attribute.\n         * @param {string} localName\n         * The local name of the attribute.\n         * @returns {Attr | null}\n         * The attribute with the given namespace URI and local name, or null if no such attribute\n         * exists.\n         * @see https://dom.spec.whatwg.org/#concept-element-attributes-get-by-namespace\n         */\n        getNamedItemNS: function(namespaceURI, localName) {\n          if (!namespaceURI) {\n            namespaceURI = null;\n          }\n          var i = 0;\n          while (i < this.length) {\n            var node = this[i];\n            if (node.localName === localName && node.namespaceURI === namespaceURI) {\n              return node;\n            }\n            i++;\n          }\n          return null;\n        }\n      };\n      NamedNodeMap.prototype[Symbol.iterator] = function() {\n        var me = this;\n        var index = 0;\n        return {\n          next: function() {\n            if (index < me.length) {\n              return {\n                value: me[index++],\n                done: false\n              };\n            } else {\n              return {\n                done: true\n              };\n            }\n          },\n          return: function() {\n            return {\n              done: true\n            };\n          }\n        };\n      };\n      function DOMImplementation() {\n      }\n      DOMImplementation.prototype = {\n        /**\n         * Test if the DOM implementation implements a specific feature and version, as specified in\n         * {@link https://www.w3.org/TR/DOM-Level-3-Core/core.html#DOMFeatures DOM Features}.\n         *\n         * The DOMImplementation.hasFeature() method returns a Boolean flag indicating if a given\n         * feature is supported. The different implementations fairly diverged in what kind of\n         * features were reported. The latest version of the spec settled to force this method to\n         * always return true, where the functionality was accurate and in use.\n         *\n         * @deprecated\n         * It is deprecated and modern browsers return true in all cases.\n         * @function DOMImplementation#hasFeature\n         * @param {string} feature\n         * The name of the feature to test.\n         * @param {string} [version]\n         * This is the version number of the feature to test.\n         * @returns {boolean}\n         * Always returns true.\n         * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/hasFeature MDN\n         * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core\n         * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard\n         * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-5CED94D7 DOM Level 3 Core\n         */\n        hasFeature: function(feature, version) {\n          return true;\n        },\n        /**\n         * Creates a DOM Document object of the specified type with its document element. Note that\n         * based on the {@link DocumentType}\n         * given to create the document, the implementation may instantiate specialized\n         * {@link Document} objects that support additional features than the "Core", such as "HTML"\n         * {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#DOM2HTML DOM Level 2 HTML}.\n         * On the other hand, setting the {@link DocumentType} after the document was created makes\n         * this very unlikely to happen. Alternatively, specialized {@link Document} creation methods,\n         * such as createHTMLDocument\n         * {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#DOM2HTML DOM Level 2 HTML},\n         * can be used to obtain specific types of {@link Document} objects.\n         *\n         * __It behaves slightly different from the description in the living standard__:\n         * - There is no interface/class `XMLDocument`, it returns a `Document`\n         * instance (with it\'s `type` set to `\'xml\'`).\n         * - `encoding`, `mode`, `origin`, `url` fields are currently not declared.\n         *\n         * @function DOMImplementation.createDocument\n         * @param {string | null} namespaceURI\n         * The\n         * {@link https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-namespaceURI namespace URI}\n         * of the document element to create or null.\n         * @param {string | null} qualifiedName\n         * The\n         * {@link https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-qualifiedname qualified name}\n         * of the document element to be created or null.\n         * @param {DocumentType | null} [doctype=null]\n         * The type of document to be created or null. When doctype is not null, its\n         * {@link Node#ownerDocument} attribute is set to the document being created. Default is\n         * `null`\n         * @returns {Document}\n         * A new {@link Document} object with its document element. If the NamespaceURI,\n         * qualifiedName, and doctype are null, the returned {@link Document} is empty with no\n         * document element.\n         * @throws {DOMException}\n         * With code:\n         *\n         * - `INVALID_CHARACTER_ERR`: Raised if the specified qualified name is not an XML name\n         * according to {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#XML XML 1.0}.\n         * - `NAMESPACE_ERR`: Raised if the qualifiedName is malformed, if the qualifiedName has a\n         * prefix and the namespaceURI is null, or if the qualifiedName is null and the namespaceURI\n         * is different from null, or if the qualifiedName has a prefix that is "xml" and the\n         * namespaceURI is different from "{@link http://www.w3.org/XML/1998/namespace}"\n         * {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#Namespaces XML Namespaces},\n         * or if the DOM implementation does not support the "XML" feature but a non-null namespace\n         * URI was provided, since namespaces were defined by XML.\n         * - `WRONG_DOCUMENT_ERR`: Raised if doctype has already been used with a different document\n         * or was created from a different implementation.\n         * - `NOT_SUPPORTED_ERR`: May be raised if the implementation does not support the feature\n         * "XML" and the language exposed through the Document does not support XML Namespaces (such\n         * as {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#HTML40 HTML 4.01}).\n         * @since DOM Level 2.\n         * @see {@link #createHTMLDocument}\n         * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN\n         * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Living Standard\n         * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Level-2-Core-DOM-createDocument DOM\n         *      Level 3 Core\n         * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM\n         *      Level 2 Core (initial)\n         */\n        createDocument: function(namespaceURI, qualifiedName, doctype) {\n          var contentType = MIME_TYPE.XML_APPLICATION;\n          if (namespaceURI === NAMESPACE.HTML) {\n            contentType = MIME_TYPE.XML_XHTML_APPLICATION;\n          } else if (namespaceURI === NAMESPACE.SVG) {\n            contentType = MIME_TYPE.XML_SVG_IMAGE;\n          }\n          var doc = new Document(PDC, { contentType });\n          doc.implementation = this;\n          doc.childNodes = new NodeList();\n          doc.doctype = doctype || null;\n          if (doctype) {\n            doc.appendChild(doctype);\n          }\n          if (qualifiedName) {\n            var root = doc.createElementNS(namespaceURI, qualifiedName);\n            doc.appendChild(root);\n          }\n          return doc;\n        },\n        /**\n         * Creates an empty DocumentType node. Entity declarations and notations are not made\n         * available. Entity reference expansions and default attribute additions do not occur.\n         *\n         * **This behavior is slightly different from the one in the specs**:\n         * - `encoding`, `mode`, `origin`, `url` fields are currently not declared.\n         * - `publicId` and `systemId` contain the raw data including any possible quotes,\n         *   so they can always be serialized back to the original value\n         * - `internalSubset` contains the raw string between `[` and `]` if present,\n         *   but is not parsed or validated in any form.\n         *\n         * @function DOMImplementation#createDocumentType\n         * @param {string} qualifiedName\n         * The {@link https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-qualifiedname qualified\n         * name} of the document type to be created.\n         * @param {string} [publicId]\n         * The external subset public identifier. Stored verbatim including surrounding quotes.\n         * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError`\n         * if the value is non-empty and does not match the XML `PubidLiteral` production\n         * (W3C DOM Parsing \xA73.2.1.3; XML 1.0 production [12]). Creation-time validation is not\n         * enforced \u2014 deferred to a future breaking release.\n         * @param {string} [systemId]\n         * The external subset system identifier. Stored verbatim including surrounding quotes.\n         * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError`\n         * if the value is non-empty and does not match the XML `SystemLiteral` production\n         * (W3C DOM Parsing \xA73.2.1.3; XML 1.0 production [11]). Creation-time validation is not\n         * enforced \u2014 deferred to a future breaking release.\n         * @param {string} [internalSubset]\n         * The internal subset or an empty string if it is not present. Stored verbatim.\n         * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError`\n         * if the value contains `"]>"`. Creation-time validation is not enforced.\n         * @returns {DocumentType}\n         * A new {@link DocumentType} node with {@link Node#ownerDocument} set to null.\n         * @throws {DOMException}\n         * With code:\n         *\n         * - `INVALID_CHARACTER_ERR`: Raised if the specified qualified name is not an XML name\n         * according to {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#XML XML 1.0}.\n         * - `NAMESPACE_ERR`: Raised if the qualifiedName is malformed.\n         * - `NOT_SUPPORTED_ERR`: May be raised if the implementation does not support the feature\n         * "XML" and the language exposed through the Document does not support XML Namespaces (such\n         * as {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#HTML40 HTML 4.01}).\n         * @since DOM Level 2.\n         * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType\n         *      MDN\n         * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype DOM Living\n         *      Standard\n         * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Level-3-Core-DOM-createDocType DOM\n         *      Level 3 Core\n         * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM\n         *      Level 2 Core\n         * @see https://github.com/xmldom/xmldom/blob/master/CHANGELOG.md#050\n         * @see https://www.w3.org/TR/DOM-Level-2-Core/#core-ID-Core-DocType-internalSubset\n         * @prettierignore\n         */\n        createDocumentType: function(qualifiedName, publicId, systemId, internalSubset) {\n          validateQualifiedName(qualifiedName);\n          var node = new DocumentType(PDC);\n          node.name = qualifiedName;\n          node.nodeName = qualifiedName;\n          node.publicId = publicId || "";\n          node.systemId = systemId || "";\n          node.internalSubset = internalSubset || "";\n          node.childNodes = new NodeList();\n          return node;\n        },\n        /**\n         * Returns an HTML document, that might already have a basic DOM structure.\n         *\n         * __It behaves slightly different from the description in the living standard__:\n         * - If the first argument is `false` no initial nodes are added (steps 3-7 in the specs are\n         * omitted)\n         * - `encoding`, `mode`, `origin`, `url` fields are currently not declared.\n         *\n         * @param {string | false} [title]\n         * A string containing the title to give the new HTML document.\n         * @returns {Document}\n         * The HTML document.\n         * @since WHATWG Living Standard.\n         * @see {@link #createDocument}\n         * @see https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument\n         * @see https://dom.spec.whatwg.org/#html-document\n         */\n        createHTMLDocument: function(title) {\n          var doc = new Document(PDC, { contentType: MIME_TYPE.HTML });\n          doc.implementation = this;\n          doc.childNodes = new NodeList();\n          if (title !== false) {\n            doc.doctype = this.createDocumentType("html");\n            doc.doctype.ownerDocument = doc;\n            doc.appendChild(doc.doctype);\n            var htmlNode = doc.createElement("html");\n            doc.appendChild(htmlNode);\n            var headNode = doc.createElement("head");\n            htmlNode.appendChild(headNode);\n            if (typeof title === "string") {\n              var titleNode = doc.createElement("title");\n              titleNode.appendChild(doc.createTextNode(title));\n              headNode.appendChild(titleNode);\n            }\n            htmlNode.appendChild(doc.createElement("body"));\n          }\n          return doc;\n        }\n      };\n      function Node(symbol) {\n        checkSymbol(symbol);\n      }\n      Node.prototype = {\n        /**\n         * The first child of this node.\n         *\n         * @type {Node | null}\n         */\n        firstChild: null,\n        /**\n         * The last child of this node.\n         *\n         * @type {Node | null}\n         */\n        lastChild: null,\n        /**\n         * The previous sibling of this node.\n         *\n         * @type {Node | null}\n         */\n        previousSibling: null,\n        /**\n         * The next sibling of this node.\n         *\n         * @type {Node | null}\n         */\n        nextSibling: null,\n        /**\n         * The parent node of this node.\n         *\n         * @type {Node | null}\n         */\n        parentNode: null,\n        /**\n         * The parent element of this node.\n         *\n         * @type {Element | null}\n         */\n        get parentElement() {\n          return this.parentNode && this.parentNode.nodeType === this.ELEMENT_NODE ? this.parentNode : null;\n        },\n        /**\n         * The child nodes of this node.\n         *\n         * @type {NodeList}\n         */\n        childNodes: null,\n        /**\n         * The document object associated with this node.\n         *\n         * @type {Document | null}\n         */\n        ownerDocument: null,\n        /**\n         * The value of this node.\n         *\n         * @type {string | null}\n         */\n        nodeValue: null,\n        /**\n         * The namespace URI of this node.\n         *\n         * @type {string | null}\n         */\n        namespaceURI: null,\n        /**\n         * The prefix of the namespace for this node.\n         *\n         * @type {string | null}\n         */\n        prefix: null,\n        /**\n         * The local part of the qualified name of this node.\n         *\n         * @type {string | null}\n         */\n        localName: null,\n        /**\n         * The baseURI is currently always `about:blank`,\n         * since that\'s what happens when you create a document from scratch.\n         *\n         * @type {\'about:blank\'}\n         */\n        baseURI: "about:blank",\n        /**\n         * Is true if this node is part of a document.\n         *\n         * @type {boolean}\n         */\n        get isConnected() {\n          var rootNode = this.getRootNode();\n          return rootNode && rootNode.nodeType === rootNode.DOCUMENT_NODE;\n        },\n        /**\n         * Checks whether `other` is an inclusive descendant of this node.\n         *\n         * @param {Node | null | undefined} other\n         * The node to check.\n         * @returns {boolean}\n         * True if `other` is an inclusive descendant of this node; false otherwise.\n         * @see https://dom.spec.whatwg.org/#dom-node-contains\n         */\n        contains: function(other) {\n          if (!other) return false;\n          var parent = other;\n          do {\n            if (this === parent) return true;\n            parent = parent.parentNode;\n          } while (parent);\n          return false;\n        },\n        /**\n         * @typedef GetRootNodeOptions\n         * @property {boolean} [composed=false]\n         */\n        /**\n         * Searches for the root node of this node.\n         *\n         * **This behavior is slightly different from the in the specs**:\n         * - ignores `options.composed`, since `ShadowRoot`s are unsupported, always returns root.\n         *\n         * @param {GetRootNodeOptions} [options]\n         * @returns {Node}\n         * Root node.\n         * @see https://dom.spec.whatwg.org/#dom-node-getrootnode\n         * @see https://dom.spec.whatwg.org/#concept-shadow-including-root\n         */\n        getRootNode: function(options) {\n          var parent = this;\n          do {\n            if (!parent.parentNode) {\n              return parent;\n            }\n            parent = parent.parentNode;\n          } while (parent);\n        },\n        /**\n         * Checks whether the given node is equal to this node.\n         *\n         * Two nodes are equal when they have the same type, defining characteristics (for the type),\n         * and the same childNodes. The comparison is iterative to avoid stack overflows on\n         * deeply-nested trees. Attribute nodes of each Element pair are also pushed onto the stack\n         * and compared the same way.\n         *\n         * @param {Node} [otherNode]\n         * @returns {boolean}\n         * @see https://dom.spec.whatwg.org/#concept-node-equals\n         * @see ../docs/walk-dom.md.\n         */\n        isEqualNode: function(otherNode) {\n          if (!otherNode) return false;\n          var stack = [{ node: this, other: otherNode }];\n          while (stack.length > 0) {\n            var pair = stack.pop();\n            var node = pair.node;\n            var other = pair.other;\n            if (node.nodeType !== other.nodeType) return false;\n            switch (node.nodeType) {\n              case node.DOCUMENT_TYPE_NODE:\n                if (node.name !== other.name) return false;\n                if (node.publicId !== other.publicId) return false;\n                if (node.systemId !== other.systemId) return false;\n                break;\n              case node.ELEMENT_NODE:\n                if (node.namespaceURI !== other.namespaceURI) return false;\n                if (node.prefix !== other.prefix) return false;\n                if (node.localName !== other.localName) return false;\n                if (node.attributes.length !== other.attributes.length) return false;\n                for (var i = 0; i < node.attributes.length; i++) {\n                  var attr = node.attributes.item(i);\n                  var otherAttr = other.getAttributeNodeNS(attr.namespaceURI, attr.localName);\n                  if (!otherAttr) return false;\n                  stack.push({ node: attr, other: otherAttr });\n                }\n                break;\n              case node.ATTRIBUTE_NODE:\n                if (node.namespaceURI !== other.namespaceURI) return false;\n                if (node.localName !== other.localName) return false;\n                if (node.value !== other.value) return false;\n                break;\n              case node.PROCESSING_INSTRUCTION_NODE:\n                if (node.target !== other.target || node.data !== other.data) return false;\n                break;\n              case node.TEXT_NODE:\n              case node.CDATA_SECTION_NODE:\n              case node.COMMENT_NODE:\n                if (node.data !== other.data) return false;\n                break;\n            }\n            if (node.childNodes.length !== other.childNodes.length) return false;\n            for (var i = node.childNodes.length - 1; i >= 0; i--) {\n              stack.push({ node: node.childNodes[i], other: other.childNodes[i] });\n            }\n          }\n          return true;\n        },\n        /**\n         * Checks whether or not the given node is this node.\n         *\n         * @param {Node} [otherNode]\n         */\n        isSameNode: function(otherNode) {\n          return this === otherNode;\n        },\n        /**\n         * Inserts a node before a reference node as a child of this node.\n         *\n         * @param {Node} newChild\n         * The new child node to be inserted.\n         * @param {Node | null} refChild\n         * The reference node before which newChild will be inserted.\n         * @returns {Node}\n         * The new child node successfully inserted.\n         * @throws {DOMException}\n         * Throws a DOMException if inserting the node would result in a DOM tree that is not\n         * well-formed, or if `child` is provided but is not a child of `parent`.\n         * See {@link _insertBefore} for more details.\n         * @since Modified in DOM L2\n         */\n        insertBefore: function(newChild, refChild) {\n          return _insertBefore(this, newChild, refChild);\n        },\n        /**\n         * Replaces an old child node with a new child node within this node.\n         *\n         * @param {Node} newChild\n         * The new node that is to replace the old node.\n         * If it already exists in the DOM, it is removed from its original position.\n         * @param {Node} oldChild\n         * The existing child node to be replaced.\n         * @returns {Node}\n         * Returns the replaced child node.\n         * @throws {DOMException}\n         * Throws a DOMException if replacing the node would result in a DOM tree that is not\n         * well-formed, or if `oldChild` is not a child of `this`.\n         * This can also occur if the pre-replacement validity assertion fails.\n         * See {@link _insertBefore}, {@link Node.removeChild}, and\n         * {@link assertPreReplacementValidityInDocument} for more details.\n         * @see https://dom.spec.whatwg.org/#concept-node-replace\n         */\n        replaceChild: function(newChild, oldChild) {\n          _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument);\n          if (oldChild) {\n            this.removeChild(oldChild);\n          }\n        },\n        /**\n         * Removes an existing child node from this node.\n         *\n         * @param {Node} oldChild\n         * The child node to be removed.\n         * @returns {Node}\n         * Returns the removed child node.\n         * @throws {DOMException}\n         * Throws a DOMException if `oldChild` is not a child of `this`.\n         * See {@link _removeChild} for more details.\n         */\n        removeChild: function(oldChild) {\n          return _removeChild(this, oldChild);\n        },\n        /**\n         * Appends a child node to this node.\n         *\n         * @param {Node} newChild\n         * The child node to be appended to this node.\n         * If it already exists in the DOM, it is removed from its original position.\n         * @returns {Node}\n         * Returns the appended child node.\n         * @throws {DOMException}\n         * Throws a DOMException if appending the node would result in a DOM tree that is not\n         * well-formed, or if `newChild` is not a valid Node.\n         * See {@link insertBefore} for more details.\n         */\n        appendChild: function(newChild) {\n          return this.insertBefore(newChild, null);\n        },\n        /**\n         * Determines whether this node has any child nodes.\n         *\n         * @returns {boolean}\n         * Returns true if this node has any child nodes, and false otherwise.\n         */\n        hasChildNodes: function() {\n          return this.firstChild != null;\n        },\n        /**\n         * Creates a copy of the calling node.\n         *\n         * @param {boolean} deep\n         * If true, the contents of the node are recursively copied.\n         * If false, only the node itself (and its attributes, if it is an element) are copied.\n         * @returns {Node}\n         * Returns the newly created copy of the node.\n         * @throws {DOMException}\n         * May throw a DOMException if operations within {@link Element#setAttributeNode} or\n         * {@link Node#appendChild} (which are potentially invoked in this method) do not meet their\n         * specific constraints.\n         * @see {@link cloneNode}\n         */\n        cloneNode: function(deep) {\n          return cloneNode(this.ownerDocument || this, this, deep);\n        },\n        /**\n         * Puts the specified node and all of its subtree into a "normalized" form. In a normalized\n         * subtree, no text nodes in the subtree are empty and there are no adjacent text nodes.\n         *\n         * Specifically, this method merges any adjacent text nodes (i.e., nodes for which `nodeType`\n         * is `TEXT_NODE`) into a single node with the combined data. It also removes any empty text\n         * nodes.\n         *\n         * This method iterativly traverses all child nodes to normalize all descendent nodes within\n         * the subtree.\n         *\n         * @throws {DOMException}\n         * May throw a DOMException if operations within removeChild or appendData (which are\n         * potentially invoked in this method) do not meet their specific constraints.\n         * @since Modified in DOM Level 2\n         * @see {@link Node.removeChild}\n         * @see {@link CharacterData.appendData}\n         * @see ../docs/walk-dom.md.\n         */\n        normalize: function() {\n          walkDOM(this, null, {\n            enter: function(node) {\n              var child = node.firstChild;\n              while (child) {\n                var next = child.nextSibling;\n                if (next !== null && next.nodeType === TEXT_NODE && child.nodeType === TEXT_NODE) {\n                  node.removeChild(next);\n                  child.appendData(next.data);\n                } else {\n                  child = next;\n                }\n              }\n              return true;\n            }\n          });\n        },\n        /**\n         * Checks whether the DOM implementation implements a specific feature and its version.\n         *\n         * @deprecated\n         * Since `DOMImplementation.hasFeature` is deprecated and always returns true.\n         * @param {string} feature\n         * The package name of the feature to test. This is the same name that can be passed to the\n         * method `hasFeature` on `DOMImplementation`.\n         * @param {string} version\n         * This is the version number of the package name to test.\n         * @returns {boolean}\n         * Returns true in all cases in the current implementation.\n         * @since Introduced in DOM Level 2\n         * @see {@link DOMImplementation.hasFeature}\n         */\n        isSupported: function(feature, version) {\n          return this.ownerDocument.implementation.hasFeature(feature, version);\n        },\n        /**\n         * Look up the prefix associated to the given namespace URI, starting from this node.\n         * **The default namespace declarations are ignored by this method.**\n         * See Namespace Prefix Lookup for details on the algorithm used by this method.\n         *\n         * **This behavior is different from the in the specs**:\n         * - no node type specific handling\n         * - uses the internal attribute _nsMap for resolving namespaces that is updated when changing attributes\n         *\n         * @param {string | null} namespaceURI\n         * The namespace URI for which to find the associated prefix.\n         * @returns {string | null}\n         * The associated prefix, if found; otherwise, null.\n         * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespacePrefix\n         * @see https://www.w3.org/TR/DOM-Level-3-Core/namespaces-algorithms.html#lookupNamespacePrefixAlgo\n         * @see https://dom.spec.whatwg.org/#dom-node-lookupprefix\n         * @see https://github.com/xmldom/xmldom/issues/322\n         * @prettierignore\n         */\n        lookupPrefix: function(namespaceURI) {\n          var el = this;\n          while (el) {\n            var map = el._nsMap;\n            if (map) {\n              for (var n in map) {\n                if (hasOwn(map, n) && map[n] === namespaceURI) {\n                  return n;\n                }\n              }\n            }\n            el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;\n          }\n          return null;\n        },\n        /**\n         * This function is used to look up the namespace URI associated with the given prefix,\n         * starting from this node.\n         *\n         * **This behavior is different from the in the specs**:\n         * - no node type specific handling\n         * - uses the internal attribute _nsMap for resolving namespaces that is updated when changing attributes\n         *\n         * @param {string | null} prefix\n         * The prefix for which to find the associated namespace URI.\n         * @returns {string | null}\n         * The associated namespace URI, if found; otherwise, null.\n         * @since DOM Level 3\n         * @see https://dom.spec.whatwg.org/#dom-node-lookupnamespaceuri\n         * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespaceURI\n         * @prettierignore\n         */\n        lookupNamespaceURI: function(prefix) {\n          var el = this;\n          while (el) {\n            var map = el._nsMap;\n            if (map) {\n              if (hasOwn(map, prefix)) {\n                return map[prefix];\n              }\n            }\n            el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;\n          }\n          return null;\n        },\n        /**\n         * Determines whether the given namespace URI is the default namespace.\n         *\n         * The function works by looking up the prefix associated with the given namespace URI. If no\n         * prefix is found (i.e., the namespace URI is not registered in the namespace map of this\n         * node or any of its ancestors), it returns `true`, implying the namespace URI is considered\n         * the default.\n         *\n         * **This behavior is different from the in the specs**:\n         * - no node type specific handling\n         * - uses the internal attribute _nsMap for resolving namespaces that is updated when changing attributes\n         *\n         * @param {string | null} namespaceURI\n         * The namespace URI to be checked.\n         * @returns {boolean}\n         * Returns true if the given namespace URI is the default namespace, false otherwise.\n         * @since DOM Level 3\n         * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-isDefaultNamespace\n         * @see https://dom.spec.whatwg.org/#dom-node-isdefaultnamespace\n         * @prettierignore\n         */\n        isDefaultNamespace: function(namespaceURI) {\n          var prefix = this.lookupPrefix(namespaceURI);\n          return prefix == null;\n        },\n        /**\n         * Compares the reference node with a node with regard to their position in the document and\n         * according to the document order.\n         *\n         * @param {Node} other\n         * The node to compare the reference node to.\n         * @returns {number}\n         * Returns how the node is positioned relatively to the reference node according to the\n         * bitmask. 0 if reference node and given node are the same.\n         * @since DOM Level 3\n         * @see https://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#Node3-compare\n         * @see https://dom.spec.whatwg.org/#dom-node-comparedocumentposition\n         */\n        compareDocumentPosition: function(other) {\n          if (this === other) return 0;\n          var node1 = other;\n          var node2 = this;\n          var attr1 = null;\n          var attr2 = null;\n          if (node1 instanceof Attr) {\n            attr1 = node1;\n            node1 = attr1.ownerElement;\n          }\n          if (node2 instanceof Attr) {\n            attr2 = node2;\n            node2 = attr2.ownerElement;\n            if (attr1 && node1 && node2 === node1) {\n              for (var i = 0, attr; attr = node2.attributes[i]; i++) {\n                if (attr === attr1)\n                  return DocumentPosition.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC + DocumentPosition.DOCUMENT_POSITION_PRECEDING;\n                if (attr === attr2)\n                  return DocumentPosition.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC + DocumentPosition.DOCUMENT_POSITION_FOLLOWING;\n              }\n            }\n          }\n          if (!node1 || !node2 || node2.ownerDocument !== node1.ownerDocument) {\n            return DocumentPosition.DOCUMENT_POSITION_DISCONNECTED + DocumentPosition.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC + (docGUID(node2.ownerDocument) > docGUID(node1.ownerDocument) ? DocumentPosition.DOCUMENT_POSITION_FOLLOWING : DocumentPosition.DOCUMENT_POSITION_PRECEDING);\n          }\n          if (attr2 && node1 === node2) {\n            return DocumentPosition.DOCUMENT_POSITION_CONTAINS + DocumentPosition.DOCUMENT_POSITION_PRECEDING;\n          }\n          if (attr1 && node1 === node2) {\n            return DocumentPosition.DOCUMENT_POSITION_CONTAINED_BY + DocumentPosition.DOCUMENT_POSITION_FOLLOWING;\n          }\n          var chain1 = [];\n          var ancestor1 = node1.parentNode;\n          while (ancestor1) {\n            if (!attr2 && ancestor1 === node2) {\n              return DocumentPosition.DOCUMENT_POSITION_CONTAINED_BY + DocumentPosition.DOCUMENT_POSITION_FOLLOWING;\n            }\n            chain1.push(ancestor1);\n            ancestor1 = ancestor1.parentNode;\n          }\n          chain1.reverse();\n          var chain2 = [];\n          var ancestor2 = node2.parentNode;\n          while (ancestor2) {\n            if (!attr1 && ancestor2 === node1) {\n              return DocumentPosition.DOCUMENT_POSITION_CONTAINS + DocumentPosition.DOCUMENT_POSITION_PRECEDING;\n            }\n            chain2.push(ancestor2);\n            ancestor2 = ancestor2.parentNode;\n          }\n          chain2.reverse();\n          var ca = commonAncestor(chain1, chain2);\n          for (var n in ca.childNodes) {\n            var child = ca.childNodes[n];\n            if (child === node2) return DocumentPosition.DOCUMENT_POSITION_FOLLOWING;\n            if (child === node1) return DocumentPosition.DOCUMENT_POSITION_PRECEDING;\n            if (chain2.indexOf(child) >= 0) return DocumentPosition.DOCUMENT_POSITION_FOLLOWING;\n            if (chain1.indexOf(child) >= 0) return DocumentPosition.DOCUMENT_POSITION_PRECEDING;\n          }\n          return 0;\n        }\n      };\n      function _xmlEncoder(c) {\n        return c == "<" && "&lt;" || c == ">" && "&gt;" || c == "&" && "&amp;" || c == \'"\' && "&quot;" || "&#" + c.charCodeAt() + ";";\n      }\n      copy(NodeType, Node);\n      copy(NodeType, Node.prototype);\n      copy(DocumentPosition, Node);\n      copy(DocumentPosition, Node.prototype);\n      function _visitNode(node, callback) {\n        walkDOM(node, null, {\n          enter: function(n) {\n            return callback(n) ? walkDOM.STOP : true;\n          }\n        });\n      }\n      function walkDOM(node, context, callbacks) {\n        var stack = [{ node, context, phase: walkDOM.ENTER }];\n        while (stack.length > 0) {\n          var frame = stack.pop();\n          if (frame.phase === walkDOM.ENTER) {\n            var childContext = callbacks.enter(frame.node, frame.context);\n            if (childContext === walkDOM.STOP) {\n              return walkDOM.STOP;\n            }\n            stack.push({ node: frame.node, context: childContext, phase: walkDOM.EXIT });\n            if (childContext === null || childContext === void 0) {\n              continue;\n            }\n            var child = frame.node.lastChild;\n            while (child) {\n              stack.push({ node: child, context: childContext, phase: walkDOM.ENTER });\n              child = child.previousSibling;\n            }\n          } else {\n            if (callbacks.exit) {\n              callbacks.exit(frame.node, frame.context);\n            }\n          }\n        }\n      }\n      walkDOM.STOP = /* @__PURE__ */ Symbol("walkDOM.STOP");\n      walkDOM.ENTER = 0;\n      walkDOM.EXIT = 1;\n      function Document(symbol, options) {\n        checkSymbol(symbol);\n        var opt = options || {};\n        this.ownerDocument = this;\n        this.contentType = opt.contentType || MIME_TYPE.XML_APPLICATION;\n        this.type = isHTMLMimeType(this.contentType) ? "html" : "xml";\n      }\n      function _onAddAttribute(doc, el, newAttr) {\n        doc && doc._inc++;\n        var ns = newAttr.namespaceURI;\n        if (ns === NAMESPACE.XMLNS) {\n          el._nsMap[newAttr.prefix ? newAttr.localName : ""] = newAttr.value;\n        }\n      }\n      function _onRemoveAttribute(doc, el, newAttr, remove) {\n        doc && doc._inc++;\n        var ns = newAttr.namespaceURI;\n        if (ns === NAMESPACE.XMLNS) {\n          delete el._nsMap[newAttr.prefix ? newAttr.localName : ""];\n        }\n      }\n      function _onUpdateChild(doc, parent, newChild) {\n        if (doc && doc._inc) {\n          doc._inc++;\n          var childNodes = parent.childNodes;\n          if (newChild && !newChild.nextSibling) {\n            childNodes[childNodes.length++] = newChild;\n          } else {\n            var child = parent.firstChild;\n            var i = 0;\n            while (child) {\n              childNodes[i++] = child;\n              child = child.nextSibling;\n            }\n            childNodes.length = i;\n            delete childNodes[childNodes.length];\n          }\n        }\n      }\n      function _removeChild(parentNode, child) {\n        if (parentNode !== child.parentNode) {\n          throw new DOMException(DOMException.NOT_FOUND_ERR, "child\'s parent is not parent");\n        }\n        var oldPreviousSibling = child.previousSibling;\n        var oldNextSibling = child.nextSibling;\n        if (oldPreviousSibling) {\n          oldPreviousSibling.nextSibling = oldNextSibling;\n        } else {\n          parentNode.firstChild = oldNextSibling;\n        }\n        if (oldNextSibling) {\n          oldNextSibling.previousSibling = oldPreviousSibling;\n        } else {\n          parentNode.lastChild = oldPreviousSibling;\n        }\n        _onUpdateChild(parentNode.ownerDocument, parentNode);\n        child.parentNode = null;\n        child.previousSibling = null;\n        child.nextSibling = null;\n        return child;\n      }\n      function hasValidParentNodeType(node) {\n        return node && (node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.ELEMENT_NODE);\n      }\n      function hasInsertableNodeType(node) {\n        return node && (node.nodeType === Node.CDATA_SECTION_NODE || node.nodeType === Node.COMMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.DOCUMENT_TYPE_NODE || node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.PROCESSING_INSTRUCTION_NODE || node.nodeType === Node.TEXT_NODE);\n      }\n      function isDocTypeNode(node) {\n        return node && node.nodeType === Node.DOCUMENT_TYPE_NODE;\n      }\n      function isElementNode(node) {\n        return node && node.nodeType === Node.ELEMENT_NODE;\n      }\n      function isTextNode(node) {\n        return node && node.nodeType === Node.TEXT_NODE;\n      }\n      function isElementInsertionPossible(doc, child) {\n        var parentChildNodes = doc.childNodes || [];\n        if (find(parentChildNodes, isElementNode) || isDocTypeNode(child)) {\n          return false;\n        }\n        var docTypeNode = find(parentChildNodes, isDocTypeNode);\n        return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child));\n      }\n      function isElementReplacementPossible(doc, child) {\n        var parentChildNodes = doc.childNodes || [];\n        function hasElementChildThatIsNotChild(node) {\n          return isElementNode(node) && node !== child;\n        }\n        if (find(parentChildNodes, hasElementChildThatIsNotChild)) {\n          return false;\n        }\n        var docTypeNode = find(parentChildNodes, isDocTypeNode);\n        return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child));\n      }\n      function assertPreInsertionValidity1to5(parent, node, child) {\n        if (!hasValidParentNodeType(parent)) {\n          throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Unexpected parent node type " + parent.nodeType);\n        }\n        if (child && child.parentNode !== parent) {\n          throw new DOMException(DOMException.NOT_FOUND_ERR, "child not in parent");\n        }\n        if (\n          // 4. If `node` is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException.\n          !hasInsertableNodeType(node) || // 5. If either `node` is a Text node and `parent` is a document,\n          // the sax parser currently adds top level text nodes, this will be fixed in 0.9.0\n          // || (node.nodeType === Node.TEXT_NODE && parent.nodeType === Node.DOCUMENT_NODE)\n          // or `node` is a doctype and `parent` is not a document, then throw a "HierarchyRequestError" DOMException.\n          isDocTypeNode(node) && parent.nodeType !== Node.DOCUMENT_NODE\n        ) {\n          throw new DOMException(\n            DOMException.HIERARCHY_REQUEST_ERR,\n            "Unexpected node type " + node.nodeType + " for parent node type " + parent.nodeType\n          );\n        }\n      }\n      function assertPreInsertionValidityInDocument(parent, node, child) {\n        var parentChildNodes = parent.childNodes || [];\n        var nodeChildNodes = node.childNodes || [];\n        if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {\n          var nodeChildElements = nodeChildNodes.filter(isElementNode);\n          if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) {\n            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "More than one element or text in fragment");\n          }\n          if (nodeChildElements.length === 1 && !isElementInsertionPossible(parent, child)) {\n            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Element in fragment can not be inserted before doctype");\n          }\n        }\n        if (isElementNode(node)) {\n          if (!isElementInsertionPossible(parent, child)) {\n            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Only one element can be added and only after doctype");\n          }\n        }\n        if (isDocTypeNode(node)) {\n          if (find(parentChildNodes, isDocTypeNode)) {\n            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Only one doctype is allowed");\n          }\n          var parentElementChild = find(parentChildNodes, isElementNode);\n          if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) {\n            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Doctype can only be inserted before an element");\n          }\n          if (!child && parentElementChild) {\n            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Doctype can not be appended since element is present");\n          }\n        }\n      }\n      function assertPreReplacementValidityInDocument(parent, node, child) {\n        var parentChildNodes = parent.childNodes || [];\n        var nodeChildNodes = node.childNodes || [];\n        if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {\n          var nodeChildElements = nodeChildNodes.filter(isElementNode);\n          if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) {\n            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "More than one element or text in fragment");\n          }\n          if (nodeChildElements.length === 1 && !isElementReplacementPossible(parent, child)) {\n            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Element in fragment can not be inserted before doctype");\n          }\n        }\n        if (isElementNode(node)) {\n          if (!isElementReplacementPossible(parent, child)) {\n            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Only one element can be added and only after doctype");\n          }\n        }\n        if (isDocTypeNode(node)) {\n          let hasDoctypeChildThatIsNotChild = function(node2) {\n            return isDocTypeNode(node2) && node2 !== child;\n          };\n          if (find(parentChildNodes, hasDoctypeChildThatIsNotChild)) {\n            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Only one doctype is allowed");\n          }\n          var parentElementChild = find(parentChildNodes, isElementNode);\n          if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) {\n            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Doctype can only be inserted before an element");\n          }\n        }\n      }\n      function _insertBefore(parent, node, child, _inDocumentAssertion) {\n        assertPreInsertionValidity1to5(parent, node, child);\n        if (parent.nodeType === Node.DOCUMENT_NODE) {\n          (_inDocumentAssertion || assertPreInsertionValidityInDocument)(parent, node, child);\n        }\n        var cp = node.parentNode;\n        if (cp) {\n          cp.removeChild(node);\n        }\n        if (node.nodeType === DOCUMENT_FRAGMENT_NODE) {\n          var newFirst = node.firstChild;\n          if (newFirst == null) {\n            return node;\n          }\n          var newLast = node.lastChild;\n        } else {\n          newFirst = newLast = node;\n        }\n        var pre = child ? child.previousSibling : parent.lastChild;\n        newFirst.previousSibling = pre;\n        newLast.nextSibling = child;\n        if (pre) {\n          pre.nextSibling = newFirst;\n        } else {\n          parent.firstChild = newFirst;\n        }\n        if (child == null) {\n          parent.lastChild = newLast;\n        } else {\n          child.previousSibling = newLast;\n        }\n        do {\n          newFirst.parentNode = parent;\n        } while (newFirst !== newLast && (newFirst = newFirst.nextSibling));\n        _onUpdateChild(parent.ownerDocument || parent, parent, node);\n        if (node.nodeType == DOCUMENT_FRAGMENT_NODE) {\n          node.firstChild = node.lastChild = null;\n        }\n        return node;\n      }\n      Document.prototype = {\n        /**\n         * The implementation that created this document.\n         *\n         * @type DOMImplementation\n         * @readonly\n         */\n        implementation: null,\n        nodeName: "#document",\n        nodeType: DOCUMENT_NODE,\n        /**\n         * The DocumentType node of the document.\n         *\n         * @type DocumentType\n         * @readonly\n         */\n        doctype: null,\n        documentElement: null,\n        _inc: 1,\n        insertBefore: function(newChild, refChild) {\n          if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) {\n            var child = newChild.firstChild;\n            while (child) {\n              var next = child.nextSibling;\n              this.insertBefore(child, refChild);\n              child = next;\n            }\n            return newChild;\n          }\n          _insertBefore(this, newChild, refChild);\n          newChild.ownerDocument = this;\n          if (this.documentElement === null && newChild.nodeType === ELEMENT_NODE) {\n            this.documentElement = newChild;\n          }\n          return newChild;\n        },\n        removeChild: function(oldChild) {\n          var removed = _removeChild(this, oldChild);\n          if (removed === this.documentElement) {\n            this.documentElement = null;\n          }\n          return removed;\n        },\n        replaceChild: function(newChild, oldChild) {\n          _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument);\n          newChild.ownerDocument = this;\n          if (oldChild) {\n            this.removeChild(oldChild);\n          }\n          if (isElementNode(newChild)) {\n            this.documentElement = newChild;\n          }\n        },\n        /**\n         * Imports a node from another document into this document, creating a new copy owned by this\n         * document. The source node and its subtree are not modified.\n         *\n         * @param {Node} importedNode\n         * The node to import.\n         * @param {boolean} deep\n         * If true, the contents of the node are recursively imported.\n         * If false, only the node itself (and its attributes, if it is an element) are imported.\n         * @returns {Node}\n         * Returns the newly created import of the node.\n         * @see {@link importNode}\n         * @see {@link https://dom.spec.whatwg.org/#dom-document-importnode}\n         */\n        importNode: function(importedNode, deep) {\n          return importNode(this, importedNode, deep);\n        },\n        // Introduced in DOM Level 2:\n        getElementById: function(id) {\n          var rtv = null;\n          _visitNode(this.documentElement, function(node) {\n            if (node.nodeType == ELEMENT_NODE) {\n              if (node.getAttribute("id") == id) {\n                rtv = node;\n                return true;\n              }\n            }\n          });\n          return rtv;\n        },\n        /**\n         * Creates a new `Element` that is owned by this `Document`.\n         * In HTML Documents `localName` is the lower cased `tagName`,\n         * otherwise no transformation is being applied.\n         * When `contentType` implies the HTML namespace, it will be set as `namespaceURI`.\n         *\n         * __This implementation differs from the specification:__ - The provided name is not checked\n         * against the `Name` production,\n         * so no related error will be thrown.\n         * - There is no interface `HTMLElement`, it is always an `Element`.\n         * - There is no support for a second argument to indicate using custom elements.\n         *\n         * @param {string} tagName\n         * @returns {Element}\n         * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement\n         * @see https://dom.spec.whatwg.org/#dom-document-createelement\n         * @see https://dom.spec.whatwg.org/#concept-create-element\n         */\n        createElement: function(tagName) {\n          var node = new Element(PDC);\n          node.ownerDocument = this;\n          if (this.type === "html") {\n            tagName = tagName.toLowerCase();\n          }\n          if (hasDefaultHTMLNamespace(this.contentType)) {\n            node.namespaceURI = NAMESPACE.HTML;\n          }\n          node.nodeName = tagName;\n          node.tagName = tagName;\n          node.localName = tagName;\n          node.childNodes = new NodeList();\n          var attrs = node.attributes = new NamedNodeMap();\n          attrs._ownerElement = node;\n          return node;\n        },\n        /**\n         * @returns {DocumentFragment}\n         */\n        createDocumentFragment: function() {\n          var node = new DocumentFragment(PDC);\n          node.ownerDocument = this;\n          node.childNodes = new NodeList();\n          return node;\n        },\n        /**\n         * @param {string} data\n         * @returns {Text}\n         */\n        createTextNode: function(data) {\n          var node = new Text(PDC);\n          node.ownerDocument = this;\n          node.childNodes = new NodeList();\n          node.appendData(data);\n          return node;\n        },\n        /**\n         * @param {string} data\n         * @returns {Comment}\n         * @see https://dom.spec.whatwg.org/#dom-document-createcomment\n         * @see https://www.w3.org/TR/xml/#NT-Comment XML 1.0 production [15]\n         * @see https://www.w3.org/TR/DOM-Parsing/#dfn-concept-serialize-xml \xA73.2.1.3\n         *\n         *      Note: no validation is performed at creation time. When the resulting document is\n         *      serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError`\n         *      if the comment data contains `--` anywhere, ends with `-`, or contains characters\n         *      outside the XML Char production (W3C DOM Parsing \xA73.2.1.3). Without that option the\n         *      data is emitted verbatim.\n         */\n        createComment: function(data) {\n          var node = new Comment(PDC);\n          node.ownerDocument = this;\n          node.childNodes = new NodeList();\n          node.appendData(data);\n          return node;\n        },\n        /**\n         * Returns a new CDATASection node whose data is `data`.\n         *\n         * __This implementation differs from the specification:__ - calling this method on an HTML\n         * document does not throw `NotSupportedError`.\n         *\n         * @param {string} data\n         * @returns {CDATASection}\n         * @throws {DOMException}\n         * With code `INVALID_CHARACTER_ERR` if `data` contains `"]]>"`.\n         * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/createCDATASection\n         * @see https://dom.spec.whatwg.org/#dom-document-createcdatasection\n         */\n        createCDATASection: function(data) {\n          if (data.indexOf("]]>") !== -1) {\n            throw new DOMException(DOMException.INVALID_CHARACTER_ERR, \'data contains "]]>"\');\n          }\n          var node = new CDATASection(PDC);\n          node.ownerDocument = this;\n          node.childNodes = new NodeList();\n          node.appendData(data);\n          return node;\n        },\n        /**\n         * Returns a ProcessingInstruction node whose target is target and data is data.\n         *\n         * __This behavior is slightly different from the in the specs__:\n         * - it does not do any input validation on the arguments and doesn\'t throw\n         * "InvalidCharacterError".\n         *\n         * Note: When the resulting document is serialized with `requireWellFormed: true`, the\n         * serializer throws `InvalidStateError` if `.target` contains `:` or is an ASCII\n         * case-insensitive match for `"xml"`, or if `.data` contains `?>` or characters outside the\n         * XML Char production (W3C DOM Parsing \xA73.2.1.7). Without that option the data is emitted\n         * verbatim.\n         *\n         * @param {string} target\n         * @param {string} data\n         * @returns {ProcessingInstruction}\n         * @see https://developer.mozilla.org/docs/Web/API/Document/createProcessingInstruction\n         * @see https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction\n         * @see https://www.w3.org/TR/DOM-Parsing/#dfn-concept-serialize-xml \xA73.2.1.7\n         */\n        createProcessingInstruction: function(target, data) {\n          var node = new ProcessingInstruction(PDC);\n          node.ownerDocument = this;\n          node.childNodes = new NodeList();\n          node.nodeName = node.target = target;\n          node.nodeValue = node.data = data;\n          return node;\n        },\n        /**\n         * Creates an `Attr` node that is owned by this document.\n         * In HTML Documents `localName` is the lower cased `name`,\n         * otherwise no transformation is being applied.\n         *\n         * __This implementation differs from the specification:__ - The provided name is not checked\n         * against the `Name` production,\n         * so no related error will be thrown.\n         *\n         * @param {string} name\n         * @returns {Attr}\n         * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/createAttribute\n         * @see https://dom.spec.whatwg.org/#dom-document-createattribute\n         */\n        createAttribute: function(name2) {\n          if (!g.QName_exact.test(name2)) {\n            throw new DOMException(DOMException.INVALID_CHARACTER_ERR, \'invalid character in name "\' + name2 + \'"\');\n          }\n          if (this.type === "html") {\n            name2 = name2.toLowerCase();\n          }\n          return this._createAttribute(name2);\n        },\n        _createAttribute: function(name2) {\n          var node = new Attr(PDC);\n          node.ownerDocument = this;\n          node.childNodes = new NodeList();\n          node.name = name2;\n          node.nodeName = name2;\n          node.localName = name2;\n          node.specified = true;\n          return node;\n        },\n        /**\n         * Creates an EntityReference object.\n         * The current implementation does not fill the `childNodes` with those of the corresponding\n         * `Entity`\n         *\n         * @deprecated\n         * In DOM Level 4.\n         * @param {string} name\n         * The name of the entity to reference. No namespace well-formedness checks are performed.\n         * @returns {EntityReference}\n         * @throws {DOMException}\n         * With code `INVALID_CHARACTER_ERR` when `name` is not valid.\n         * @throws {DOMException}\n         * with code `NOT_SUPPORTED_ERR` when the document is of type `html`\n         * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-392B75AE\n         */\n        createEntityReference: function(name2) {\n          if (!g.Name.test(name2)) {\n            throw new DOMException(DOMException.INVALID_CHARACTER_ERR, \'not a valid xml name "\' + name2 + \'"\');\n          }\n          if (this.type === "html") {\n            throw new DOMException("document is an html document", DOMExceptionName.NotSupportedError);\n          }\n          var node = new EntityReference(PDC);\n          node.ownerDocument = this;\n          node.childNodes = new NodeList();\n          node.nodeName = name2;\n          return node;\n        },\n        // Introduced in DOM Level 2:\n        /**\n         * @param {string} namespaceURI\n         * @param {string} qualifiedName\n         * @returns {Element}\n         */\n        createElementNS: function(namespaceURI, qualifiedName) {\n          var validated = validateAndExtract(namespaceURI, qualifiedName);\n          var node = new Element(PDC);\n          var attrs = node.attributes = new NamedNodeMap();\n          node.childNodes = new NodeList();\n          node.ownerDocument = this;\n          node.nodeName = qualifiedName;\n          node.tagName = qualifiedName;\n          node.namespaceURI = validated[0];\n          node.prefix = validated[1];\n          node.localName = validated[2];\n          attrs._ownerElement = node;\n          return node;\n        },\n        // Introduced in DOM Level 2:\n        /**\n         * @param {string} namespaceURI\n         * @param {string} qualifiedName\n         * @returns {Attr}\n         */\n        createAttributeNS: function(namespaceURI, qualifiedName) {\n          var validated = validateAndExtract(namespaceURI, qualifiedName);\n          var node = new Attr(PDC);\n          node.ownerDocument = this;\n          node.childNodes = new NodeList();\n          node.nodeName = qualifiedName;\n          node.name = qualifiedName;\n          node.specified = true;\n          node.namespaceURI = validated[0];\n          node.prefix = validated[1];\n          node.localName = validated[2];\n          return node;\n        }\n      };\n      _extends(Document, Node);\n      function Element(symbol) {\n        checkSymbol(symbol);\n        this._nsMap = /* @__PURE__ */ Object.create(null);\n      }\n      Element.prototype = {\n        nodeType: ELEMENT_NODE,\n        /**\n         * The attributes of this element.\n         *\n         * @type {NamedNodeMap | null}\n         */\n        attributes: null,\n        getQualifiedName: function() {\n          return this.prefix ? this.prefix + ":" + this.localName : this.localName;\n        },\n        _isInHTMLDocumentAndNamespace: function() {\n          return this.ownerDocument.type === "html" && this.namespaceURI === NAMESPACE.HTML;\n        },\n        /**\n         * Implementaton of Level2 Core function hasAttributes.\n         *\n         * @returns {boolean}\n         * True if attribute list is not empty.\n         * @see https://www.w3.org/TR/DOM-Level-2-Core/#core-ID-NodeHasAttrs\n         */\n        hasAttributes: function() {\n          return !!(this.attributes && this.attributes.length);\n        },\n        hasAttribute: function(name2) {\n          return !!this.getAttributeNode(name2);\n        },\n        /**\n         * Returns element\u2019s first attribute whose qualified name is `name`, and `null`\n         * if there is no such attribute.\n         *\n         * @param {string} name\n         * @returns {string | null}\n         */\n        getAttribute: function(name2) {\n          var attr = this.getAttributeNode(name2);\n          return attr ? attr.value : null;\n        },\n        getAttributeNode: function(name2) {\n          if (this._isInHTMLDocumentAndNamespace()) {\n            name2 = name2.toLowerCase();\n          }\n          return this.attributes.getNamedItem(name2);\n        },\n        /**\n         * Sets the value of element\u2019s first attribute whose qualified name is qualifiedName to value.\n         *\n         * @param {string} name\n         * @param {string} value\n         */\n        setAttribute: function(name2, value) {\n          if (this._isInHTMLDocumentAndNamespace()) {\n            name2 = name2.toLowerCase();\n          }\n          var attr = this.getAttributeNode(name2);\n          if (attr) {\n            attr.value = attr.nodeValue = "" + value;\n          } else {\n            attr = this.ownerDocument._createAttribute(name2);\n            attr.value = attr.nodeValue = "" + value;\n            this.setAttributeNode(attr);\n          }\n        },\n        removeAttribute: function(name2) {\n          var attr = this.getAttributeNode(name2);\n          attr && this.removeAttributeNode(attr);\n        },\n        setAttributeNode: function(newAttr) {\n          return this.attributes.setNamedItem(newAttr);\n        },\n        setAttributeNodeNS: function(newAttr) {\n          return this.attributes.setNamedItemNS(newAttr);\n        },\n        removeAttributeNode: function(oldAttr) {\n          return this.attributes.removeNamedItem(oldAttr.nodeName);\n        },\n        //get real attribute name,and remove it by removeAttributeNode\n        removeAttributeNS: function(namespaceURI, localName) {\n          var old = this.getAttributeNodeNS(namespaceURI, localName);\n          old && this.removeAttributeNode(old);\n        },\n        hasAttributeNS: function(namespaceURI, localName) {\n          return this.getAttributeNodeNS(namespaceURI, localName) != null;\n        },\n        /**\n         * Returns element\u2019s attribute whose namespace is `namespaceURI` and local name is\n         * `localName`,\n         * or `null` if there is no such attribute.\n         *\n         * @param {string} namespaceURI\n         * @param {string} localName\n         * @returns {string | null}\n         */\n        getAttributeNS: function(namespaceURI, localName) {\n          var attr = this.getAttributeNodeNS(namespaceURI, localName);\n          return attr ? attr.value : null;\n        },\n        /**\n         * Sets the value of element\u2019s attribute whose namespace is `namespaceURI` and local name is\n         * `localName` to value.\n         *\n         * @param {string} namespaceURI\n         * @param {string} qualifiedName\n         * @param {string} value\n         * @see https://dom.spec.whatwg.org/#dom-element-setattributens\n         */\n        setAttributeNS: function(namespaceURI, qualifiedName, value) {\n          var validated = validateAndExtract(namespaceURI, qualifiedName);\n          var localName = validated[2];\n          var attr = this.getAttributeNodeNS(namespaceURI, localName);\n          if (attr) {\n            attr.value = attr.nodeValue = "" + value;\n          } else {\n            attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);\n            attr.value = attr.nodeValue = "" + value;\n            this.setAttributeNode(attr);\n          }\n        },\n        getAttributeNodeNS: function(namespaceURI, localName) {\n          return this.attributes.getNamedItemNS(namespaceURI, localName);\n        },\n        /**\n         * Returns a LiveNodeList of all child elements which have **all** of the given class name(s).\n         *\n         * Returns an empty list if `classNames` is an empty string or only contains HTML white space\n         * characters.\n         *\n         * Warning: This returns a live LiveNodeList.\n         * Changes in the DOM will reflect in the array as the changes occur.\n         * If an element selected by this array no longer qualifies for the selector,\n         * it will automatically be removed. Be aware of this for iteration purposes.\n         *\n         * @param {string} classNames\n         * Is a string representing the class name(s) to match; multiple class names are separated by\n         * (ASCII-)whitespace.\n         * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName\n         * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName\n         * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname\n         */\n        getElementsByClassName: function(classNames) {\n          var classNamesSet = toOrderedSet(classNames);\n          return new LiveNodeList(this, function(base) {\n            var ls = [];\n            if (classNamesSet.length > 0) {\n              _visitNode(base, function(node) {\n                if (node !== base && node.nodeType === ELEMENT_NODE) {\n                  var nodeClassNames = node.getAttribute("class");\n                  if (nodeClassNames) {\n                    var matches = classNames === nodeClassNames;\n                    if (!matches) {\n                      var nodeClassNamesSet = toOrderedSet(nodeClassNames);\n                      matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet));\n                    }\n                    if (matches) {\n                      ls.push(node);\n                    }\n                  }\n                }\n              });\n            }\n            return ls;\n          });\n        },\n        /**\n         * Returns a LiveNodeList of elements with the given qualifiedName.\n         * Searching for all descendants can be done by passing `*` as `qualifiedName`.\n         *\n         * All descendants of the specified element are searched, but not the element itself.\n         * The returned list is live, which means it updates itself with the DOM tree automatically.\n         * Therefore, there is no need to call `Element.getElementsByTagName()`\n         * with the same element and arguments repeatedly if the DOM changes in between calls.\n         *\n         * When called on an HTML element in an HTML document,\n         * `getElementsByTagName` lower-cases the argument before searching for it.\n         * This is undesirable when trying to match camel-cased SVG elements (such as\n         * `<linearGradient>`) in an HTML document.\n         * Instead, use `Element.getElementsByTagNameNS()`,\n         * which preserves the capitalization of the tag name.\n         *\n         * `Element.getElementsByTagName` is similar to `Document.getElementsByTagName()`,\n         * except that it only searches for elements that are descendants of the specified element.\n         *\n         * @param {string} qualifiedName\n         * @returns {LiveNodeList}\n         * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName\n         * @see https://dom.spec.whatwg.org/#concept-getelementsbytagname\n         */\n        getElementsByTagName: function(qualifiedName) {\n          var isHTMLDocument = (this.nodeType === DOCUMENT_NODE ? this : this.ownerDocument).type === "html";\n          var lowerQualifiedName = qualifiedName.toLowerCase();\n          return new LiveNodeList(this, function(base) {\n            var ls = [];\n            _visitNode(base, function(node) {\n              if (node === base || node.nodeType !== ELEMENT_NODE) {\n                return;\n              }\n              if (qualifiedName === "*") {\n                ls.push(node);\n              } else {\n                var nodeQualifiedName = node.getQualifiedName();\n                var matchingQName = isHTMLDocument && node.namespaceURI === NAMESPACE.HTML ? lowerQualifiedName : qualifiedName;\n                if (nodeQualifiedName === matchingQName) {\n                  ls.push(node);\n                }\n              }\n            });\n            return ls;\n          });\n        },\n        getElementsByTagNameNS: function(namespaceURI, localName) {\n          return new LiveNodeList(this, function(base) {\n            var ls = [];\n            _visitNode(base, function(node) {\n              if (node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === "*" || node.namespaceURI === namespaceURI) && (localName === "*" || node.localName == localName)) {\n                ls.push(node);\n              }\n            });\n            return ls;\n          });\n        }\n      };\n      Document.prototype.getElementsByClassName = Element.prototype.getElementsByClassName;\n      Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;\n      Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;\n      _extends(Element, Node);\n      function Attr(symbol) {\n        checkSymbol(symbol);\n        this.namespaceURI = null;\n        this.prefix = null;\n        this.ownerElement = null;\n      }\n      Attr.prototype.nodeType = ATTRIBUTE_NODE;\n      _extends(Attr, Node);\n      function CharacterData(symbol) {\n        checkSymbol(symbol);\n      }\n      CharacterData.prototype = {\n        data: "",\n        substringData: function(offset, count) {\n          return this.data.substring(offset, offset + count);\n        },\n        appendData: function(text) {\n          text = this.data + text;\n          this.nodeValue = this.data = text;\n          this.length = text.length;\n        },\n        insertData: function(offset, text) {\n          this.replaceData(offset, 0, text);\n        },\n        deleteData: function(offset, count) {\n          this.replaceData(offset, count, "");\n        },\n        replaceData: function(offset, count, text) {\n          var start = this.data.substring(0, offset);\n          var end = this.data.substring(offset + count);\n          text = start + text + end;\n          this.nodeValue = this.data = text;\n          this.length = text.length;\n        }\n      };\n      _extends(CharacterData, Node);\n      function Text(symbol) {\n        checkSymbol(symbol);\n      }\n      Text.prototype = {\n        nodeName: "#text",\n        nodeType: TEXT_NODE,\n        splitText: function(offset) {\n          var text = this.data;\n          var newText = text.substring(offset);\n          text = text.substring(0, offset);\n          this.data = this.nodeValue = text;\n          this.length = text.length;\n          var newNode = this.ownerDocument.createTextNode(newText);\n          if (this.parentNode) {\n            this.parentNode.insertBefore(newNode, this.nextSibling);\n          }\n          return newNode;\n        }\n      };\n      _extends(Text, CharacterData);\n      function Comment(symbol) {\n        checkSymbol(symbol);\n      }\n      Comment.prototype = {\n        nodeName: "#comment",\n        nodeType: COMMENT_NODE\n      };\n      _extends(Comment, CharacterData);\n      function CDATASection(symbol) {\n        checkSymbol(symbol);\n      }\n      CDATASection.prototype = {\n        nodeName: "#cdata-section",\n        nodeType: CDATA_SECTION_NODE\n      };\n      _extends(CDATASection, Text);\n      function DocumentType(symbol) {\n        checkSymbol(symbol);\n      }\n      DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;\n      _extends(DocumentType, Node);\n      function Notation(symbol) {\n        checkSymbol(symbol);\n      }\n      Notation.prototype.nodeType = NOTATION_NODE;\n      _extends(Notation, Node);\n      function Entity(symbol) {\n        checkSymbol(symbol);\n      }\n      Entity.prototype.nodeType = ENTITY_NODE;\n      _extends(Entity, Node);\n      function EntityReference(symbol) {\n        checkSymbol(symbol);\n      }\n      EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;\n      _extends(EntityReference, Node);\n      function DocumentFragment(symbol) {\n        checkSymbol(symbol);\n      }\n      DocumentFragment.prototype.nodeName = "#document-fragment";\n      DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;\n      _extends(DocumentFragment, Node);\n      function ProcessingInstruction(symbol) {\n        checkSymbol(symbol);\n      }\n      ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;\n      _extends(ProcessingInstruction, CharacterData);\n      function XMLSerializer2() {\n      }\n      XMLSerializer2.prototype.serializeToString = function(node, options) {\n        return nodeSerializeToString.call(node, options);\n      };\n      Node.prototype.toString = nodeSerializeToString;\n      function nodeSerializeToString(options) {\n        var opts;\n        if (typeof options === "function") {\n          opts = { requireWellFormed: false, splitCDATASections: true, nodeFilter: options };\n        } else if (options != null) {\n          opts = {\n            requireWellFormed: !!options.requireWellFormed,\n            splitCDATASections: options.splitCDATASections !== false,\n            nodeFilter: options.nodeFilter || null\n          };\n        } else {\n          opts = { requireWellFormed: false, splitCDATASections: true, nodeFilter: null };\n        }\n        var buf = [];\n        var refNode = this.nodeType === DOCUMENT_NODE && this.documentElement || this;\n        var prefix = refNode.prefix;\n        var uri = refNode.namespaceURI;\n        if (uri && prefix == null) {\n          var prefix = refNode.lookupPrefix(uri);\n          if (prefix == null) {\n            var visibleNamespaces = [\n              { namespace: uri, prefix: null }\n              //{namespace:uri,prefix:\'\'}\n            ];\n          }\n        }\n        serializeToString(this, buf, visibleNamespaces, opts);\n        return buf.join("");\n      }\n      function needNamespaceDefine(node, isHTML, visibleNamespaces) {\n        var prefix = node.prefix || "";\n        var uri = node.namespaceURI;\n        if (!uri) {\n          return false;\n        }\n        if (prefix === "xml" && uri === NAMESPACE.XML || uri === NAMESPACE.XMLNS) {\n          return false;\n        }\n        var i = visibleNamespaces.length;\n        while (i--) {\n          var ns = visibleNamespaces[i];\n          if (ns.prefix === prefix) {\n            return ns.namespace !== uri;\n          }\n        }\n        return true;\n      }\n      function addSerializedAttribute(buf, qualifiedName, value) {\n        buf.push(" ", qualifiedName, \'="\', value.replace(/[<>&"\\t\\n\\r]/g, _xmlEncoder), \'"\');\n      }\n      function serializeToString(node, buf, visibleNamespaces, opts) {\n        if (!visibleNamespaces) {\n          visibleNamespaces = [];\n        }\n        var nodeFilter = opts.nodeFilter;\n        var requireWellFormed = opts.requireWellFormed;\n        var splitCDATASections = opts.splitCDATASections;\n        var doc = node.nodeType === DOCUMENT_NODE ? node : node.ownerDocument;\n        var isHTML = doc.type === "html";\n        walkDOM(\n          node,\n          { ns: visibleNamespaces },\n          {\n            enter: function(n, ctx) {\n              var namespaces = ctx.ns;\n              if (nodeFilter) {\n                n = nodeFilter(n);\n                if (n) {\n                  if (typeof n == "string") {\n                    buf.push(n);\n                    return null;\n                  }\n                } else {\n                  return null;\n                }\n              }\n              switch (n.nodeType) {\n                case ELEMENT_NODE:\n                  var attrs = n.attributes;\n                  var len = attrs.length;\n                  var nodeName = n.tagName;\n                  var prefixedNodeName = nodeName;\n                  if (!isHTML && !n.prefix && n.namespaceURI) {\n                    var defaultNS;\n                    for (var ai = 0; ai < attrs.length; ai++) {\n                      if (attrs.item(ai).name === "xmlns") {\n                        defaultNS = attrs.item(ai).value;\n                        break;\n                      }\n                    }\n                    if (!defaultNS) {\n                      for (var nsi = namespaces.length - 1; nsi >= 0; nsi--) {\n                        var nsEntry = namespaces[nsi];\n                        if (nsEntry.prefix === "" && nsEntry.namespace === n.namespaceURI) {\n                          defaultNS = nsEntry.namespace;\n                          break;\n                        }\n                      }\n                    }\n                    if (defaultNS !== n.namespaceURI) {\n                      for (var nsi = namespaces.length - 1; nsi >= 0; nsi--) {\n                        var nsEntry = namespaces[nsi];\n                        if (nsEntry.namespace === n.namespaceURI) {\n                          if (nsEntry.prefix) {\n                            prefixedNodeName = nsEntry.prefix + ":" + nodeName;\n                          }\n                          break;\n                        }\n                      }\n                    }\n                  }\n                  buf.push("<", prefixedNodeName);\n                  var childNamespaces = namespaces.slice();\n                  for (var i = 0; i < len; i++) {\n                    var attr = attrs.item(i);\n                    if (attr.prefix == "xmlns") {\n                      childNamespaces.push({\n                        prefix: attr.localName,\n                        namespace: attr.value\n                      });\n                    } else if (attr.nodeName == "xmlns") {\n                      childNamespaces.push({ prefix: "", namespace: attr.value });\n                    }\n                  }\n                  for (var i = 0; i < len; i++) {\n                    var attr = attrs.item(i);\n                    if (needNamespaceDefine(attr, isHTML, childNamespaces)) {\n                      var attrPrefix = attr.prefix || "";\n                      var uri = attr.namespaceURI;\n                      addSerializedAttribute(buf, attrPrefix ? "xmlns:" + attrPrefix : "xmlns", uri);\n                      childNamespaces.push({ prefix: attrPrefix, namespace: uri });\n                    }\n                    var filteredAttr = nodeFilter ? nodeFilter(attr) : attr;\n                    if (filteredAttr) {\n                      if (typeof filteredAttr === "string") {\n                        buf.push(filteredAttr);\n                      } else {\n                        addSerializedAttribute(buf, filteredAttr.name, filteredAttr.value);\n                      }\n                    }\n                  }\n                  if (nodeName === prefixedNodeName && needNamespaceDefine(n, isHTML, childNamespaces)) {\n                    var nodePrefix = n.prefix || "";\n                    var uri = n.namespaceURI;\n                    addSerializedAttribute(buf, nodePrefix ? "xmlns:" + nodePrefix : "xmlns", uri);\n                    childNamespaces.push({ prefix: nodePrefix, namespace: uri });\n                  }\n                  var canCloseTag = !n.firstChild;\n                  if (canCloseTag && (isHTML || n.namespaceURI === NAMESPACE.HTML)) {\n                    canCloseTag = isHTMLVoidElement(nodeName);\n                  }\n                  if (canCloseTag) {\n                    buf.push("/>");\n                    return null;\n                  }\n                  buf.push(">");\n                  if (isHTML && isHTMLRawTextElement(nodeName)) {\n                    var child = n.firstChild;\n                    while (child) {\n                      if (child.data) {\n                        buf.push(child.data);\n                      } else {\n                        serializeToString(child, buf, childNamespaces.slice(), opts);\n                      }\n                      child = child.nextSibling;\n                    }\n                    buf.push("</", prefixedNodeName, ">");\n                    return null;\n                  }\n                  return { ns: childNamespaces, tag: prefixedNodeName };\n                case DOCUMENT_NODE:\n                case DOCUMENT_FRAGMENT_NODE:\n                  if (requireWellFormed && n.nodeType === DOCUMENT_NODE && n.documentElement == null) {\n                    throw new DOMException("The Document has no documentElement", DOMExceptionName.InvalidStateError);\n                  }\n                  return { ns: namespaces };\n                case ATTRIBUTE_NODE:\n                  addSerializedAttribute(buf, n.name, n.value);\n                  return null;\n                case TEXT_NODE:\n                  if (requireWellFormed && g.InvalidChar.test(n.data)) {\n                    throw new DOMException(\n                      "The Text node data contains characters outside the XML Char production",\n                      DOMExceptionName.InvalidStateError\n                    );\n                  }\n                  buf.push(n.data.replace(/[<&>]/g, _xmlEncoder));\n                  return null;\n                case CDATA_SECTION_NODE:\n                  if (requireWellFormed && n.data.indexOf("]]>") !== -1) {\n                    throw new DOMException(\'The CDATASection data contains "]]>"\', DOMExceptionName.InvalidStateError);\n                  }\n                  if (splitCDATASections) {\n                    buf.push(g.CDATA_START, n.data.replace(/]]>/g, "]]]]><![CDATA[>"), g.CDATA_END);\n                  } else {\n                    buf.push(g.CDATA_START, n.data, g.CDATA_END);\n                  }\n                  return null;\n                case COMMENT_NODE:\n                  if (requireWellFormed) {\n                    if (g.InvalidChar.test(n.data)) {\n                      throw new DOMException(\n                        "The comment node data contains characters outside the XML Char production",\n                        DOMExceptionName.InvalidStateError\n                      );\n                    }\n                    if (n.data.indexOf("--") !== -1 || n.data[n.data.length - 1] === "-") {\n                      throw new DOMException(\n                        \'The comment node data contains "--" or ends with "-"\',\n                        DOMExceptionName.InvalidStateError\n                      );\n                    }\n                  }\n                  buf.push(g.COMMENT_START, n.data, g.COMMENT_END);\n                  return null;\n                case DOCUMENT_TYPE_NODE:\n                  var pubid = n.publicId;\n                  var sysid = n.systemId;\n                  if (requireWellFormed) {\n                    if (pubid && !g.PubidLiteral_match.test(pubid)) {\n                      throw new DOMException("DocumentType publicId is not a valid PubidLiteral", DOMExceptionName.InvalidStateError);\n                    }\n                    if (sysid && sysid !== "." && !g.SystemLiteral_match.test(sysid)) {\n                      throw new DOMException("DocumentType systemId is not a valid SystemLiteral", DOMExceptionName.InvalidStateError);\n                    }\n                    if (n.internalSubset && n.internalSubset.indexOf("]>") !== -1) {\n                      throw new DOMException(\'DocumentType internalSubset contains "]>"\', DOMExceptionName.InvalidStateError);\n                    }\n                  }\n                  buf.push(g.DOCTYPE_DECL_START, " ", n.name);\n                  if (pubid) {\n                    buf.push(" ", g.PUBLIC, " ", pubid);\n                    if (sysid && sysid !== ".") {\n                      buf.push(" ", sysid);\n                    }\n                  } else if (sysid && sysid !== ".") {\n                    buf.push(" ", g.SYSTEM, " ", sysid);\n                  }\n                  if (n.internalSubset) {\n                    buf.push(" [", n.internalSubset, "]");\n                  }\n                  buf.push(">");\n                  return null;\n                case PROCESSING_INSTRUCTION_NODE:\n                  if (requireWellFormed) {\n                    if (n.target.indexOf(":") !== -1 || n.target.toLowerCase() === "xml") {\n                      throw new DOMException("The ProcessingInstruction target is not well-formed", DOMExceptionName.InvalidStateError);\n                    }\n                    if (g.InvalidChar.test(n.data)) {\n                      throw new DOMException(\n                        "The ProcessingInstruction data contains characters outside the XML Char production",\n                        DOMExceptionName.InvalidStateError\n                      );\n                    }\n                    if (n.data.indexOf("?>") !== -1) {\n                      throw new DOMException(\'The ProcessingInstruction data contains "?>"\', DOMExceptionName.InvalidStateError);\n                    }\n                  }\n                  buf.push("<?", n.target, " ", n.data, "?>");\n                  return null;\n                case ENTITY_REFERENCE_NODE:\n                  buf.push("&", n.nodeName, ";");\n                  return null;\n                //case ENTITY_NODE:\n                //case NOTATION_NODE:\n                default:\n                  buf.push("??", n.nodeName);\n                  return null;\n              }\n            },\n            exit: function(n, childCtx) {\n              if (childCtx && childCtx.tag) {\n                buf.push("</", childCtx.tag, ">");\n              }\n            }\n          }\n        );\n      }\n      function importNode(doc, node, deep) {\n        var destRoot;\n        walkDOM(node, null, {\n          enter: function(srcNode, destParent) {\n            var destNode = srcNode.cloneNode(false);\n            destNode.ownerDocument = doc;\n            destNode.parentNode = null;\n            if (destParent === null) {\n              destRoot = destNode;\n            } else {\n              destParent.appendChild(destNode);\n            }\n            var shouldDeep = srcNode.nodeType === ATTRIBUTE_NODE || deep;\n            return shouldDeep ? destNode : null;\n          }\n        });\n        return destRoot;\n      }\n      function cloneNode(doc, node, deep) {\n        var destRoot;\n        walkDOM(node, null, {\n          enter: function(srcNode, destParent) {\n            var destNode = new srcNode.constructor(PDC);\n            for (var n in srcNode) {\n              if (hasOwn(srcNode, n)) {\n                var v = srcNode[n];\n                if (typeof v != "object") {\n                  if (v != destNode[n]) {\n                    destNode[n] = v;\n                  }\n                }\n              }\n            }\n            if (srcNode.childNodes) {\n              destNode.childNodes = new NodeList();\n            }\n            destNode.ownerDocument = doc;\n            var shouldDeep = deep;\n            switch (destNode.nodeType) {\n              case ELEMENT_NODE:\n                var attrs = srcNode.attributes;\n                var attrs2 = destNode.attributes = new NamedNodeMap();\n                var len = attrs.length;\n                attrs2._ownerElement = destNode;\n                for (var i = 0; i < len; i++) {\n                  destNode.setAttributeNode(cloneNode(doc, attrs.item(i), true));\n                }\n                break;\n              case ATTRIBUTE_NODE:\n                shouldDeep = true;\n            }\n            if (destParent !== null) {\n              destParent.appendChild(destNode);\n            } else {\n              destRoot = destNode;\n            }\n            return shouldDeep ? destNode : null;\n          }\n        });\n        return destRoot;\n      }\n      function __set__(object, key, value) {\n        object[key] = value;\n      }\n      function childrenRefresh(node) {\n        var ls = [];\n        var child = node.firstChild;\n        while (child) {\n          if (child.nodeType === ELEMENT_NODE) {\n            ls.push(child);\n          }\n          child = child.nextSibling;\n        }\n        return ls;\n      }\n      try {\n        if (Object.defineProperty) {\n          Object.defineProperty(LiveNodeList.prototype, "length", {\n            get: function() {\n              _updateLiveList(this);\n              return this.$$length;\n            }\n          });\n          Object.defineProperty(Node.prototype, "textContent", {\n            get: function() {\n              if (this.nodeType === ELEMENT_NODE || this.nodeType === DOCUMENT_FRAGMENT_NODE) {\n                var buf = [];\n                walkDOM(this, null, {\n                  enter: function(n) {\n                    if (n.nodeType === ELEMENT_NODE || n.nodeType === DOCUMENT_FRAGMENT_NODE) {\n                      return true;\n                    }\n                    if (n.nodeType === PROCESSING_INSTRUCTION_NODE || n.nodeType === COMMENT_NODE) {\n                      return null;\n                    }\n                    buf.push(n.nodeValue);\n                  }\n                });\n                return buf.join("");\n              }\n              return this.nodeValue;\n            },\n            set: function(data) {\n              switch (this.nodeType) {\n                case ELEMENT_NODE:\n                case DOCUMENT_FRAGMENT_NODE:\n                  while (this.firstChild) {\n                    this.removeChild(this.firstChild);\n                  }\n                  if (data || String(data)) {\n                    this.appendChild(this.ownerDocument.createTextNode(data));\n                  }\n                  break;\n                default:\n                  this.data = data;\n                  this.value = data;\n                  this.nodeValue = data;\n              }\n            }\n          });\n          Object.defineProperty(Element.prototype, "children", {\n            get: function() {\n              return new LiveNodeList(this, childrenRefresh);\n            }\n          });\n          Object.defineProperty(Document.prototype, "children", {\n            get: function() {\n              return new LiveNodeList(this, childrenRefresh);\n            }\n          });\n          Object.defineProperty(DocumentFragment.prototype, "children", {\n            get: function() {\n              return new LiveNodeList(this, childrenRefresh);\n            }\n          });\n          __set__ = function(object, key, value) {\n            object["$$" + key] = value;\n          };\n        }\n      } catch (e) {\n      }\n      exports2._updateLiveList = _updateLiveList;\n      exports2.Attr = Attr;\n      exports2.CDATASection = CDATASection;\n      exports2.CharacterData = CharacterData;\n      exports2.Comment = Comment;\n      exports2.Document = Document;\n      exports2.DocumentFragment = DocumentFragment;\n      exports2.DocumentType = DocumentType;\n      exports2.DOMImplementation = DOMImplementation;\n      exports2.Element = Element;\n      exports2.Entity = Entity;\n      exports2.EntityReference = EntityReference;\n      exports2.LiveNodeList = LiveNodeList;\n      exports2.NamedNodeMap = NamedNodeMap;\n      exports2.Node = Node;\n      exports2.NodeList = NodeList;\n      exports2.Notation = Notation;\n      exports2.Text = Text;\n      exports2.ProcessingInstruction = ProcessingInstruction;\n      exports2.walkDOM = walkDOM;\n      exports2.XMLSerializer = XMLSerializer2;\n    }\n  });\n\n  // node_modules/@xmldom/xmldom/lib/entities.js\n  var require_entities = __commonJS({\n    "node_modules/@xmldom/xmldom/lib/entities.js"(exports2) {\n      "use strict";\n      var freeze = require_conventions().freeze;\n      exports2.XML_ENTITIES = freeze({\n        amp: "&",\n        apos: "\'",\n        gt: ">",\n        lt: "<",\n        quot: \'"\'\n      });\n      exports2.HTML_ENTITIES = freeze({\n        Aacute: "\\xC1",\n        aacute: "\\xE1",\n        Abreve: "\\u0102",\n        abreve: "\\u0103",\n        ac: "\\u223E",\n        acd: "\\u223F",\n        acE: "\\u223E\\u0333",\n        Acirc: "\\xC2",\n        acirc: "\\xE2",\n        acute: "\\xB4",\n        Acy: "\\u0410",\n        acy: "\\u0430",\n        AElig: "\\xC6",\n        aelig: "\\xE6",\n        af: "\\u2061",\n        Afr: "\\u{1D504}",\n        afr: "\\u{1D51E}",\n        Agrave: "\\xC0",\n        agrave: "\\xE0",\n        alefsym: "\\u2135",\n        aleph: "\\u2135",\n        Alpha: "\\u0391",\n        alpha: "\\u03B1",\n        Amacr: "\\u0100",\n        amacr: "\\u0101",\n        amalg: "\\u2A3F",\n        AMP: "&",\n        amp: "&",\n        And: "\\u2A53",\n        and: "\\u2227",\n        andand: "\\u2A55",\n        andd: "\\u2A5C",\n        andslope: "\\u2A58",\n        andv: "\\u2A5A",\n        ang: "\\u2220",\n        ange: "\\u29A4",\n        angle: "\\u2220",\n        angmsd: "\\u2221",\n        angmsdaa: "\\u29A8",\n        angmsdab: "\\u29A9",\n        angmsdac: "\\u29AA",\n        angmsdad: "\\u29AB",\n        angmsdae: "\\u29AC",\n        angmsdaf: "\\u29AD",\n        angmsdag: "\\u29AE",\n        angmsdah: "\\u29AF",\n        angrt: "\\u221F",\n        angrtvb: "\\u22BE",\n        angrtvbd: "\\u299D",\n        angsph: "\\u2222",\n        angst: "\\xC5",\n        angzarr: "\\u237C",\n        Aogon: "\\u0104",\n        aogon: "\\u0105",\n        Aopf: "\\u{1D538}",\n        aopf: "\\u{1D552}",\n        ap: "\\u2248",\n        apacir: "\\u2A6F",\n        apE: "\\u2A70",\n        ape: "\\u224A",\n        apid: "\\u224B",\n        apos: "\'",\n        ApplyFunction: "\\u2061",\n        approx: "\\u2248",\n        approxeq: "\\u224A",\n        Aring: "\\xC5",\n        aring: "\\xE5",\n        Ascr: "\\u{1D49C}",\n        ascr: "\\u{1D4B6}",\n        Assign: "\\u2254",\n        ast: "*",\n        asymp: "\\u2248",\n        asympeq: "\\u224D",\n        Atilde: "\\xC3",\n        atilde: "\\xE3",\n        Auml: "\\xC4",\n        auml: "\\xE4",\n        awconint: "\\u2233",\n        awint: "\\u2A11",\n        backcong: "\\u224C",\n        backepsilon: "\\u03F6",\n        backprime: "\\u2035",\n        backsim: "\\u223D",\n        backsimeq: "\\u22CD",\n        Backslash: "\\u2216",\n        Barv: "\\u2AE7",\n        barvee: "\\u22BD",\n        Barwed: "\\u2306",\n        barwed: "\\u2305",\n        barwedge: "\\u2305",\n        bbrk: "\\u23B5",\n        bbrktbrk: "\\u23B6",\n        bcong: "\\u224C",\n        Bcy: "\\u0411",\n        bcy: "\\u0431",\n        bdquo: "\\u201E",\n        becaus: "\\u2235",\n        Because: "\\u2235",\n        because: "\\u2235",\n        bemptyv: "\\u29B0",\n        bepsi: "\\u03F6",\n        bernou: "\\u212C",\n        Bernoullis: "\\u212C",\n        Beta: "\\u0392",\n        beta: "\\u03B2",\n        beth: "\\u2136",\n        between: "\\u226C",\n        Bfr: "\\u{1D505}",\n        bfr: "\\u{1D51F}",\n        bigcap: "\\u22C2",\n        bigcirc: "\\u25EF",\n        bigcup: "\\u22C3",\n        bigodot: "\\u2A00",\n        bigoplus: "\\u2A01",\n        bigotimes: "\\u2A02",\n        bigsqcup: "\\u2A06",\n        bigstar: "\\u2605",\n        bigtriangledown: "\\u25BD",\n        bigtriangleup: "\\u25B3",\n        biguplus: "\\u2A04",\n        bigvee: "\\u22C1",\n        bigwedge: "\\u22C0",\n        bkarow: "\\u290D",\n        blacklozenge: "\\u29EB",\n        blacksquare: "\\u25AA",\n        blacktriangle: "\\u25B4",\n        blacktriangledown: "\\u25BE",\n        blacktriangleleft: "\\u25C2",\n        blacktriangleright: "\\u25B8",\n        blank: "\\u2423",\n        blk12: "\\u2592",\n        blk14: "\\u2591",\n        blk34: "\\u2593",\n        block: "\\u2588",\n        bne: "=\\u20E5",\n        bnequiv: "\\u2261\\u20E5",\n        bNot: "\\u2AED",\n        bnot: "\\u2310",\n        Bopf: "\\u{1D539}",\n        bopf: "\\u{1D553}",\n        bot: "\\u22A5",\n        bottom: "\\u22A5",\n        bowtie: "\\u22C8",\n        boxbox: "\\u29C9",\n        boxDL: "\\u2557",\n        boxDl: "\\u2556",\n        boxdL: "\\u2555",\n        boxdl: "\\u2510",\n        boxDR: "\\u2554",\n        boxDr: "\\u2553",\n        boxdR: "\\u2552",\n        boxdr: "\\u250C",\n        boxH: "\\u2550",\n        boxh: "\\u2500",\n        boxHD: "\\u2566",\n        boxHd: "\\u2564",\n        boxhD: "\\u2565",\n        boxhd: "\\u252C",\n        boxHU: "\\u2569",\n        boxHu: "\\u2567",\n        boxhU: "\\u2568",\n        boxhu: "\\u2534",\n        boxminus: "\\u229F",\n        boxplus: "\\u229E",\n        boxtimes: "\\u22A0",\n        boxUL: "\\u255D",\n        boxUl: "\\u255C",\n        boxuL: "\\u255B",\n        boxul: "\\u2518",\n        boxUR: "\\u255A",\n        boxUr: "\\u2559",\n        boxuR: "\\u2558",\n        boxur: "\\u2514",\n        boxV: "\\u2551",\n        boxv: "\\u2502",\n        boxVH: "\\u256C",\n        boxVh: "\\u256B",\n        boxvH: "\\u256A",\n        boxvh: "\\u253C",\n        boxVL: "\\u2563",\n        boxVl: "\\u2562",\n        boxvL: "\\u2561",\n        boxvl: "\\u2524",\n        boxVR: "\\u2560",\n        boxVr: "\\u255F",\n        boxvR: "\\u255E",\n        boxvr: "\\u251C",\n        bprime: "\\u2035",\n        Breve: "\\u02D8",\n        breve: "\\u02D8",\n        brvbar: "\\xA6",\n        Bscr: "\\u212C",\n        bscr: "\\u{1D4B7}",\n        bsemi: "\\u204F",\n        bsim: "\\u223D",\n        bsime: "\\u22CD",\n        bsol: "\\\\",\n        bsolb: "\\u29C5",\n        bsolhsub: "\\u27C8",\n        bull: "\\u2022",\n        bullet: "\\u2022",\n        bump: "\\u224E",\n        bumpE: "\\u2AAE",\n        bumpe: "\\u224F",\n        Bumpeq: "\\u224E",\n        bumpeq: "\\u224F",\n        Cacute: "\\u0106",\n        cacute: "\\u0107",\n        Cap: "\\u22D2",\n        cap: "\\u2229",\n        capand: "\\u2A44",\n        capbrcup: "\\u2A49",\n        capcap: "\\u2A4B",\n        capcup: "\\u2A47",\n        capdot: "\\u2A40",\n        CapitalDifferentialD: "\\u2145",\n        caps: "\\u2229\\uFE00",\n        caret: "\\u2041",\n        caron: "\\u02C7",\n        Cayleys: "\\u212D",\n        ccaps: "\\u2A4D",\n        Ccaron: "\\u010C",\n        ccaron: "\\u010D",\n        Ccedil: "\\xC7",\n        ccedil: "\\xE7",\n        Ccirc: "\\u0108",\n        ccirc: "\\u0109",\n        Cconint: "\\u2230",\n        ccups: "\\u2A4C",\n        ccupssm: "\\u2A50",\n        Cdot: "\\u010A",\n        cdot: "\\u010B",\n        cedil: "\\xB8",\n        Cedilla: "\\xB8",\n        cemptyv: "\\u29B2",\n        cent: "\\xA2",\n        CenterDot: "\\xB7",\n        centerdot: "\\xB7",\n        Cfr: "\\u212D",\n        cfr: "\\u{1D520}",\n        CHcy: "\\u0427",\n        chcy: "\\u0447",\n        check: "\\u2713",\n        checkmark: "\\u2713",\n        Chi: "\\u03A7",\n        chi: "\\u03C7",\n        cir: "\\u25CB",\n        circ: "\\u02C6",\n        circeq: "\\u2257",\n        circlearrowleft: "\\u21BA",\n        circlearrowright: "\\u21BB",\n        circledast: "\\u229B",\n        circledcirc: "\\u229A",\n        circleddash: "\\u229D",\n        CircleDot: "\\u2299",\n        circledR: "\\xAE",\n        circledS: "\\u24C8",\n        CircleMinus: "\\u2296",\n        CirclePlus: "\\u2295",\n        CircleTimes: "\\u2297",\n        cirE: "\\u29C3",\n        cire: "\\u2257",\n        cirfnint: "\\u2A10",\n        cirmid: "\\u2AEF",\n        cirscir: "\\u29C2",\n        ClockwiseContourIntegral: "\\u2232",\n        CloseCurlyDoubleQuote: "\\u201D",\n        CloseCurlyQuote: "\\u2019",\n        clubs: "\\u2663",\n        clubsuit: "\\u2663",\n        Colon: "\\u2237",\n        colon: ":",\n        Colone: "\\u2A74",\n        colone: "\\u2254",\n        coloneq: "\\u2254",\n        comma: ",",\n        commat: "@",\n        comp: "\\u2201",\n        compfn: "\\u2218",\n        complement: "\\u2201",\n        complexes: "\\u2102",\n        cong: "\\u2245",\n        congdot: "\\u2A6D",\n        Congruent: "\\u2261",\n        Conint: "\\u222F",\n        conint: "\\u222E",\n        ContourIntegral: "\\u222E",\n        Copf: "\\u2102",\n        copf: "\\u{1D554}",\n        coprod: "\\u2210",\n        Coproduct: "\\u2210",\n        COPY: "\\xA9",\n        copy: "\\xA9",\n        copysr: "\\u2117",\n        CounterClockwiseContourIntegral: "\\u2233",\n        crarr: "\\u21B5",\n        Cross: "\\u2A2F",\n        cross: "\\u2717",\n        Cscr: "\\u{1D49E}",\n        cscr: "\\u{1D4B8}",\n        csub: "\\u2ACF",\n        csube: "\\u2AD1",\n        csup: "\\u2AD0",\n        csupe: "\\u2AD2",\n        ctdot: "\\u22EF",\n        cudarrl: "\\u2938",\n        cudarrr: "\\u2935",\n        cuepr: "\\u22DE",\n        cuesc: "\\u22DF",\n        cularr: "\\u21B6",\n        cularrp: "\\u293D",\n        Cup: "\\u22D3",\n        cup: "\\u222A",\n        cupbrcap: "\\u2A48",\n        CupCap: "\\u224D",\n        cupcap: "\\u2A46",\n        cupcup: "\\u2A4A",\n        cupdot: "\\u228D",\n        cupor: "\\u2A45",\n        cups: "\\u222A\\uFE00",\n        curarr: "\\u21B7",\n        curarrm: "\\u293C",\n        curlyeqprec: "\\u22DE",\n        curlyeqsucc: "\\u22DF",\n        curlyvee: "\\u22CE",\n        curlywedge: "\\u22CF",\n        curren: "\\xA4",\n        curvearrowleft: "\\u21B6",\n        curvearrowright: "\\u21B7",\n        cuvee: "\\u22CE",\n        cuwed: "\\u22CF",\n        cwconint: "\\u2232",\n        cwint: "\\u2231",\n        cylcty: "\\u232D",\n        Dagger: "\\u2021",\n        dagger: "\\u2020",\n        daleth: "\\u2138",\n        Darr: "\\u21A1",\n        dArr: "\\u21D3",\n        darr: "\\u2193",\n        dash: "\\u2010",\n        Dashv: "\\u2AE4",\n        dashv: "\\u22A3",\n        dbkarow: "\\u290F",\n        dblac: "\\u02DD",\n        Dcaron: "\\u010E",\n        dcaron: "\\u010F",\n        Dcy: "\\u0414",\n        dcy: "\\u0434",\n        DD: "\\u2145",\n        dd: "\\u2146",\n        ddagger: "\\u2021",\n        ddarr: "\\u21CA",\n        DDotrahd: "\\u2911",\n        ddotseq: "\\u2A77",\n        deg: "\\xB0",\n        Del: "\\u2207",\n        Delta: "\\u0394",\n        delta: "\\u03B4",\n        demptyv: "\\u29B1",\n        dfisht: "\\u297F",\n        Dfr: "\\u{1D507}",\n        dfr: "\\u{1D521}",\n        dHar: "\\u2965",\n        dharl: "\\u21C3",\n        dharr: "\\u21C2",\n        DiacriticalAcute: "\\xB4",\n        DiacriticalDot: "\\u02D9",\n        DiacriticalDoubleAcute: "\\u02DD",\n        DiacriticalGrave: "`",\n        DiacriticalTilde: "\\u02DC",\n        diam: "\\u22C4",\n        Diamond: "\\u22C4",\n        diamond: "\\u22C4",\n        diamondsuit: "\\u2666",\n        diams: "\\u2666",\n        die: "\\xA8",\n        DifferentialD: "\\u2146",\n        digamma: "\\u03DD",\n        disin: "\\u22F2",\n        div: "\\xF7",\n        divide: "\\xF7",\n        divideontimes: "\\u22C7",\n        divonx: "\\u22C7",\n        DJcy: "\\u0402",\n        djcy: "\\u0452",\n        dlcorn: "\\u231E",\n        dlcrop: "\\u230D",\n        dollar: "$",\n        Dopf: "\\u{1D53B}",\n        dopf: "\\u{1D555}",\n        Dot: "\\xA8",\n        dot: "\\u02D9",\n        DotDot: "\\u20DC",\n        doteq: "\\u2250",\n        doteqdot: "\\u2251",\n        DotEqual: "\\u2250",\n        dotminus: "\\u2238",\n        dotplus: "\\u2214",\n        dotsquare: "\\u22A1",\n        doublebarwedge: "\\u2306",\n        DoubleContourIntegral: "\\u222F",\n        DoubleDot: "\\xA8",\n        DoubleDownArrow: "\\u21D3",\n        DoubleLeftArrow: "\\u21D0",\n        DoubleLeftRightArrow: "\\u21D4",\n        DoubleLeftTee: "\\u2AE4",\n        DoubleLongLeftArrow: "\\u27F8",\n        DoubleLongLeftRightArrow: "\\u27FA",\n        DoubleLongRightArrow: "\\u27F9",\n        DoubleRightArrow: "\\u21D2",\n        DoubleRightTee: "\\u22A8",\n        DoubleUpArrow: "\\u21D1",\n        DoubleUpDownArrow: "\\u21D5",\n        DoubleVerticalBar: "\\u2225",\n        DownArrow: "\\u2193",\n        Downarrow: "\\u21D3",\n        downarrow: "\\u2193",\n        DownArrowBar: "\\u2913",\n        DownArrowUpArrow: "\\u21F5",\n        DownBreve: "\\u0311",\n        downdownarrows: "\\u21CA",\n        downharpoonleft: "\\u21C3",\n        downharpoonright: "\\u21C2",\n        DownLeftRightVector: "\\u2950",\n        DownLeftTeeVector: "\\u295E",\n        DownLeftVector: "\\u21BD",\n        DownLeftVectorBar: "\\u2956",\n        DownRightTeeVector: "\\u295F",\n        DownRightVector: "\\u21C1",\n        DownRightVectorBar: "\\u2957",\n        DownTee: "\\u22A4",\n        DownTeeArrow: "\\u21A7",\n        drbkarow: "\\u2910",\n        drcorn: "\\u231F",\n        drcrop: "\\u230C",\n        Dscr: "\\u{1D49F}",\n        dscr: "\\u{1D4B9}",\n        DScy: "\\u0405",\n        dscy: "\\u0455",\n        dsol: "\\u29F6",\n        Dstrok: "\\u0110",\n        dstrok: "\\u0111",\n        dtdot: "\\u22F1",\n        dtri: "\\u25BF",\n        dtrif: "\\u25BE",\n        duarr: "\\u21F5",\n        duhar: "\\u296F",\n        dwangle: "\\u29A6",\n        DZcy: "\\u040F",\n        dzcy: "\\u045F",\n        dzigrarr: "\\u27FF",\n        Eacute: "\\xC9",\n        eacute: "\\xE9",\n        easter: "\\u2A6E",\n        Ecaron: "\\u011A",\n        ecaron: "\\u011B",\n        ecir: "\\u2256",\n        Ecirc: "\\xCA",\n        ecirc: "\\xEA",\n        ecolon: "\\u2255",\n        Ecy: "\\u042D",\n        ecy: "\\u044D",\n        eDDot: "\\u2A77",\n        Edot: "\\u0116",\n        eDot: "\\u2251",\n        edot: "\\u0117",\n        ee: "\\u2147",\n        efDot: "\\u2252",\n        Efr: "\\u{1D508}",\n        efr: "\\u{1D522}",\n        eg: "\\u2A9A",\n        Egrave: "\\xC8",\n        egrave: "\\xE8",\n        egs: "\\u2A96",\n        egsdot: "\\u2A98",\n        el: "\\u2A99",\n        Element: "\\u2208",\n        elinters: "\\u23E7",\n        ell: "\\u2113",\n        els: "\\u2A95",\n        elsdot: "\\u2A97",\n        Emacr: "\\u0112",\n        emacr: "\\u0113",\n        empty: "\\u2205",\n        emptyset: "\\u2205",\n        EmptySmallSquare: "\\u25FB",\n        emptyv: "\\u2205",\n        EmptyVerySmallSquare: "\\u25AB",\n        emsp: "\\u2003",\n        emsp13: "\\u2004",\n        emsp14: "\\u2005",\n        ENG: "\\u014A",\n        eng: "\\u014B",\n        ensp: "\\u2002",\n        Eogon: "\\u0118",\n        eogon: "\\u0119",\n        Eopf: "\\u{1D53C}",\n        eopf: "\\u{1D556}",\n        epar: "\\u22D5",\n        eparsl: "\\u29E3",\n        eplus: "\\u2A71",\n        epsi: "\\u03B5",\n        Epsilon: "\\u0395",\n        epsilon: "\\u03B5",\n        epsiv: "\\u03F5",\n        eqcirc: "\\u2256",\n        eqcolon: "\\u2255",\n        eqsim: "\\u2242",\n        eqslantgtr: "\\u2A96",\n        eqslantless: "\\u2A95",\n        Equal: "\\u2A75",\n        equals: "=",\n        EqualTilde: "\\u2242",\n        equest: "\\u225F",\n        Equilibrium: "\\u21CC",\n        equiv: "\\u2261",\n        equivDD: "\\u2A78",\n        eqvparsl: "\\u29E5",\n        erarr: "\\u2971",\n        erDot: "\\u2253",\n        Escr: "\\u2130",\n        escr: "\\u212F",\n        esdot: "\\u2250",\n        Esim: "\\u2A73",\n        esim: "\\u2242",\n        Eta: "\\u0397",\n        eta: "\\u03B7",\n        ETH: "\\xD0",\n        eth: "\\xF0",\n        Euml: "\\xCB",\n        euml: "\\xEB",\n        euro: "\\u20AC",\n        excl: "!",\n        exist: "\\u2203",\n        Exists: "\\u2203",\n        expectation: "\\u2130",\n        ExponentialE: "\\u2147",\n        exponentiale: "\\u2147",\n        fallingdotseq: "\\u2252",\n        Fcy: "\\u0424",\n        fcy: "\\u0444",\n        female: "\\u2640",\n        ffilig: "\\uFB03",\n        fflig: "\\uFB00",\n        ffllig: "\\uFB04",\n        Ffr: "\\u{1D509}",\n        ffr: "\\u{1D523}",\n        filig: "\\uFB01",\n        FilledSmallSquare: "\\u25FC",\n        FilledVerySmallSquare: "\\u25AA",\n        fjlig: "fj",\n        flat: "\\u266D",\n        fllig: "\\uFB02",\n        fltns: "\\u25B1",\n        fnof: "\\u0192",\n        Fopf: "\\u{1D53D}",\n        fopf: "\\u{1D557}",\n        ForAll: "\\u2200",\n        forall: "\\u2200",\n        fork: "\\u22D4",\n        forkv: "\\u2AD9",\n        Fouriertrf: "\\u2131",\n        fpartint: "\\u2A0D",\n        frac12: "\\xBD",\n        frac13: "\\u2153",\n        frac14: "\\xBC",\n        frac15: "\\u2155",\n        frac16: "\\u2159",\n        frac18: "\\u215B",\n        frac23: "\\u2154",\n        frac25: "\\u2156",\n        frac34: "\\xBE",\n        frac35: "\\u2157",\n        frac38: "\\u215C",\n        frac45: "\\u2158",\n        frac56: "\\u215A",\n        frac58: "\\u215D",\n        frac78: "\\u215E",\n        frasl: "\\u2044",\n        frown: "\\u2322",\n        Fscr: "\\u2131",\n        fscr: "\\u{1D4BB}",\n        gacute: "\\u01F5",\n        Gamma: "\\u0393",\n        gamma: "\\u03B3",\n        Gammad: "\\u03DC",\n        gammad: "\\u03DD",\n        gap: "\\u2A86",\n        Gbreve: "\\u011E",\n        gbreve: "\\u011F",\n        Gcedil: "\\u0122",\n        Gcirc: "\\u011C",\n        gcirc: "\\u011D",\n        Gcy: "\\u0413",\n        gcy: "\\u0433",\n        Gdot: "\\u0120",\n        gdot: "\\u0121",\n        gE: "\\u2267",\n        ge: "\\u2265",\n        gEl: "\\u2A8C",\n        gel: "\\u22DB",\n        geq: "\\u2265",\n        geqq: "\\u2267",\n        geqslant: "\\u2A7E",\n        ges: "\\u2A7E",\n        gescc: "\\u2AA9",\n        gesdot: "\\u2A80",\n        gesdoto: "\\u2A82",\n        gesdotol: "\\u2A84",\n        gesl: "\\u22DB\\uFE00",\n        gesles: "\\u2A94",\n        Gfr: "\\u{1D50A}",\n        gfr: "\\u{1D524}",\n        Gg: "\\u22D9",\n        gg: "\\u226B",\n        ggg: "\\u22D9",\n        gimel: "\\u2137",\n        GJcy: "\\u0403",\n        gjcy: "\\u0453",\n        gl: "\\u2277",\n        gla: "\\u2AA5",\n        glE: "\\u2A92",\n        glj: "\\u2AA4",\n        gnap: "\\u2A8A",\n        gnapprox: "\\u2A8A",\n        gnE: "\\u2269",\n        gne: "\\u2A88",\n        gneq: "\\u2A88",\n        gneqq: "\\u2269",\n        gnsim: "\\u22E7",\n        Gopf: "\\u{1D53E}",\n        gopf: "\\u{1D558}",\n        grave: "`",\n        GreaterEqual: "\\u2265",\n        GreaterEqualLess: "\\u22DB",\n        GreaterFullEqual: "\\u2267",\n        GreaterGreater: "\\u2AA2",\n        GreaterLess: "\\u2277",\n        GreaterSlantEqual: "\\u2A7E",\n        GreaterTilde: "\\u2273",\n        Gscr: "\\u{1D4A2}",\n        gscr: "\\u210A",\n        gsim: "\\u2273",\n        gsime: "\\u2A8E",\n        gsiml: "\\u2A90",\n        Gt: "\\u226B",\n        GT: ">",\n        gt: ">",\n        gtcc: "\\u2AA7",\n        gtcir: "\\u2A7A",\n        gtdot: "\\u22D7",\n        gtlPar: "\\u2995",\n        gtquest: "\\u2A7C",\n        gtrapprox: "\\u2A86",\n        gtrarr: "\\u2978",\n        gtrdot: "\\u22D7",\n        gtreqless: "\\u22DB",\n        gtreqqless: "\\u2A8C",\n        gtrless: "\\u2277",\n        gtrsim: "\\u2273",\n        gvertneqq: "\\u2269\\uFE00",\n        gvnE: "\\u2269\\uFE00",\n        Hacek: "\\u02C7",\n        hairsp: "\\u200A",\n        half: "\\xBD",\n        hamilt: "\\u210B",\n        HARDcy: "\\u042A",\n        hardcy: "\\u044A",\n        hArr: "\\u21D4",\n        harr: "\\u2194",\n        harrcir: "\\u2948",\n        harrw: "\\u21AD",\n        Hat: "^",\n        hbar: "\\u210F",\n        Hcirc: "\\u0124",\n        hcirc: "\\u0125",\n        hearts: "\\u2665",\n        heartsuit: "\\u2665",\n        hellip: "\\u2026",\n        hercon: "\\u22B9",\n        Hfr: "\\u210C",\n        hfr: "\\u{1D525}",\n        HilbertSpace: "\\u210B",\n        hksearow: "\\u2925",\n        hkswarow: "\\u2926",\n        hoarr: "\\u21FF",\n        homtht: "\\u223B",\n        hookleftarrow: "\\u21A9",\n        hookrightarrow: "\\u21AA",\n        Hopf: "\\u210D",\n        hopf: "\\u{1D559}",\n        horbar: "\\u2015",\n        HorizontalLine: "\\u2500",\n        Hscr: "\\u210B",\n        hscr: "\\u{1D4BD}",\n        hslash: "\\u210F",\n        Hstrok: "\\u0126",\n        hstrok: "\\u0127",\n        HumpDownHump: "\\u224E",\n        HumpEqual: "\\u224F",\n        hybull: "\\u2043",\n        hyphen: "\\u2010",\n        Iacute: "\\xCD",\n        iacute: "\\xED",\n        ic: "\\u2063",\n        Icirc: "\\xCE",\n        icirc: "\\xEE",\n        Icy: "\\u0418",\n        icy: "\\u0438",\n        Idot: "\\u0130",\n        IEcy: "\\u0415",\n        iecy: "\\u0435",\n        iexcl: "\\xA1",\n        iff: "\\u21D4",\n        Ifr: "\\u2111",\n        ifr: "\\u{1D526}",\n        Igrave: "\\xCC",\n        igrave: "\\xEC",\n        ii: "\\u2148",\n        iiiint: "\\u2A0C",\n        iiint: "\\u222D",\n        iinfin: "\\u29DC",\n        iiota: "\\u2129",\n        IJlig: "\\u0132",\n        ijlig: "\\u0133",\n        Im: "\\u2111",\n        Imacr: "\\u012A",\n        imacr: "\\u012B",\n        image: "\\u2111",\n        ImaginaryI: "\\u2148",\n        imagline: "\\u2110",\n        imagpart: "\\u2111",\n        imath: "\\u0131",\n        imof: "\\u22B7",\n        imped: "\\u01B5",\n        Implies: "\\u21D2",\n        in: "\\u2208",\n        incare: "\\u2105",\n        infin: "\\u221E",\n        infintie: "\\u29DD",\n        inodot: "\\u0131",\n        Int: "\\u222C",\n        int: "\\u222B",\n        intcal: "\\u22BA",\n        integers: "\\u2124",\n        Integral: "\\u222B",\n        intercal: "\\u22BA",\n        Intersection: "\\u22C2",\n        intlarhk: "\\u2A17",\n        intprod: "\\u2A3C",\n        InvisibleComma: "\\u2063",\n        InvisibleTimes: "\\u2062",\n        IOcy: "\\u0401",\n        iocy: "\\u0451",\n        Iogon: "\\u012E",\n        iogon: "\\u012F",\n        Iopf: "\\u{1D540}",\n        iopf: "\\u{1D55A}",\n        Iota: "\\u0399",\n        iota: "\\u03B9",\n        iprod: "\\u2A3C",\n        iquest: "\\xBF",\n        Iscr: "\\u2110",\n        iscr: "\\u{1D4BE}",\n        isin: "\\u2208",\n        isindot: "\\u22F5",\n        isinE: "\\u22F9",\n        isins: "\\u22F4",\n        isinsv: "\\u22F3",\n        isinv: "\\u2208",\n        it: "\\u2062",\n        Itilde: "\\u0128",\n        itilde: "\\u0129",\n        Iukcy: "\\u0406",\n        iukcy: "\\u0456",\n        Iuml: "\\xCF",\n        iuml: "\\xEF",\n        Jcirc: "\\u0134",\n        jcirc: "\\u0135",\n        Jcy: "\\u0419",\n        jcy: "\\u0439",\n        Jfr: "\\u{1D50D}",\n        jfr: "\\u{1D527}",\n        jmath: "\\u0237",\n        Jopf: "\\u{1D541}",\n        jopf: "\\u{1D55B}",\n        Jscr: "\\u{1D4A5}",\n        jscr: "\\u{1D4BF}",\n        Jsercy: "\\u0408",\n        jsercy: "\\u0458",\n        Jukcy: "\\u0404",\n        jukcy: "\\u0454",\n        Kappa: "\\u039A",\n        kappa: "\\u03BA",\n        kappav: "\\u03F0",\n        Kcedil: "\\u0136",\n        kcedil: "\\u0137",\n        Kcy: "\\u041A",\n        kcy: "\\u043A",\n        Kfr: "\\u{1D50E}",\n        kfr: "\\u{1D528}",\n        kgreen: "\\u0138",\n        KHcy: "\\u0425",\n        khcy: "\\u0445",\n        KJcy: "\\u040C",\n        kjcy: "\\u045C",\n        Kopf: "\\u{1D542}",\n        kopf: "\\u{1D55C}",\n        Kscr: "\\u{1D4A6}",\n        kscr: "\\u{1D4C0}",\n        lAarr: "\\u21DA",\n        Lacute: "\\u0139",\n        lacute: "\\u013A",\n        laemptyv: "\\u29B4",\n        lagran: "\\u2112",\n        Lambda: "\\u039B",\n        lambda: "\\u03BB",\n        Lang: "\\u27EA",\n        lang: "\\u27E8",\n        langd: "\\u2991",\n        langle: "\\u27E8",\n        lap: "\\u2A85",\n        Laplacetrf: "\\u2112",\n        laquo: "\\xAB",\n        Larr: "\\u219E",\n        lArr: "\\u21D0",\n        larr: "\\u2190",\n        larrb: "\\u21E4",\n        larrbfs: "\\u291F",\n        larrfs: "\\u291D",\n        larrhk: "\\u21A9",\n        larrlp: "\\u21AB",\n        larrpl: "\\u2939",\n        larrsim: "\\u2973",\n        larrtl: "\\u21A2",\n        lat: "\\u2AAB",\n        lAtail: "\\u291B",\n        latail: "\\u2919",\n        late: "\\u2AAD",\n        lates: "\\u2AAD\\uFE00",\n        lBarr: "\\u290E",\n        lbarr: "\\u290C",\n        lbbrk: "\\u2772",\n        lbrace: "{",\n        lbrack: "[",\n        lbrke: "\\u298B",\n        lbrksld: "\\u298F",\n        lbrkslu: "\\u298D",\n        Lcaron: "\\u013D",\n        lcaron: "\\u013E",\n        Lcedil: "\\u013B",\n        lcedil: "\\u013C",\n        lceil: "\\u2308",\n        lcub: "{",\n        Lcy: "\\u041B",\n        lcy: "\\u043B",\n        ldca: "\\u2936",\n        ldquo: "\\u201C",\n        ldquor: "\\u201E",\n        ldrdhar: "\\u2967",\n        ldrushar: "\\u294B",\n        ldsh: "\\u21B2",\n        lE: "\\u2266",\n        le: "\\u2264",\n        LeftAngleBracket: "\\u27E8",\n        LeftArrow: "\\u2190",\n        Leftarrow: "\\u21D0",\n        leftarrow: "\\u2190",\n        LeftArrowBar: "\\u21E4",\n        LeftArrowRightArrow: "\\u21C6",\n        leftarrowtail: "\\u21A2",\n        LeftCeiling: "\\u2308",\n        LeftDoubleBracket: "\\u27E6",\n        LeftDownTeeVector: "\\u2961",\n        LeftDownVector: "\\u21C3",\n        LeftDownVectorBar: "\\u2959",\n        LeftFloor: "\\u230A",\n        leftharpoondown: "\\u21BD",\n        leftharpoonup: "\\u21BC",\n        leftleftarrows: "\\u21C7",\n        LeftRightArrow: "\\u2194",\n        Leftrightarrow: "\\u21D4",\n        leftrightarrow: "\\u2194",\n        leftrightarrows: "\\u21C6",\n        leftrightharpoons: "\\u21CB",\n        leftrightsquigarrow: "\\u21AD",\n        LeftRightVector: "\\u294E",\n        LeftTee: "\\u22A3",\n        LeftTeeArrow: "\\u21A4",\n        LeftTeeVector: "\\u295A",\n        leftthreetimes: "\\u22CB",\n        LeftTriangle: "\\u22B2",\n        LeftTriangleBar: "\\u29CF",\n        LeftTriangleEqual: "\\u22B4",\n        LeftUpDownVector: "\\u2951",\n        LeftUpTeeVector: "\\u2960",\n        LeftUpVector: "\\u21BF",\n        LeftUpVectorBar: "\\u2958",\n        LeftVector: "\\u21BC",\n        LeftVectorBar: "\\u2952",\n        lEg: "\\u2A8B",\n        leg: "\\u22DA",\n        leq: "\\u2264",\n        leqq: "\\u2266",\n        leqslant: "\\u2A7D",\n        les: "\\u2A7D",\n        lescc: "\\u2AA8",\n        lesdot: "\\u2A7F",\n        lesdoto: "\\u2A81",\n        lesdotor: "\\u2A83",\n        lesg: "\\u22DA\\uFE00",\n        lesges: "\\u2A93",\n        lessapprox: "\\u2A85",\n        lessdot: "\\u22D6",\n        lesseqgtr: "\\u22DA",\n        lesseqqgtr: "\\u2A8B",\n        LessEqualGreater: "\\u22DA",\n        LessFullEqual: "\\u2266",\n        LessGreater: "\\u2276",\n        lessgtr: "\\u2276",\n        LessLess: "\\u2AA1",\n        lesssim: "\\u2272",\n        LessSlantEqual: "\\u2A7D",\n        LessTilde: "\\u2272",\n        lfisht: "\\u297C",\n        lfloor: "\\u230A",\n        Lfr: "\\u{1D50F}",\n        lfr: "\\u{1D529}",\n        lg: "\\u2276",\n        lgE: "\\u2A91",\n        lHar: "\\u2962",\n        lhard: "\\u21BD",\n        lharu: "\\u21BC",\n        lharul: "\\u296A",\n        lhblk: "\\u2584",\n        LJcy: "\\u0409",\n        ljcy: "\\u0459",\n        Ll: "\\u22D8",\n        ll: "\\u226A",\n        llarr: "\\u21C7",\n        llcorner: "\\u231E",\n        Lleftarrow: "\\u21DA",\n        llhard: "\\u296B",\n        lltri: "\\u25FA",\n        Lmidot: "\\u013F",\n        lmidot: "\\u0140",\n        lmoust: "\\u23B0",\n        lmoustache: "\\u23B0",\n        lnap: "\\u2A89",\n        lnapprox: "\\u2A89",\n        lnE: "\\u2268",\n        lne: "\\u2A87",\n        lneq: "\\u2A87",\n        lneqq: "\\u2268",\n        lnsim: "\\u22E6",\n        loang: "\\u27EC",\n        loarr: "\\u21FD",\n        lobrk: "\\u27E6",\n        LongLeftArrow: "\\u27F5",\n        Longleftarrow: "\\u27F8",\n        longleftarrow: "\\u27F5",\n        LongLeftRightArrow: "\\u27F7",\n        Longleftrightarrow: "\\u27FA",\n        longleftrightarrow: "\\u27F7",\n        longmapsto: "\\u27FC",\n        LongRightArrow: "\\u27F6",\n        Longrightarrow: "\\u27F9",\n        longrightarrow: "\\u27F6",\n        looparrowleft: "\\u21AB",\n        looparrowright: "\\u21AC",\n        lopar: "\\u2985",\n        Lopf: "\\u{1D543}",\n        lopf: "\\u{1D55D}",\n        loplus: "\\u2A2D",\n        lotimes: "\\u2A34",\n        lowast: "\\u2217",\n        lowbar: "_",\n        LowerLeftArrow: "\\u2199",\n        LowerRightArrow: "\\u2198",\n        loz: "\\u25CA",\n        lozenge: "\\u25CA",\n        lozf: "\\u29EB",\n        lpar: "(",\n        lparlt: "\\u2993",\n        lrarr: "\\u21C6",\n        lrcorner: "\\u231F",\n        lrhar: "\\u21CB",\n        lrhard: "\\u296D",\n        lrm: "\\u200E",\n        lrtri: "\\u22BF",\n        lsaquo: "\\u2039",\n        Lscr: "\\u2112",\n        lscr: "\\u{1D4C1}",\n        Lsh: "\\u21B0",\n        lsh: "\\u21B0",\n        lsim: "\\u2272",\n        lsime: "\\u2A8D",\n        lsimg: "\\u2A8F",\n        lsqb: "[",\n        lsquo: "\\u2018",\n        lsquor: "\\u201A",\n        Lstrok: "\\u0141",\n        lstrok: "\\u0142",\n        Lt: "\\u226A",\n        LT: "<",\n        lt: "<",\n        ltcc: "\\u2AA6",\n        ltcir: "\\u2A79",\n        ltdot: "\\u22D6",\n        lthree: "\\u22CB",\n        ltimes: "\\u22C9",\n        ltlarr: "\\u2976",\n        ltquest: "\\u2A7B",\n        ltri: "\\u25C3",\n        ltrie: "\\u22B4",\n        ltrif: "\\u25C2",\n        ltrPar: "\\u2996",\n        lurdshar: "\\u294A",\n        luruhar: "\\u2966",\n        lvertneqq: "\\u2268\\uFE00",\n        lvnE: "\\u2268\\uFE00",\n        macr: "\\xAF",\n        male: "\\u2642",\n        malt: "\\u2720",\n        maltese: "\\u2720",\n        Map: "\\u2905",\n        map: "\\u21A6",\n        mapsto: "\\u21A6",\n        mapstodown: "\\u21A7",\n        mapstoleft: "\\u21A4",\n        mapstoup: "\\u21A5",\n        marker: "\\u25AE",\n        mcomma: "\\u2A29",\n        Mcy: "\\u041C",\n        mcy: "\\u043C",\n        mdash: "\\u2014",\n        mDDot: "\\u223A",\n        measuredangle: "\\u2221",\n        MediumSpace: "\\u205F",\n        Mellintrf: "\\u2133",\n        Mfr: "\\u{1D510}",\n        mfr: "\\u{1D52A}",\n        mho: "\\u2127",\n        micro: "\\xB5",\n        mid: "\\u2223",\n        midast: "*",\n        midcir: "\\u2AF0",\n        middot: "\\xB7",\n        minus: "\\u2212",\n        minusb: "\\u229F",\n        minusd: "\\u2238",\n        minusdu: "\\u2A2A",\n        MinusPlus: "\\u2213",\n        mlcp: "\\u2ADB",\n        mldr: "\\u2026",\n        mnplus: "\\u2213",\n        models: "\\u22A7",\n        Mopf: "\\u{1D544}",\n        mopf: "\\u{1D55E}",\n        mp: "\\u2213",\n        Mscr: "\\u2133",\n        mscr: "\\u{1D4C2}",\n        mstpos: "\\u223E",\n        Mu: "\\u039C",\n        mu: "\\u03BC",\n        multimap: "\\u22B8",\n        mumap: "\\u22B8",\n        nabla: "\\u2207",\n        Nacute: "\\u0143",\n        nacute: "\\u0144",\n        nang: "\\u2220\\u20D2",\n        nap: "\\u2249",\n        napE: "\\u2A70\\u0338",\n        napid: "\\u224B\\u0338",\n        napos: "\\u0149",\n        napprox: "\\u2249",\n        natur: "\\u266E",\n        natural: "\\u266E",\n        naturals: "\\u2115",\n        nbsp: "\\xA0",\n        nbump: "\\u224E\\u0338",\n        nbumpe: "\\u224F\\u0338",\n        ncap: "\\u2A43",\n        Ncaron: "\\u0147",\n        ncaron: "\\u0148",\n        Ncedil: "\\u0145",\n        ncedil: "\\u0146",\n        ncong: "\\u2247",\n        ncongdot: "\\u2A6D\\u0338",\n        ncup: "\\u2A42",\n        Ncy: "\\u041D",\n        ncy: "\\u043D",\n        ndash: "\\u2013",\n        ne: "\\u2260",\n        nearhk: "\\u2924",\n        neArr: "\\u21D7",\n        nearr: "\\u2197",\n        nearrow: "\\u2197",\n        nedot: "\\u2250\\u0338",\n        NegativeMediumSpace: "\\u200B",\n        NegativeThickSpace: "\\u200B",\n        NegativeThinSpace: "\\u200B",\n        NegativeVeryThinSpace: "\\u200B",\n        nequiv: "\\u2262",\n        nesear: "\\u2928",\n        nesim: "\\u2242\\u0338",\n        NestedGreaterGreater: "\\u226B",\n        NestedLessLess: "\\u226A",\n        NewLine: "\\n",\n        nexist: "\\u2204",\n        nexists: "\\u2204",\n        Nfr: "\\u{1D511}",\n        nfr: "\\u{1D52B}",\n        ngE: "\\u2267\\u0338",\n        nge: "\\u2271",\n        ngeq: "\\u2271",\n        ngeqq: "\\u2267\\u0338",\n        ngeqslant: "\\u2A7E\\u0338",\n        nges: "\\u2A7E\\u0338",\n        nGg: "\\u22D9\\u0338",\n        ngsim: "\\u2275",\n        nGt: "\\u226B\\u20D2",\n        ngt: "\\u226F",\n        ngtr: "\\u226F",\n        nGtv: "\\u226B\\u0338",\n        nhArr: "\\u21CE",\n        nharr: "\\u21AE",\n        nhpar: "\\u2AF2",\n        ni: "\\u220B",\n        nis: "\\u22FC",\n        nisd: "\\u22FA",\n        niv: "\\u220B",\n        NJcy: "\\u040A",\n        njcy: "\\u045A",\n        nlArr: "\\u21CD",\n        nlarr: "\\u219A",\n        nldr: "\\u2025",\n        nlE: "\\u2266\\u0338",\n        nle: "\\u2270",\n        nLeftarrow: "\\u21CD",\n        nleftarrow: "\\u219A",\n        nLeftrightarrow: "\\u21CE",\n        nleftrightarrow: "\\u21AE",\n        nleq: "\\u2270",\n        nleqq: "\\u2266\\u0338",\n        nleqslant: "\\u2A7D\\u0338",\n        nles: "\\u2A7D\\u0338",\n        nless: "\\u226E",\n        nLl: "\\u22D8\\u0338",\n        nlsim: "\\u2274",\n        nLt: "\\u226A\\u20D2",\n        nlt: "\\u226E",\n        nltri: "\\u22EA",\n        nltrie: "\\u22EC",\n        nLtv: "\\u226A\\u0338",\n        nmid: "\\u2224",\n        NoBreak: "\\u2060",\n        NonBreakingSpace: "\\xA0",\n        Nopf: "\\u2115",\n        nopf: "\\u{1D55F}",\n        Not: "\\u2AEC",\n        not: "\\xAC",\n        NotCongruent: "\\u2262",\n        NotCupCap: "\\u226D",\n        NotDoubleVerticalBar: "\\u2226",\n        NotElement: "\\u2209",\n        NotEqual: "\\u2260",\n        NotEqualTilde: "\\u2242\\u0338",\n        NotExists: "\\u2204",\n        NotGreater: "\\u226F",\n        NotGreaterEqual: "\\u2271",\n        NotGreaterFullEqual: "\\u2267\\u0338",\n        NotGreaterGreater: "\\u226B\\u0338",\n        NotGreaterLess: "\\u2279",\n        NotGreaterSlantEqual: "\\u2A7E\\u0338",\n        NotGreaterTilde: "\\u2275",\n        NotHumpDownHump: "\\u224E\\u0338",\n        NotHumpEqual: "\\u224F\\u0338",\n        notin: "\\u2209",\n        notindot: "\\u22F5\\u0338",\n        notinE: "\\u22F9\\u0338",\n        notinva: "\\u2209",\n        notinvb: "\\u22F7",\n        notinvc: "\\u22F6",\n        NotLeftTriangle: "\\u22EA",\n        NotLeftTriangleBar: "\\u29CF\\u0338",\n        NotLeftTriangleEqual: "\\u22EC",\n        NotLess: "\\u226E",\n        NotLessEqual: "\\u2270",\n        NotLessGreater: "\\u2278",\n        NotLessLess: "\\u226A\\u0338",\n        NotLessSlantEqual: "\\u2A7D\\u0338",\n        NotLessTilde: "\\u2274",\n        NotNestedGreaterGreater: "\\u2AA2\\u0338",\n        NotNestedLessLess: "\\u2AA1\\u0338",\n        notni: "\\u220C",\n        notniva: "\\u220C",\n        notnivb: "\\u22FE",\n        notnivc: "\\u22FD",\n        NotPrecedes: "\\u2280",\n        NotPrecedesEqual: "\\u2AAF\\u0338",\n        NotPrecedesSlantEqual: "\\u22E0",\n        NotReverseElement: "\\u220C",\n        NotRightTriangle: "\\u22EB",\n        NotRightTriangleBar: "\\u29D0\\u0338",\n        NotRightTriangleEqual: "\\u22ED",\n        NotSquareSubset: "\\u228F\\u0338",\n        NotSquareSubsetEqual: "\\u22E2",\n        NotSquareSuperset: "\\u2290\\u0338",\n        NotSquareSupersetEqual: "\\u22E3",\n        NotSubset: "\\u2282\\u20D2",\n        NotSubsetEqual: "\\u2288",\n        NotSucceeds: "\\u2281",\n        NotSucceedsEqual: "\\u2AB0\\u0338",\n        NotSucceedsSlantEqual: "\\u22E1",\n        NotSucceedsTilde: "\\u227F\\u0338",\n        NotSuperset: "\\u2283\\u20D2",\n        NotSupersetEqual: "\\u2289",\n        NotTilde: "\\u2241",\n        NotTildeEqual: "\\u2244",\n        NotTildeFullEqual: "\\u2247",\n        NotTildeTilde: "\\u2249",\n        NotVerticalBar: "\\u2224",\n        npar: "\\u2226",\n        nparallel: "\\u2226",\n        nparsl: "\\u2AFD\\u20E5",\n        npart: "\\u2202\\u0338",\n        npolint: "\\u2A14",\n        npr: "\\u2280",\n        nprcue: "\\u22E0",\n        npre: "\\u2AAF\\u0338",\n        nprec: "\\u2280",\n        npreceq: "\\u2AAF\\u0338",\n        nrArr: "\\u21CF",\n        nrarr: "\\u219B",\n        nrarrc: "\\u2933\\u0338",\n        nrarrw: "\\u219D\\u0338",\n        nRightarrow: "\\u21CF",\n        nrightarrow: "\\u219B",\n        nrtri: "\\u22EB",\n        nrtrie: "\\u22ED",\n        nsc: "\\u2281",\n        nsccue: "\\u22E1",\n        nsce: "\\u2AB0\\u0338",\n        Nscr: "\\u{1D4A9}",\n        nscr: "\\u{1D4C3}",\n        nshortmid: "\\u2224",\n        nshortparallel: "\\u2226",\n        nsim: "\\u2241",\n        nsime: "\\u2244",\n        nsimeq: "\\u2244",\n        nsmid: "\\u2224",\n        nspar: "\\u2226",\n        nsqsube: "\\u22E2",\n        nsqsupe: "\\u22E3",\n        nsub: "\\u2284",\n        nsubE: "\\u2AC5\\u0338",\n        nsube: "\\u2288",\n        nsubset: "\\u2282\\u20D2",\n        nsubseteq: "\\u2288",\n        nsubseteqq: "\\u2AC5\\u0338",\n        nsucc: "\\u2281",\n        nsucceq: "\\u2AB0\\u0338",\n        nsup: "\\u2285",\n        nsupE: "\\u2AC6\\u0338",\n        nsupe: "\\u2289",\n        nsupset: "\\u2283\\u20D2",\n        nsupseteq: "\\u2289",\n        nsupseteqq: "\\u2AC6\\u0338",\n        ntgl: "\\u2279",\n        Ntilde: "\\xD1",\n        ntilde: "\\xF1",\n        ntlg: "\\u2278",\n        ntriangleleft: "\\u22EA",\n        ntrianglelefteq: "\\u22EC",\n        ntriangleright: "\\u22EB",\n        ntrianglerighteq: "\\u22ED",\n        Nu: "\\u039D",\n        nu: "\\u03BD",\n        num: "#",\n        numero: "\\u2116",\n        numsp: "\\u2007",\n        nvap: "\\u224D\\u20D2",\n        nVDash: "\\u22AF",\n        nVdash: "\\u22AE",\n        nvDash: "\\u22AD",\n        nvdash: "\\u22AC",\n        nvge: "\\u2265\\u20D2",\n        nvgt: ">\\u20D2",\n        nvHarr: "\\u2904",\n        nvinfin: "\\u29DE",\n        nvlArr: "\\u2902",\n        nvle: "\\u2264\\u20D2",\n        nvlt: "<\\u20D2",\n        nvltrie: "\\u22B4\\u20D2",\n        nvrArr: "\\u2903",\n        nvrtrie: "\\u22B5\\u20D2",\n        nvsim: "\\u223C\\u20D2",\n        nwarhk: "\\u2923",\n        nwArr: "\\u21D6",\n        nwarr: "\\u2196",\n        nwarrow: "\\u2196",\n        nwnear: "\\u2927",\n        Oacute: "\\xD3",\n        oacute: "\\xF3",\n        oast: "\\u229B",\n        ocir: "\\u229A",\n        Ocirc: "\\xD4",\n        ocirc: "\\xF4",\n        Ocy: "\\u041E",\n        ocy: "\\u043E",\n        odash: "\\u229D",\n        Odblac: "\\u0150",\n        odblac: "\\u0151",\n        odiv: "\\u2A38",\n        odot: "\\u2299",\n        odsold: "\\u29BC",\n        OElig: "\\u0152",\n        oelig: "\\u0153",\n        ofcir: "\\u29BF",\n        Ofr: "\\u{1D512}",\n        ofr: "\\u{1D52C}",\n        ogon: "\\u02DB",\n        Ograve: "\\xD2",\n        ograve: "\\xF2",\n        ogt: "\\u29C1",\n        ohbar: "\\u29B5",\n        ohm: "\\u03A9",\n        oint: "\\u222E",\n        olarr: "\\u21BA",\n        olcir: "\\u29BE",\n        olcross: "\\u29BB",\n        oline: "\\u203E",\n        olt: "\\u29C0",\n        Omacr: "\\u014C",\n        omacr: "\\u014D",\n        Omega: "\\u03A9",\n        omega: "\\u03C9",\n        Omicron: "\\u039F",\n        omicron: "\\u03BF",\n        omid: "\\u29B6",\n        ominus: "\\u2296",\n        Oopf: "\\u{1D546}",\n        oopf: "\\u{1D560}",\n        opar: "\\u29B7",\n        OpenCurlyDoubleQuote: "\\u201C",\n        OpenCurlyQuote: "\\u2018",\n        operp: "\\u29B9",\n        oplus: "\\u2295",\n        Or: "\\u2A54",\n        or: "\\u2228",\n        orarr: "\\u21BB",\n        ord: "\\u2A5D",\n        order: "\\u2134",\n        orderof: "\\u2134",\n        ordf: "\\xAA",\n        ordm: "\\xBA",\n        origof: "\\u22B6",\n        oror: "\\u2A56",\n        orslope: "\\u2A57",\n        orv: "\\u2A5B",\n        oS: "\\u24C8",\n        Oscr: "\\u{1D4AA}",\n        oscr: "\\u2134",\n        Oslash: "\\xD8",\n        oslash: "\\xF8",\n        osol: "\\u2298",\n        Otilde: "\\xD5",\n        otilde: "\\xF5",\n        Otimes: "\\u2A37",\n        otimes: "\\u2297",\n        otimesas: "\\u2A36",\n        Ouml: "\\xD6",\n        ouml: "\\xF6",\n        ovbar: "\\u233D",\n        OverBar: "\\u203E",\n        OverBrace: "\\u23DE",\n        OverBracket: "\\u23B4",\n        OverParenthesis: "\\u23DC",\n        par: "\\u2225",\n        para: "\\xB6",\n        parallel: "\\u2225",\n        parsim: "\\u2AF3",\n        parsl: "\\u2AFD",\n        part: "\\u2202",\n        PartialD: "\\u2202",\n        Pcy: "\\u041F",\n        pcy: "\\u043F",\n        percnt: "%",\n        period: ".",\n        permil: "\\u2030",\n        perp: "\\u22A5",\n        pertenk: "\\u2031",\n        Pfr: "\\u{1D513}",\n        pfr: "\\u{1D52D}",\n        Phi: "\\u03A6",\n        phi: "\\u03C6",\n        phiv: "\\u03D5",\n        phmmat: "\\u2133",\n        phone: "\\u260E",\n        Pi: "\\u03A0",\n        pi: "\\u03C0",\n        pitchfork: "\\u22D4",\n        piv: "\\u03D6",\n        planck: "\\u210F",\n        planckh: "\\u210E",\n        plankv: "\\u210F",\n        plus: "+",\n        plusacir: "\\u2A23",\n        plusb: "\\u229E",\n        pluscir: "\\u2A22",\n        plusdo: "\\u2214",\n        plusdu: "\\u2A25",\n        pluse: "\\u2A72",\n        PlusMinus: "\\xB1",\n        plusmn: "\\xB1",\n        plussim: "\\u2A26",\n        plustwo: "\\u2A27",\n        pm: "\\xB1",\n        Poincareplane: "\\u210C",\n        pointint: "\\u2A15",\n        Popf: "\\u2119",\n        popf: "\\u{1D561}",\n        pound: "\\xA3",\n        Pr: "\\u2ABB",\n        pr: "\\u227A",\n        prap: "\\u2AB7",\n        prcue: "\\u227C",\n        prE: "\\u2AB3",\n        pre: "\\u2AAF",\n        prec: "\\u227A",\n        precapprox: "\\u2AB7",\n        preccurlyeq: "\\u227C",\n        Precedes: "\\u227A",\n        PrecedesEqual: "\\u2AAF",\n        PrecedesSlantEqual: "\\u227C",\n        PrecedesTilde: "\\u227E",\n        preceq: "\\u2AAF",\n        precnapprox: "\\u2AB9",\n        precneqq: "\\u2AB5",\n        precnsim: "\\u22E8",\n        precsim: "\\u227E",\n        Prime: "\\u2033",\n        prime: "\\u2032",\n        primes: "\\u2119",\n        prnap: "\\u2AB9",\n        prnE: "\\u2AB5",\n        prnsim: "\\u22E8",\n        prod: "\\u220F",\n        Product: "\\u220F",\n        profalar: "\\u232E",\n        profline: "\\u2312",\n        profsurf: "\\u2313",\n        prop: "\\u221D",\n        Proportion: "\\u2237",\n        Proportional: "\\u221D",\n        propto: "\\u221D",\n        prsim: "\\u227E",\n        prurel: "\\u22B0",\n        Pscr: "\\u{1D4AB}",\n        pscr: "\\u{1D4C5}",\n        Psi: "\\u03A8",\n        psi: "\\u03C8",\n        puncsp: "\\u2008",\n        Qfr: "\\u{1D514}",\n        qfr: "\\u{1D52E}",\n        qint: "\\u2A0C",\n        Qopf: "\\u211A",\n        qopf: "\\u{1D562}",\n        qprime: "\\u2057",\n        Qscr: "\\u{1D4AC}",\n        qscr: "\\u{1D4C6}",\n        quaternions: "\\u210D",\n        quatint: "\\u2A16",\n        quest: "?",\n        questeq: "\\u225F",\n        QUOT: \'"\',\n        quot: \'"\',\n        rAarr: "\\u21DB",\n        race: "\\u223D\\u0331",\n        Racute: "\\u0154",\n        racute: "\\u0155",\n        radic: "\\u221A",\n        raemptyv: "\\u29B3",\n        Rang: "\\u27EB",\n        rang: "\\u27E9",\n        rangd: "\\u2992",\n        range: "\\u29A5",\n        rangle: "\\u27E9",\n        raquo: "\\xBB",\n        Rarr: "\\u21A0",\n        rArr: "\\u21D2",\n        rarr: "\\u2192",\n        rarrap: "\\u2975",\n        rarrb: "\\u21E5",\n        rarrbfs: "\\u2920",\n        rarrc: "\\u2933",\n        rarrfs: "\\u291E",\n        rarrhk: "\\u21AA",\n        rarrlp: "\\u21AC",\n        rarrpl: "\\u2945",\n        rarrsim: "\\u2974",\n        Rarrtl: "\\u2916",\n        rarrtl: "\\u21A3",\n        rarrw: "\\u219D",\n        rAtail: "\\u291C",\n        ratail: "\\u291A",\n        ratio: "\\u2236",\n        rationals: "\\u211A",\n        RBarr: "\\u2910",\n        rBarr: "\\u290F",\n        rbarr: "\\u290D",\n        rbbrk: "\\u2773",\n        rbrace: "}",\n        rbrack: "]",\n        rbrke: "\\u298C",\n        rbrksld: "\\u298E",\n        rbrkslu: "\\u2990",\n        Rcaron: "\\u0158",\n        rcaron: "\\u0159",\n        Rcedil: "\\u0156",\n        rcedil: "\\u0157",\n        rceil: "\\u2309",\n        rcub: "}",\n        Rcy: "\\u0420",\n        rcy: "\\u0440",\n        rdca: "\\u2937",\n        rdldhar: "\\u2969",\n        rdquo: "\\u201D",\n        rdquor: "\\u201D",\n        rdsh: "\\u21B3",\n        Re: "\\u211C",\n        real: "\\u211C",\n        realine: "\\u211B",\n        realpart: "\\u211C",\n        reals: "\\u211D",\n        rect: "\\u25AD",\n        REG: "\\xAE",\n        reg: "\\xAE",\n        ReverseElement: "\\u220B",\n        ReverseEquilibrium: "\\u21CB",\n        ReverseUpEquilibrium: "\\u296F",\n        rfisht: "\\u297D",\n        rfloor: "\\u230B",\n        Rfr: "\\u211C",\n        rfr: "\\u{1D52F}",\n        rHar: "\\u2964",\n        rhard: "\\u21C1",\n        rharu: "\\u21C0",\n        rharul: "\\u296C",\n        Rho: "\\u03A1",\n        rho: "\\u03C1",\n        rhov: "\\u03F1",\n        RightAngleBracket: "\\u27E9",\n        RightArrow: "\\u2192",\n        Rightarrow: "\\u21D2",\n        rightarrow: "\\u2192",\n        RightArrowBar: "\\u21E5",\n        RightArrowLeftArrow: "\\u21C4",\n        rightarrowtail: "\\u21A3",\n        RightCeiling: "\\u2309",\n        RightDoubleBracket: "\\u27E7",\n        RightDownTeeVector: "\\u295D",\n        RightDownVector: "\\u21C2",\n        RightDownVectorBar: "\\u2955",\n        RightFloor: "\\u230B",\n        rightharpoondown: "\\u21C1",\n        rightharpoonup: "\\u21C0",\n        rightleftarrows: "\\u21C4",\n        rightleftharpoons: "\\u21CC",\n        rightrightarrows: "\\u21C9",\n        rightsquigarrow: "\\u219D",\n        RightTee: "\\u22A2",\n        RightTeeArrow: "\\u21A6",\n        RightTeeVector: "\\u295B",\n        rightthreetimes: "\\u22CC",\n        RightTriangle: "\\u22B3",\n        RightTriangleBar: "\\u29D0",\n        RightTriangleEqual: "\\u22B5",\n        RightUpDownVector: "\\u294F",\n        RightUpTeeVector: "\\u295C",\n        RightUpVector: "\\u21BE",\n        RightUpVectorBar: "\\u2954",\n        RightVector: "\\u21C0",\n        RightVectorBar: "\\u2953",\n        ring: "\\u02DA",\n        risingdotseq: "\\u2253",\n        rlarr: "\\u21C4",\n        rlhar: "\\u21CC",\n        rlm: "\\u200F",\n        rmoust: "\\u23B1",\n        rmoustache: "\\u23B1",\n        rnmid: "\\u2AEE",\n        roang: "\\u27ED",\n        roarr: "\\u21FE",\n        robrk: "\\u27E7",\n        ropar: "\\u2986",\n        Ropf: "\\u211D",\n        ropf: "\\u{1D563}",\n        roplus: "\\u2A2E",\n        rotimes: "\\u2A35",\n        RoundImplies: "\\u2970",\n        rpar: ")",\n        rpargt: "\\u2994",\n        rppolint: "\\u2A12",\n        rrarr: "\\u21C9",\n        Rrightarrow: "\\u21DB",\n        rsaquo: "\\u203A",\n        Rscr: "\\u211B",\n        rscr: "\\u{1D4C7}",\n        Rsh: "\\u21B1",\n        rsh: "\\u21B1",\n        rsqb: "]",\n        rsquo: "\\u2019",\n        rsquor: "\\u2019",\n        rthree: "\\u22CC",\n        rtimes: "\\u22CA",\n        rtri: "\\u25B9",\n        rtrie: "\\u22B5",\n        rtrif: "\\u25B8",\n        rtriltri: "\\u29CE",\n        RuleDelayed: "\\u29F4",\n        ruluhar: "\\u2968",\n        rx: "\\u211E",\n        Sacute: "\\u015A",\n        sacute: "\\u015B",\n        sbquo: "\\u201A",\n        Sc: "\\u2ABC",\n        sc: "\\u227B",\n        scap: "\\u2AB8",\n        Scaron: "\\u0160",\n        scaron: "\\u0161",\n        sccue: "\\u227D",\n        scE: "\\u2AB4",\n        sce: "\\u2AB0",\n        Scedil: "\\u015E",\n        scedil: "\\u015F",\n        Scirc: "\\u015C",\n        scirc: "\\u015D",\n        scnap: "\\u2ABA",\n        scnE: "\\u2AB6",\n        scnsim: "\\u22E9",\n        scpolint: "\\u2A13",\n        scsim: "\\u227F",\n        Scy: "\\u0421",\n        scy: "\\u0441",\n        sdot: "\\u22C5",\n        sdotb: "\\u22A1",\n        sdote: "\\u2A66",\n        searhk: "\\u2925",\n        seArr: "\\u21D8",\n        searr: "\\u2198",\n        searrow: "\\u2198",\n        sect: "\\xA7",\n        semi: ";",\n        seswar: "\\u2929",\n        setminus: "\\u2216",\n        setmn: "\\u2216",\n        sext: "\\u2736",\n        Sfr: "\\u{1D516}",\n        sfr: "\\u{1D530}",\n        sfrown: "\\u2322",\n        sharp: "\\u266F",\n        SHCHcy: "\\u0429",\n        shchcy: "\\u0449",\n        SHcy: "\\u0428",\n        shcy: "\\u0448",\n        ShortDownArrow: "\\u2193",\n        ShortLeftArrow: "\\u2190",\n        shortmid: "\\u2223",\n        shortparallel: "\\u2225",\n        ShortRightArrow: "\\u2192",\n        ShortUpArrow: "\\u2191",\n        shy: "\\xAD",\n        Sigma: "\\u03A3",\n        sigma: "\\u03C3",\n        sigmaf: "\\u03C2",\n        sigmav: "\\u03C2",\n        sim: "\\u223C",\n        simdot: "\\u2A6A",\n        sime: "\\u2243",\n        simeq: "\\u2243",\n        simg: "\\u2A9E",\n        simgE: "\\u2AA0",\n        siml: "\\u2A9D",\n        simlE: "\\u2A9F",\n        simne: "\\u2246",\n        simplus: "\\u2A24",\n        simrarr: "\\u2972",\n        slarr: "\\u2190",\n        SmallCircle: "\\u2218",\n        smallsetminus: "\\u2216",\n        smashp: "\\u2A33",\n        smeparsl: "\\u29E4",\n        smid: "\\u2223",\n        smile: "\\u2323",\n        smt: "\\u2AAA",\n        smte: "\\u2AAC",\n        smtes: "\\u2AAC\\uFE00",\n        SOFTcy: "\\u042C",\n        softcy: "\\u044C",\n        sol: "/",\n        solb: "\\u29C4",\n        solbar: "\\u233F",\n        Sopf: "\\u{1D54A}",\n        sopf: "\\u{1D564}",\n        spades: "\\u2660",\n        spadesuit: "\\u2660",\n        spar: "\\u2225",\n        sqcap: "\\u2293",\n        sqcaps: "\\u2293\\uFE00",\n        sqcup: "\\u2294",\n        sqcups: "\\u2294\\uFE00",\n        Sqrt: "\\u221A",\n        sqsub: "\\u228F",\n        sqsube: "\\u2291",\n        sqsubset: "\\u228F",\n        sqsubseteq: "\\u2291",\n        sqsup: "\\u2290",\n        sqsupe: "\\u2292",\n        sqsupset: "\\u2290",\n        sqsupseteq: "\\u2292",\n        squ: "\\u25A1",\n        Square: "\\u25A1",\n        square: "\\u25A1",\n        SquareIntersection: "\\u2293",\n        SquareSubset: "\\u228F",\n        SquareSubsetEqual: "\\u2291",\n        SquareSuperset: "\\u2290",\n        SquareSupersetEqual: "\\u2292",\n        SquareUnion: "\\u2294",\n        squarf: "\\u25AA",\n        squf: "\\u25AA",\n        srarr: "\\u2192",\n        Sscr: "\\u{1D4AE}",\n        sscr: "\\u{1D4C8}",\n        ssetmn: "\\u2216",\n        ssmile: "\\u2323",\n        sstarf: "\\u22C6",\n        Star: "\\u22C6",\n        star: "\\u2606",\n        starf: "\\u2605",\n        straightepsilon: "\\u03F5",\n        straightphi: "\\u03D5",\n        strns: "\\xAF",\n        Sub: "\\u22D0",\n        sub: "\\u2282",\n        subdot: "\\u2ABD",\n        subE: "\\u2AC5",\n        sube: "\\u2286",\n        subedot: "\\u2AC3",\n        submult: "\\u2AC1",\n        subnE: "\\u2ACB",\n        subne: "\\u228A",\n        subplus: "\\u2ABF",\n        subrarr: "\\u2979",\n        Subset: "\\u22D0",\n        subset: "\\u2282",\n        subseteq: "\\u2286",\n        subseteqq: "\\u2AC5",\n        SubsetEqual: "\\u2286",\n        subsetneq: "\\u228A",\n        subsetneqq: "\\u2ACB",\n        subsim: "\\u2AC7",\n        subsub: "\\u2AD5",\n        subsup: "\\u2AD3",\n        succ: "\\u227B",\n        succapprox: "\\u2AB8",\n        succcurlyeq: "\\u227D",\n        Succeeds: "\\u227B",\n        SucceedsEqual: "\\u2AB0",\n        SucceedsSlantEqual: "\\u227D",\n        SucceedsTilde: "\\u227F",\n        succeq: "\\u2AB0",\n        succnapprox: "\\u2ABA",\n        succneqq: "\\u2AB6",\n        succnsim: "\\u22E9",\n        succsim: "\\u227F",\n        SuchThat: "\\u220B",\n        Sum: "\\u2211",\n        sum: "\\u2211",\n        sung: "\\u266A",\n        Sup: "\\u22D1",\n        sup: "\\u2283",\n        sup1: "\\xB9",\n        sup2: "\\xB2",\n        sup3: "\\xB3",\n        supdot: "\\u2ABE",\n        supdsub: "\\u2AD8",\n        supE: "\\u2AC6",\n        supe: "\\u2287",\n        supedot: "\\u2AC4",\n        Superset: "\\u2283",\n        SupersetEqual: "\\u2287",\n        suphsol: "\\u27C9",\n        suphsub: "\\u2AD7",\n        suplarr: "\\u297B",\n        supmult: "\\u2AC2",\n        supnE: "\\u2ACC",\n        supne: "\\u228B",\n        supplus: "\\u2AC0",\n        Supset: "\\u22D1",\n        supset: "\\u2283",\n        supseteq: "\\u2287",\n        supseteqq: "\\u2AC6",\n        supsetneq: "\\u228B",\n        supsetneqq: "\\u2ACC",\n        supsim: "\\u2AC8",\n        supsub: "\\u2AD4",\n        supsup: "\\u2AD6",\n        swarhk: "\\u2926",\n        swArr: "\\u21D9",\n        swarr: "\\u2199",\n        swarrow: "\\u2199",\n        swnwar: "\\u292A",\n        szlig: "\\xDF",\n        Tab: "	",\n        target: "\\u2316",\n        Tau: "\\u03A4",\n        tau: "\\u03C4",\n        tbrk: "\\u23B4",\n        Tcaron: "\\u0164",\n        tcaron: "\\u0165",\n        Tcedil: "\\u0162",\n        tcedil: "\\u0163",\n        Tcy: "\\u0422",\n        tcy: "\\u0442",\n        tdot: "\\u20DB",\n        telrec: "\\u2315",\n        Tfr: "\\u{1D517}",\n        tfr: "\\u{1D531}",\n        there4: "\\u2234",\n        Therefore: "\\u2234",\n        therefore: "\\u2234",\n        Theta: "\\u0398",\n        theta: "\\u03B8",\n        thetasym: "\\u03D1",\n        thetav: "\\u03D1",\n        thickapprox: "\\u2248",\n        thicksim: "\\u223C",\n        ThickSpace: "\\u205F\\u200A",\n        thinsp: "\\u2009",\n        ThinSpace: "\\u2009",\n        thkap: "\\u2248",\n        thksim: "\\u223C",\n        THORN: "\\xDE",\n        thorn: "\\xFE",\n        Tilde: "\\u223C",\n        tilde: "\\u02DC",\n        TildeEqual: "\\u2243",\n        TildeFullEqual: "\\u2245",\n        TildeTilde: "\\u2248",\n        times: "\\xD7",\n        timesb: "\\u22A0",\n        timesbar: "\\u2A31",\n        timesd: "\\u2A30",\n        tint: "\\u222D",\n        toea: "\\u2928",\n        top: "\\u22A4",\n        topbot: "\\u2336",\n        topcir: "\\u2AF1",\n        Topf: "\\u{1D54B}",\n        topf: "\\u{1D565}",\n        topfork: "\\u2ADA",\n        tosa: "\\u2929",\n        tprime: "\\u2034",\n        TRADE: "\\u2122",\n        trade: "\\u2122",\n        triangle: "\\u25B5",\n        triangledown: "\\u25BF",\n        triangleleft: "\\u25C3",\n        trianglelefteq: "\\u22B4",\n        triangleq: "\\u225C",\n        triangleright: "\\u25B9",\n        trianglerighteq: "\\u22B5",\n        tridot: "\\u25EC",\n        trie: "\\u225C",\n        triminus: "\\u2A3A",\n        TripleDot: "\\u20DB",\n        triplus: "\\u2A39",\n        trisb: "\\u29CD",\n        tritime: "\\u2A3B",\n        trpezium: "\\u23E2",\n        Tscr: "\\u{1D4AF}",\n        tscr: "\\u{1D4C9}",\n        TScy: "\\u0426",\n        tscy: "\\u0446",\n        TSHcy: "\\u040B",\n        tshcy: "\\u045B",\n        Tstrok: "\\u0166",\n        tstrok: "\\u0167",\n        twixt: "\\u226C",\n        twoheadleftarrow: "\\u219E",\n        twoheadrightarrow: "\\u21A0",\n        Uacute: "\\xDA",\n        uacute: "\\xFA",\n        Uarr: "\\u219F",\n        uArr: "\\u21D1",\n        uarr: "\\u2191",\n        Uarrocir: "\\u2949",\n        Ubrcy: "\\u040E",\n        ubrcy: "\\u045E",\n        Ubreve: "\\u016C",\n        ubreve: "\\u016D",\n        Ucirc: "\\xDB",\n        ucirc: "\\xFB",\n        Ucy: "\\u0423",\n        ucy: "\\u0443",\n        udarr: "\\u21C5",\n        Udblac: "\\u0170",\n        udblac: "\\u0171",\n        udhar: "\\u296E",\n        ufisht: "\\u297E",\n        Ufr: "\\u{1D518}",\n        ufr: "\\u{1D532}",\n        Ugrave: "\\xD9",\n        ugrave: "\\xF9",\n        uHar: "\\u2963",\n        uharl: "\\u21BF",\n        uharr: "\\u21BE",\n        uhblk: "\\u2580",\n        ulcorn: "\\u231C",\n        ulcorner: "\\u231C",\n        ulcrop: "\\u230F",\n        ultri: "\\u25F8",\n        Umacr: "\\u016A",\n        umacr: "\\u016B",\n        uml: "\\xA8",\n        UnderBar: "_",\n        UnderBrace: "\\u23DF",\n        UnderBracket: "\\u23B5",\n        UnderParenthesis: "\\u23DD",\n        Union: "\\u22C3",\n        UnionPlus: "\\u228E",\n        Uogon: "\\u0172",\n        uogon: "\\u0173",\n        Uopf: "\\u{1D54C}",\n        uopf: "\\u{1D566}",\n        UpArrow: "\\u2191",\n        Uparrow: "\\u21D1",\n        uparrow: "\\u2191",\n        UpArrowBar: "\\u2912",\n        UpArrowDownArrow: "\\u21C5",\n        UpDownArrow: "\\u2195",\n        Updownarrow: "\\u21D5",\n        updownarrow: "\\u2195",\n        UpEquilibrium: "\\u296E",\n        upharpoonleft: "\\u21BF",\n        upharpoonright: "\\u21BE",\n        uplus: "\\u228E",\n        UpperLeftArrow: "\\u2196",\n        UpperRightArrow: "\\u2197",\n        Upsi: "\\u03D2",\n        upsi: "\\u03C5",\n        upsih: "\\u03D2",\n        Upsilon: "\\u03A5",\n        upsilon: "\\u03C5",\n        UpTee: "\\u22A5",\n        UpTeeArrow: "\\u21A5",\n        upuparrows: "\\u21C8",\n        urcorn: "\\u231D",\n        urcorner: "\\u231D",\n        urcrop: "\\u230E",\n        Uring: "\\u016E",\n        uring: "\\u016F",\n        urtri: "\\u25F9",\n        Uscr: "\\u{1D4B0}",\n        uscr: "\\u{1D4CA}",\n        utdot: "\\u22F0",\n        Utilde: "\\u0168",\n        utilde: "\\u0169",\n        utri: "\\u25B5",\n        utrif: "\\u25B4",\n        uuarr: "\\u21C8",\n        Uuml: "\\xDC",\n        uuml: "\\xFC",\n        uwangle: "\\u29A7",\n        vangrt: "\\u299C",\n        varepsilon: "\\u03F5",\n        varkappa: "\\u03F0",\n        varnothing: "\\u2205",\n        varphi: "\\u03D5",\n        varpi: "\\u03D6",\n        varpropto: "\\u221D",\n        vArr: "\\u21D5",\n        varr: "\\u2195",\n        varrho: "\\u03F1",\n        varsigma: "\\u03C2",\n        varsubsetneq: "\\u228A\\uFE00",\n        varsubsetneqq: "\\u2ACB\\uFE00",\n        varsupsetneq: "\\u228B\\uFE00",\n        varsupsetneqq: "\\u2ACC\\uFE00",\n        vartheta: "\\u03D1",\n        vartriangleleft: "\\u22B2",\n        vartriangleright: "\\u22B3",\n        Vbar: "\\u2AEB",\n        vBar: "\\u2AE8",\n        vBarv: "\\u2AE9",\n        Vcy: "\\u0412",\n        vcy: "\\u0432",\n        VDash: "\\u22AB",\n        Vdash: "\\u22A9",\n        vDash: "\\u22A8",\n        vdash: "\\u22A2",\n        Vdashl: "\\u2AE6",\n        Vee: "\\u22C1",\n        vee: "\\u2228",\n        veebar: "\\u22BB",\n        veeeq: "\\u225A",\n        vellip: "\\u22EE",\n        Verbar: "\\u2016",\n        verbar: "|",\n        Vert: "\\u2016",\n        vert: "|",\n        VerticalBar: "\\u2223",\n        VerticalLine: "|",\n        VerticalSeparator: "\\u2758",\n        VerticalTilde: "\\u2240",\n        VeryThinSpace: "\\u200A",\n        Vfr: "\\u{1D519}",\n        vfr: "\\u{1D533}",\n        vltri: "\\u22B2",\n        vnsub: "\\u2282\\u20D2",\n        vnsup: "\\u2283\\u20D2",\n        Vopf: "\\u{1D54D}",\n        vopf: "\\u{1D567}",\n        vprop: "\\u221D",\n        vrtri: "\\u22B3",\n        Vscr: "\\u{1D4B1}",\n        vscr: "\\u{1D4CB}",\n        vsubnE: "\\u2ACB\\uFE00",\n        vsubne: "\\u228A\\uFE00",\n        vsupnE: "\\u2ACC\\uFE00",\n        vsupne: "\\u228B\\uFE00",\n        Vvdash: "\\u22AA",\n        vzigzag: "\\u299A",\n        Wcirc: "\\u0174",\n        wcirc: "\\u0175",\n        wedbar: "\\u2A5F",\n        Wedge: "\\u22C0",\n        wedge: "\\u2227",\n        wedgeq: "\\u2259",\n        weierp: "\\u2118",\n        Wfr: "\\u{1D51A}",\n        wfr: "\\u{1D534}",\n        Wopf: "\\u{1D54E}",\n        wopf: "\\u{1D568}",\n        wp: "\\u2118",\n        wr: "\\u2240",\n        wreath: "\\u2240",\n        Wscr: "\\u{1D4B2}",\n        wscr: "\\u{1D4CC}",\n        xcap: "\\u22C2",\n        xcirc: "\\u25EF",\n        xcup: "\\u22C3",\n        xdtri: "\\u25BD",\n        Xfr: "\\u{1D51B}",\n        xfr: "\\u{1D535}",\n        xhArr: "\\u27FA",\n        xharr: "\\u27F7",\n        Xi: "\\u039E",\n        xi: "\\u03BE",\n        xlArr: "\\u27F8",\n        xlarr: "\\u27F5",\n        xmap: "\\u27FC",\n        xnis: "\\u22FB",\n        xodot: "\\u2A00",\n        Xopf: "\\u{1D54F}",\n        xopf: "\\u{1D569}",\n        xoplus: "\\u2A01",\n        xotime: "\\u2A02",\n        xrArr: "\\u27F9",\n        xrarr: "\\u27F6",\n        Xscr: "\\u{1D4B3}",\n        xscr: "\\u{1D4CD}",\n        xsqcup: "\\u2A06",\n        xuplus: "\\u2A04",\n        xutri: "\\u25B3",\n        xvee: "\\u22C1",\n        xwedge: "\\u22C0",\n        Yacute: "\\xDD",\n        yacute: "\\xFD",\n        YAcy: "\\u042F",\n        yacy: "\\u044F",\n        Ycirc: "\\u0176",\n        ycirc: "\\u0177",\n        Ycy: "\\u042B",\n        ycy: "\\u044B",\n        yen: "\\xA5",\n        Yfr: "\\u{1D51C}",\n        yfr: "\\u{1D536}",\n        YIcy: "\\u0407",\n        yicy: "\\u0457",\n        Yopf: "\\u{1D550}",\n        yopf: "\\u{1D56A}",\n        Yscr: "\\u{1D4B4}",\n        yscr: "\\u{1D4CE}",\n        YUcy: "\\u042E",\n        yucy: "\\u044E",\n        Yuml: "\\u0178",\n        yuml: "\\xFF",\n        Zacute: "\\u0179",\n        zacute: "\\u017A",\n        Zcaron: "\\u017D",\n        zcaron: "\\u017E",\n        Zcy: "\\u0417",\n        zcy: "\\u0437",\n        Zdot: "\\u017B",\n        zdot: "\\u017C",\n        zeetrf: "\\u2128",\n        ZeroWidthSpace: "\\u200B",\n        Zeta: "\\u0396",\n        zeta: "\\u03B6",\n        Zfr: "\\u2128",\n        zfr: "\\u{1D537}",\n        ZHcy: "\\u0416",\n        zhcy: "\\u0436",\n        zigrarr: "\\u21DD",\n        Zopf: "\\u2124",\n        zopf: "\\u{1D56B}",\n        Zscr: "\\u{1D4B5}",\n        zscr: "\\u{1D4CF}",\n        zwj: "\\u200D",\n        zwnj: "\\u200C"\n      });\n      exports2.entityMap = exports2.HTML_ENTITIES;\n    }\n  });\n\n  // node_modules/@xmldom/xmldom/lib/sax.js\n  var require_sax = __commonJS({\n    "node_modules/@xmldom/xmldom/lib/sax.js"(exports2) {\n      "use strict";\n      var conventions = require_conventions();\n      var g = require_grammar();\n      var errors = require_errors2();\n      var isHTMLEscapableRawTextElement = conventions.isHTMLEscapableRawTextElement;\n      var isHTMLMimeType = conventions.isHTMLMimeType;\n      var isHTMLRawTextElement = conventions.isHTMLRawTextElement;\n      var hasOwn = conventions.hasOwn;\n      var NAMESPACE = conventions.NAMESPACE;\n      var ParseError = errors.ParseError;\n      var DOMException = errors.DOMException;\n      var S_TAG = 0;\n      var S_ATTR = 1;\n      var S_ATTR_SPACE = 2;\n      var S_EQ = 3;\n      var S_ATTR_NOQUOT_VALUE = 4;\n      var S_ATTR_END = 5;\n      var S_TAG_SPACE = 6;\n      var S_TAG_CLOSE = 7;\n      function XMLReader() {\n      }\n      XMLReader.prototype = {\n        parse: function(source, defaultNSMap, entityMap) {\n          var domBuilder = this.domBuilder;\n          domBuilder.startDocument();\n          _copy(defaultNSMap, defaultNSMap = /* @__PURE__ */ Object.create(null));\n          parse(source, defaultNSMap, entityMap, domBuilder, this.errorHandler);\n          domBuilder.endDocument();\n        }\n      };\n      var ENTITY_REG = /&#?\\w+;?/g;\n      function parse(source, defaultNSMapCopy, entityMap, domBuilder, errorHandler) {\n        var isHTML = isHTMLMimeType(domBuilder.mimeType);\n        if (source.indexOf(g.UNICODE_REPLACEMENT_CHARACTER) >= 0) {\n          errorHandler.warning("Unicode replacement character detected, source encoding issues?");\n        }\n        function fixedFromCharCode(code) {\n          if (code > 65535) {\n            code -= 65536;\n            var surrogate1 = 55296 + (code >> 10), surrogate2 = 56320 + (code & 1023);\n            return String.fromCharCode(surrogate1, surrogate2);\n          } else {\n            return String.fromCharCode(code);\n          }\n        }\n        function entityReplacer(a2) {\n          var complete = a2[a2.length - 1] === ";" ? a2 : a2 + ";";\n          if (!isHTML && complete !== a2) {\n            errorHandler.error("EntityRef: expecting ;");\n            return a2;\n          }\n          var match = g.Reference.exec(complete);\n          if (!match || match[0].length !== complete.length) {\n            errorHandler.error("entity not matching Reference production: " + a2);\n            return a2;\n          }\n          var k = complete.slice(1, -1);\n          if (hasOwn(entityMap, k)) {\n            return entityMap[k];\n          } else if (k.charAt(0) === "#") {\n            return fixedFromCharCode(parseInt(k.substring(1).replace("x", "0x")));\n          } else {\n            errorHandler.error("entity not found:" + a2);\n            return a2;\n          }\n        }\n        function appendText(end2) {\n          if (end2 > start) {\n            var xt = source.substring(start, end2).replace(ENTITY_REG, entityReplacer);\n            locator && position(start);\n            domBuilder.characters(xt, 0, end2 - start);\n            start = end2;\n          }\n        }\n        var lineStart = 0;\n        var lineEnd = 0;\n        var linePattern = /\\r\\n?|\\n|$/g;\n        var locator = domBuilder.locator;\n        function position(p, m) {\n          while (p >= lineEnd && (m = linePattern.exec(source))) {\n            lineStart = lineEnd;\n            lineEnd = m.index + m[0].length;\n            locator.lineNumber++;\n          }\n          locator.columnNumber = p - lineStart + 1;\n        }\n        var parseStack = [{ currentNSMap: defaultNSMapCopy }];\n        var unclosedTags = [];\n        var start = 0;\n        while (true) {\n          try {\n            var tagStart = source.indexOf("<", start);\n            if (tagStart < 0) {\n              if (!isHTML && unclosedTags.length > 0) {\n                return errorHandler.fatalError("unclosed xml tag(s): " + unclosedTags.join(", "));\n              }\n              if (!source.substring(start).match(/^\\s*$/)) {\n                var doc = domBuilder.doc;\n                var text = doc.createTextNode(source.substring(start));\n                if (doc.documentElement) {\n                  return errorHandler.error("Extra content at the end of the document");\n                }\n                doc.appendChild(text);\n                domBuilder.currentElement = text;\n              }\n              return;\n            }\n            if (tagStart > start) {\n              var fromSource = source.substring(start, tagStart);\n              if (!isHTML && unclosedTags.length === 0) {\n                fromSource = fromSource.replace(new RegExp(g.S_OPT.source, "g"), "");\n                fromSource && errorHandler.error("Unexpected content outside root element: \'" + fromSource + "\'");\n              }\n              appendText(tagStart);\n            }\n            switch (source.charAt(tagStart + 1)) {\n              case "/":\n                var end = source.indexOf(">", tagStart + 2);\n                var tagNameRaw = source.substring(tagStart + 2, end > 0 ? end : void 0);\n                if (!tagNameRaw) {\n                  return errorHandler.fatalError("end tag name missing");\n                }\n                var tagNameMatch = end > 0 && g.reg("^", g.QName_group, g.S_OPT, "$").exec(tagNameRaw);\n                if (!tagNameMatch) {\n                  return errorHandler.fatalError(\'end tag name contains invalid characters: "\' + tagNameRaw + \'"\');\n                }\n                if (!domBuilder.currentElement && !domBuilder.doc.documentElement) {\n                  return;\n                }\n                var currentTagName = unclosedTags[unclosedTags.length - 1] || domBuilder.currentElement.tagName || domBuilder.doc.documentElement.tagName || "";\n                if (currentTagName !== tagNameMatch[1]) {\n                  var tagNameLower = tagNameMatch[1].toLowerCase();\n                  if (!isHTML || currentTagName.toLowerCase() !== tagNameLower) {\n                    return errorHandler.fatalError(\'Opening and ending tag mismatch: "\' + currentTagName + \'" != "\' + tagNameRaw + \'"\');\n                  }\n                }\n                var config = parseStack.pop();\n                unclosedTags.pop();\n                var localNSMap = config.localNSMap;\n                domBuilder.endElement(config.uri, config.localName, currentTagName);\n                if (localNSMap) {\n                  for (var prefix in localNSMap) {\n                    if (hasOwn(localNSMap, prefix)) {\n                      domBuilder.endPrefixMapping(prefix);\n                    }\n                  }\n                }\n                end++;\n                break;\n              // end element\n              case "?":\n                locator && position(tagStart);\n                end = parseProcessingInstruction(source, tagStart, domBuilder, errorHandler);\n                break;\n              case "!":\n                locator && position(tagStart);\n                end = parseDoctypeCommentOrCData(source, tagStart, domBuilder, errorHandler, isHTML);\n                break;\n              default:\n                locator && position(tagStart);\n                var el = new ElementAttributes();\n                var currentNSMap = parseStack[parseStack.length - 1].currentNSMap;\n                var end = parseElementStartPart(source, tagStart, el, currentNSMap, entityReplacer, errorHandler, isHTML);\n                var len = el.length;\n                if (!el.closed) {\n                  if (isHTML && conventions.isHTMLVoidElement(el.tagName)) {\n                    el.closed = true;\n                  } else {\n                    unclosedTags.push(el.tagName);\n                  }\n                }\n                if (locator && len) {\n                  var locator2 = copyLocator(locator, {});\n                  for (var i = 0; i < len; i++) {\n                    var a = el[i];\n                    position(a.offset);\n                    a.locator = copyLocator(locator, {});\n                  }\n                  domBuilder.locator = locator2;\n                  if (appendElement(el, domBuilder, currentNSMap)) {\n                    parseStack.push(el);\n                  }\n                  domBuilder.locator = locator;\n                } else {\n                  if (appendElement(el, domBuilder, currentNSMap)) {\n                    parseStack.push(el);\n                  }\n                }\n                if (isHTML && !el.closed) {\n                  end = parseHtmlSpecialContent(source, end, el.tagName, entityReplacer, domBuilder);\n                } else {\n                  end++;\n                }\n            }\n          } catch (e) {\n            if (e instanceof ParseError) {\n              throw e;\n            } else if (e instanceof DOMException) {\n              throw new ParseError(e.name + ": " + e.message, domBuilder.locator, e);\n            }\n            errorHandler.error("element parse error: " + e);\n            end = -1;\n          }\n          if (end > start) {\n            start = end;\n          } else {\n            appendText(Math.max(tagStart, start) + 1);\n          }\n        }\n      }\n      function copyLocator(f, t) {\n        t.lineNumber = f.lineNumber;\n        t.columnNumber = f.columnNumber;\n        return t;\n      }\n      function parseElementStartPart(source, start, el, currentNSMap, entityReplacer, errorHandler, isHTML) {\n        function addAttribute(qname, value2, startIndex) {\n          if (hasOwn(el.attributeNames, qname)) {\n            return errorHandler.fatalError("Attribute " + qname + " redefined");\n          }\n          if (!isHTML && value2.indexOf("<") >= 0) {\n            return errorHandler.fatalError("Unescaped \'<\' not allowed in attributes values");\n          }\n          el.addValue(\n            qname,\n            // @see https://www.w3.org/TR/xml/#AVNormalize\n            // since the xmldom sax parser does not "interpret" DTD the following is not implemented:\n            // - recursive replacement of (DTD) entity references\n            // - trimming and collapsing multiple spaces into a single one for attributes that are not of type CDATA\n            value2.replace(/[\\t\\n\\r]/g, " ").replace(ENTITY_REG, entityReplacer),\n            startIndex\n          );\n        }\n        var attrName;\n        var value;\n        var p = ++start;\n        var s = S_TAG;\n        while (true) {\n          var c = source.charAt(p);\n          switch (c) {\n            case "=":\n              if (s === S_ATTR) {\n                attrName = source.slice(start, p);\n                s = S_EQ;\n              } else if (s === S_ATTR_SPACE) {\n                s = S_EQ;\n              } else {\n                throw new Error("attribute equal must after attrName");\n              }\n              break;\n            case "\'":\n            case \'"\':\n              if (s === S_EQ || s === S_ATTR) {\n                if (s === S_ATTR) {\n                  errorHandler.warning(\'attribute value must after "="\');\n                  attrName = source.slice(start, p);\n                }\n                start = p + 1;\n                p = source.indexOf(c, start);\n                if (p > 0) {\n                  value = source.slice(start, p);\n                  addAttribute(attrName, value, start - 1);\n                  s = S_ATTR_END;\n                } else {\n                  throw new Error("attribute value no end \'" + c + "\' match");\n                }\n              } else if (s == S_ATTR_NOQUOT_VALUE) {\n                value = source.slice(start, p);\n                addAttribute(attrName, value, start);\n                errorHandler.warning(\'attribute "\' + attrName + \'" missed start quot(\' + c + ")!!");\n                start = p + 1;\n                s = S_ATTR_END;\n              } else {\n                throw new Error(\'attribute value must after "="\');\n              }\n              break;\n            case "/":\n              switch (s) {\n                case S_TAG:\n                  el.setTagName(source.slice(start, p));\n                case S_ATTR_END:\n                case S_TAG_SPACE:\n                case S_TAG_CLOSE:\n                  s = S_TAG_CLOSE;\n                  el.closed = true;\n                case S_ATTR_NOQUOT_VALUE:\n                case S_ATTR:\n                  break;\n                case S_ATTR_SPACE:\n                  el.closed = true;\n                  break;\n                //case S_EQ:\n                default:\n                  throw new Error("attribute invalid close char(\'/\')");\n              }\n              break;\n            case "":\n              errorHandler.error("unexpected end of input");\n              if (s == S_TAG) {\n                el.setTagName(source.slice(start, p));\n              }\n              return p;\n            case ">":\n              switch (s) {\n                case S_TAG:\n                  el.setTagName(source.slice(start, p));\n                case S_ATTR_END:\n                case S_TAG_SPACE:\n                case S_TAG_CLOSE:\n                  break;\n                //normal\n                case S_ATTR_NOQUOT_VALUE:\n                //Compatible state\n                case S_ATTR:\n                  value = source.slice(start, p);\n                  if (value.slice(-1) === "/") {\n                    el.closed = true;\n                    value = value.slice(0, -1);\n                  }\n                case S_ATTR_SPACE:\n                  if (s === S_ATTR_SPACE) {\n                    value = attrName;\n                  }\n                  if (s == S_ATTR_NOQUOT_VALUE) {\n                    errorHandler.warning(\'attribute "\' + value + \'" missed quot(")!\');\n                    addAttribute(attrName, value, start);\n                  } else {\n                    if (!isHTML) {\n                      errorHandler.warning(\'attribute "\' + value + \'" missed value!! "\' + value + \'" instead!!\');\n                    }\n                    addAttribute(value, value, start);\n                  }\n                  break;\n                case S_EQ:\n                  if (!isHTML) {\n                    return errorHandler.fatalError(`AttValue: \' or " expected`);\n                  }\n              }\n              return p;\n            /*xml space \'\\x20\' | #x9 | #xD | #xA; */\n            case "\\x80":\n              c = " ";\n            default:\n              if (c <= " ") {\n                switch (s) {\n                  case S_TAG:\n                    el.setTagName(source.slice(start, p));\n                    s = S_TAG_SPACE;\n                    break;\n                  case S_ATTR:\n                    attrName = source.slice(start, p);\n                    s = S_ATTR_SPACE;\n                    break;\n                  case S_ATTR_NOQUOT_VALUE:\n                    var value = source.slice(start, p);\n                    errorHandler.warning(\'attribute "\' + value + \'" missed quot(")!!\');\n                    addAttribute(attrName, value, start);\n                  case S_ATTR_END:\n                    s = S_TAG_SPACE;\n                    break;\n                }\n              } else {\n                switch (s) {\n                  //case S_TAG:void();break;\n                  //case S_ATTR:void();break;\n                  //case S_ATTR_NOQUOT_VALUE:void();break;\n                  case S_ATTR_SPACE:\n                    if (!isHTML) {\n                      errorHandler.warning(\'attribute "\' + attrName + \'" missed value!! "\' + attrName + \'" instead2!!\');\n                    }\n                    addAttribute(attrName, attrName, start);\n                    start = p;\n                    s = S_ATTR;\n                    break;\n                  case S_ATTR_END:\n                    errorHandler.warning(\'attribute space is required"\' + attrName + \'"!!\');\n                  case S_TAG_SPACE:\n                    s = S_ATTR;\n                    start = p;\n                    break;\n                  case S_EQ:\n                    s = S_ATTR_NOQUOT_VALUE;\n                    start = p;\n                    break;\n                  case S_TAG_CLOSE:\n                    throw new Error("elements closed character \'/\' and \'>\' must be connected to");\n                }\n              }\n          }\n          p++;\n        }\n      }\n      function appendElement(el, domBuilder, currentNSMap) {\n        var tagName = el.tagName;\n        var localNSMap = null;\n        var i = el.length;\n        while (i--) {\n          var a = el[i];\n          var qName = a.qName;\n          var value = a.value;\n          var nsp = qName.indexOf(":");\n          if (nsp > 0) {\n            var prefix = a.prefix = qName.slice(0, nsp);\n            var localName = qName.slice(nsp + 1);\n            var nsPrefix = prefix === "xmlns" && localName;\n          } else {\n            localName = qName;\n            prefix = null;\n            nsPrefix = qName === "xmlns" && "";\n          }\n          a.localName = localName;\n          if (nsPrefix !== false) {\n            if (localNSMap == null) {\n              localNSMap = /* @__PURE__ */ Object.create(null);\n              _copy(currentNSMap, currentNSMap = /* @__PURE__ */ Object.create(null));\n            }\n            currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;\n            a.uri = NAMESPACE.XMLNS;\n            domBuilder.startPrefixMapping(nsPrefix, value);\n          }\n        }\n        var i = el.length;\n        while (i--) {\n          a = el[i];\n          if (a.prefix) {\n            if (a.prefix === "xml") {\n              a.uri = NAMESPACE.XML;\n            }\n            if (a.prefix !== "xmlns") {\n              a.uri = currentNSMap[a.prefix];\n            }\n          }\n        }\n        var nsp = tagName.indexOf(":");\n        if (nsp > 0) {\n          prefix = el.prefix = tagName.slice(0, nsp);\n          localName = el.localName = tagName.slice(nsp + 1);\n        } else {\n          prefix = null;\n          localName = el.localName = tagName;\n        }\n        var ns = el.uri = currentNSMap[prefix || ""];\n        domBuilder.startElement(ns, localName, tagName, el);\n        if (el.closed) {\n          domBuilder.endElement(ns, localName, tagName);\n          if (localNSMap) {\n            for (prefix in localNSMap) {\n              if (hasOwn(localNSMap, prefix)) {\n                domBuilder.endPrefixMapping(prefix);\n              }\n            }\n          }\n        } else {\n          el.currentNSMap = currentNSMap;\n          el.localNSMap = localNSMap;\n          return true;\n        }\n      }\n      function parseHtmlSpecialContent(source, elStartEnd, tagName, entityReplacer, domBuilder) {\n        var isEscapableRaw = isHTMLEscapableRawTextElement(tagName);\n        if (isEscapableRaw || isHTMLRawTextElement(tagName)) {\n          var elEndStart = source.indexOf("</" + tagName + ">", elStartEnd);\n          var text = source.substring(elStartEnd + 1, elEndStart);\n          if (isEscapableRaw) {\n            text = text.replace(ENTITY_REG, entityReplacer);\n          }\n          domBuilder.characters(text, 0, text.length);\n          return elEndStart;\n        }\n        return elStartEnd + 1;\n      }\n      function _copy(source, target) {\n        for (var n in source) {\n          if (hasOwn(source, n)) {\n            target[n] = source[n];\n          }\n        }\n      }\n      function parseUtils(source, start) {\n        var index = start;\n        function char(n) {\n          n = n || 0;\n          return source.charAt(index + n);\n        }\n        function skip(n) {\n          n = n || 1;\n          index += n;\n        }\n        function skipBlanks() {\n          var blanks = 0;\n          while (index < source.length) {\n            var c = char();\n            if (c !== " " && c !== "\\n" && c !== "	" && c !== "\\r") {\n              return blanks;\n            }\n            blanks++;\n            skip();\n          }\n          return -1;\n        }\n        function substringFromIndex() {\n          return source.substring(index);\n        }\n        function substringStartsWith(text) {\n          return source.substring(index, index + text.length) === text;\n        }\n        function substringStartsWithCaseInsensitive(text) {\n          return source.substring(index, index + text.length).toUpperCase() === text.toUpperCase();\n        }\n        function getMatch(args) {\n          var expr = g.reg("^", args);\n          var match = expr.exec(substringFromIndex());\n          if (match) {\n            skip(match[0].length);\n            return match[0];\n          }\n          return null;\n        }\n        return {\n          char,\n          getIndex: function() {\n            return index;\n          },\n          getMatch,\n          getSource: function() {\n            return source;\n          },\n          skip,\n          skipBlanks,\n          substringFromIndex,\n          substringStartsWith,\n          substringStartsWithCaseInsensitive\n        };\n      }\n      function parseDoctypeInternalSubset(p, errorHandler) {\n        function parsePI(p2, errorHandler2) {\n          var match = g.PI.exec(p2.substringFromIndex());\n          if (!match) {\n            return errorHandler2.fatalError("processing instruction is not well-formed at position " + p2.getIndex());\n          }\n          if (match[1].toLowerCase() === "xml") {\n            return errorHandler2.fatalError(\n              "xml declaration is only allowed at the start of the document, but found at position " + p2.getIndex()\n            );\n          }\n          p2.skip(match[0].length);\n          return match[0];\n        }\n        var source = p.getSource();\n        if (p.char() === "[") {\n          p.skip(1);\n          var intSubsetStart = p.getIndex();\n          while (p.getIndex() < source.length) {\n            p.skipBlanks();\n            if (p.char() === "]") {\n              var internalSubset = source.substring(intSubsetStart, p.getIndex());\n              p.skip(1);\n              return internalSubset;\n            }\n            var current = null;\n            if (p.char() === "<" && p.char(1) === "!") {\n              switch (p.char(2)) {\n                case "E":\n                  if (p.char(3) === "L") {\n                    current = p.getMatch(g.elementdecl);\n                  } else if (p.char(3) === "N") {\n                    current = p.getMatch(g.EntityDecl);\n                  }\n                  break;\n                case "A":\n                  current = p.getMatch(g.AttlistDecl);\n                  break;\n                case "N":\n                  current = p.getMatch(g.NotationDecl);\n                  break;\n                case "-":\n                  current = p.getMatch(g.Comment);\n                  break;\n              }\n            } else if (p.char() === "<" && p.char(1) === "?") {\n              current = parsePI(p, errorHandler);\n            } else if (p.char() === "%") {\n              current = p.getMatch(g.PEReference);\n            } else {\n              return errorHandler.fatalError("Error detected in Markup declaration");\n            }\n            if (!current) {\n              return errorHandler.fatalError("Error in internal subset at position " + p.getIndex());\n            }\n          }\n          return errorHandler.fatalError("doctype internal subset is not well-formed, missing ]");\n        }\n      }\n      function parseDoctypeCommentOrCData(source, start, domBuilder, errorHandler, isHTML) {\n        var p = parseUtils(source, start);\n        switch (isHTML ? p.char(2).toUpperCase() : p.char(2)) {\n          case "-":\n            var comment = p.getMatch(g.Comment);\n            if (comment) {\n              domBuilder.comment(comment, g.COMMENT_START.length, comment.length - g.COMMENT_START.length - g.COMMENT_END.length);\n              return p.getIndex();\n            } else {\n              return errorHandler.fatalError("comment is not well-formed at position " + p.getIndex());\n            }\n          case "[":\n            var cdata = p.getMatch(g.CDSect);\n            if (cdata) {\n              if (!isHTML && !domBuilder.currentElement) {\n                return errorHandler.fatalError("CDATA outside of element");\n              }\n              domBuilder.startCDATA();\n              domBuilder.characters(cdata, g.CDATA_START.length, cdata.length - g.CDATA_START.length - g.CDATA_END.length);\n              domBuilder.endCDATA();\n              return p.getIndex();\n            } else {\n              return errorHandler.fatalError("Invalid CDATA starting at position " + start);\n            }\n          case "D": {\n            if (domBuilder.doc && domBuilder.doc.documentElement) {\n              return errorHandler.fatalError("Doctype not allowed inside or after documentElement at position " + p.getIndex());\n            }\n            if (isHTML ? !p.substringStartsWithCaseInsensitive(g.DOCTYPE_DECL_START) : !p.substringStartsWith(g.DOCTYPE_DECL_START)) {\n              return errorHandler.fatalError("Expected " + g.DOCTYPE_DECL_START + " at position " + p.getIndex());\n            }\n            p.skip(g.DOCTYPE_DECL_START.length);\n            if (p.skipBlanks() < 1) {\n              return errorHandler.fatalError("Expected whitespace after " + g.DOCTYPE_DECL_START + " at position " + p.getIndex());\n            }\n            var doctype = {\n              name: void 0,\n              publicId: void 0,\n              systemId: void 0,\n              internalSubset: void 0\n            };\n            doctype.name = p.getMatch(g.Name);\n            if (!doctype.name)\n              return errorHandler.fatalError("doctype name missing or contains unexpected characters at position " + p.getIndex());\n            if (isHTML && doctype.name.toLowerCase() !== "html") {\n              errorHandler.warning("Unexpected DOCTYPE in HTML document at position " + p.getIndex());\n            }\n            p.skipBlanks();\n            if (p.substringStartsWith(g.PUBLIC) || p.substringStartsWith(g.SYSTEM)) {\n              var match = g.ExternalID_match.exec(p.substringFromIndex());\n              if (!match) {\n                return errorHandler.fatalError("doctype external id is not well-formed at position " + p.getIndex());\n              }\n              if (match.groups.SystemLiteralOnly !== void 0) {\n                doctype.systemId = match.groups.SystemLiteralOnly;\n              } else {\n                doctype.systemId = match.groups.SystemLiteral;\n                doctype.publicId = match.groups.PubidLiteral;\n              }\n              p.skip(match[0].length);\n            } else if (isHTML && p.substringStartsWithCaseInsensitive(g.SYSTEM)) {\n              p.skip(g.SYSTEM.length);\n              if (p.skipBlanks() < 1) {\n                return errorHandler.fatalError("Expected whitespace after " + g.SYSTEM + " at position " + p.getIndex());\n              }\n              doctype.systemId = p.getMatch(g.ABOUT_LEGACY_COMPAT_SystemLiteral);\n              if (!doctype.systemId) {\n                return errorHandler.fatalError(\n                  "Expected " + g.ABOUT_LEGACY_COMPAT + " in single or double quotes after " + g.SYSTEM + " at position " + p.getIndex()\n                );\n              }\n            }\n            if (isHTML && doctype.systemId && !g.ABOUT_LEGACY_COMPAT_SystemLiteral.test(doctype.systemId)) {\n              errorHandler.warning("Unexpected doctype.systemId in HTML document at position " + p.getIndex());\n            }\n            if (!isHTML) {\n              p.skipBlanks();\n              doctype.internalSubset = parseDoctypeInternalSubset(p, errorHandler);\n            }\n            p.skipBlanks();\n            if (p.char() !== ">") {\n              return errorHandler.fatalError("doctype not terminated with > at position " + p.getIndex());\n            }\n            p.skip(1);\n            domBuilder.startDTD(doctype.name, doctype.publicId, doctype.systemId, doctype.internalSubset);\n            domBuilder.endDTD();\n            return p.getIndex();\n          }\n          default:\n            return errorHandler.fatalError(\'Not well-formed XML starting with "<!" at position \' + start);\n        }\n      }\n      function parseProcessingInstruction(source, start, domBuilder, errorHandler) {\n        var match = source.substring(start).match(g.PI);\n        if (!match) {\n          return errorHandler.fatalError("Invalid processing instruction starting at position " + start);\n        }\n        if (match[1].toLowerCase() === "xml") {\n          if (start > 0) {\n            return errorHandler.fatalError(\n              "processing instruction at position " + start + " is an xml declaration which is only at the start of the document"\n            );\n          }\n          if (!g.XMLDecl.test(source.substring(start))) {\n            return errorHandler.fatalError("xml declaration is not well-formed");\n          }\n        }\n        domBuilder.processingInstruction(match[1], match[2]);\n        return start + match[0].length;\n      }\n      function ElementAttributes() {\n        this.attributeNames = /* @__PURE__ */ Object.create(null);\n      }\n      ElementAttributes.prototype = {\n        setTagName: function(tagName) {\n          if (!g.QName_exact.test(tagName)) {\n            throw new Error("invalid tagName:" + tagName);\n          }\n          this.tagName = tagName;\n        },\n        addValue: function(qName, value, offset) {\n          if (!g.QName_exact.test(qName)) {\n            throw new Error("invalid attribute:" + qName);\n          }\n          this.attributeNames[qName] = this.length;\n          this[this.length++] = { qName, value, offset };\n        },\n        length: 0,\n        getLocalName: function(i) {\n          return this[i].localName;\n        },\n        getLocator: function(i) {\n          return this[i].locator;\n        },\n        getQName: function(i) {\n          return this[i].qName;\n        },\n        getURI: function(i) {\n          return this[i].uri;\n        },\n        getValue: function(i) {\n          return this[i].value;\n        }\n        //	,getIndex:function(uri, localName)){\n        //		if(localName){\n        //\n        //		}else{\n        //			var qName = uri\n        //		}\n        //	},\n        //	getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},\n        //	getType:function(uri,localName){}\n        //	getType:function(i){},\n      };\n      exports2.XMLReader = XMLReader;\n      exports2.parseUtils = parseUtils;\n      exports2.parseDoctypeCommentOrCData = parseDoctypeCommentOrCData;\n    }\n  });\n\n  // node_modules/@xmldom/xmldom/lib/dom-parser.js\n  var require_dom_parser = __commonJS({\n    "node_modules/@xmldom/xmldom/lib/dom-parser.js"(exports2) {\n      "use strict";\n      var conventions = require_conventions();\n      var dom = require_dom();\n      var errors = require_errors2();\n      var entities = require_entities();\n      var sax = require_sax();\n      var DOMImplementation = dom.DOMImplementation;\n      var hasDefaultHTMLNamespace = conventions.hasDefaultHTMLNamespace;\n      var isHTMLMimeType = conventions.isHTMLMimeType;\n      var isValidMimeType = conventions.isValidMimeType;\n      var MIME_TYPE = conventions.MIME_TYPE;\n      var NAMESPACE = conventions.NAMESPACE;\n      var ParseError = errors.ParseError;\n      var XMLReader = sax.XMLReader;\n      function normalizeLineEndings(input) {\n        return input.replace(/\\r[\\n\\u0085]/g, "\\n").replace(/[\\r\\u0085\\u2028\\u2029]/g, "\\n");\n      }\n      function DOMParser2(options) {\n        options = options || {};\n        if (options.locator === void 0) {\n          options.locator = true;\n        }\n        this.assign = options.assign || conventions.assign;\n        this.domHandler = options.domHandler || DOMHandler;\n        this.onError = options.onError || options.errorHandler;\n        if (options.errorHandler && typeof options.errorHandler !== "function") {\n          throw new TypeError("errorHandler object is no longer supported, switch to onError!");\n        } else if (options.errorHandler) {\n          options.errorHandler("warning", "The `errorHandler` option has been deprecated, use `onError` instead!", this);\n        }\n        this.normalizeLineEndings = options.normalizeLineEndings || normalizeLineEndings;\n        this.locator = !!options.locator;\n        this.xmlns = this.assign(/* @__PURE__ */ Object.create(null), options.xmlns);\n      }\n      DOMParser2.prototype.parseFromString = function(source, mimeType) {\n        if (!isValidMimeType(mimeType)) {\n          throw new TypeError(\'DOMParser.parseFromString: the provided mimeType "\' + mimeType + \'" is not valid.\');\n        }\n        var defaultNSMap = this.assign(/* @__PURE__ */ Object.create(null), this.xmlns);\n        var entityMap = entities.XML_ENTITIES;\n        var defaultNamespace = defaultNSMap[""] || null;\n        if (hasDefaultHTMLNamespace(mimeType)) {\n          entityMap = entities.HTML_ENTITIES;\n          defaultNamespace = NAMESPACE.HTML;\n        } else if (mimeType === MIME_TYPE.XML_SVG_IMAGE) {\n          defaultNamespace = NAMESPACE.SVG;\n        }\n        defaultNSMap[""] = defaultNamespace;\n        defaultNSMap.xml = defaultNSMap.xml || NAMESPACE.XML;\n        var domBuilder = new this.domHandler({\n          mimeType,\n          defaultNamespace,\n          onError: this.onError\n        });\n        var locator = this.locator ? {} : void 0;\n        if (this.locator) {\n          domBuilder.setDocumentLocator(locator);\n        }\n        var sax2 = new XMLReader();\n        sax2.errorHandler = domBuilder;\n        sax2.domBuilder = domBuilder;\n        var isXml = !conventions.isHTMLMimeType(mimeType);\n        if (isXml && typeof source !== "string") {\n          sax2.errorHandler.fatalError("source is not a string");\n        }\n        sax2.parse(this.normalizeLineEndings(String(source)), defaultNSMap, entityMap);\n        if (!domBuilder.doc.documentElement) {\n          sax2.errorHandler.fatalError("missing root element");\n        }\n        return domBuilder.doc;\n      };\n      function DOMHandler(options) {\n        var opt = options || {};\n        this.mimeType = opt.mimeType || MIME_TYPE.XML_APPLICATION;\n        this.defaultNamespace = opt.defaultNamespace || null;\n        this.cdata = false;\n        this.currentElement = void 0;\n        this.doc = void 0;\n        this.locator = void 0;\n        this.onError = opt.onError;\n      }\n      function position(locator, node) {\n        node.lineNumber = locator.lineNumber;\n        node.columnNumber = locator.columnNumber;\n      }\n      DOMHandler.prototype = {\n        /**\n         * Either creates an XML or an HTML document and stores it under `this.doc`.\n         * If it is an XML document, `this.defaultNamespace` is used to create it,\n         * and it will not contain any `childNodes`.\n         * If it is an HTML document, it will be created without any `childNodes`.\n         *\n         * @see http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html\n         */\n        startDocument: function() {\n          var impl = new DOMImplementation();\n          this.doc = isHTMLMimeType(this.mimeType) ? impl.createHTMLDocument(false) : impl.createDocument(this.defaultNamespace, "");\n        },\n        startElement: function(namespaceURI, localName, qName, attrs) {\n          var doc = this.doc;\n          var el = doc.createElementNS(namespaceURI, qName || localName);\n          var len = attrs.length;\n          appendElement(this, el);\n          this.currentElement = el;\n          this.locator && position(this.locator, el);\n          for (var i = 0; i < len; i++) {\n            var namespaceURI = attrs.getURI(i);\n            var value = attrs.getValue(i);\n            var qName = attrs.getQName(i);\n            var attr = doc.createAttributeNS(namespaceURI, qName);\n            this.locator && position(attrs.getLocator(i), attr);\n            attr.value = attr.nodeValue = value;\n            el.setAttributeNode(attr);\n          }\n        },\n        endElement: function(namespaceURI, localName, qName) {\n          this.currentElement = this.currentElement.parentNode;\n        },\n        startPrefixMapping: function(prefix, uri) {\n        },\n        endPrefixMapping: function(prefix) {\n        },\n        processingInstruction: function(target, data) {\n          var ins = this.doc.createProcessingInstruction(target, data);\n          this.locator && position(this.locator, ins);\n          appendElement(this, ins);\n        },\n        ignorableWhitespace: function(ch, start, length) {\n        },\n        characters: function(chars, start, length) {\n          chars = _toString.apply(this, arguments);\n          if (chars) {\n            if (this.cdata) {\n              var charNode = this.doc.createCDATASection(chars);\n            } else {\n              var charNode = this.doc.createTextNode(chars);\n            }\n            if (this.currentElement) {\n              this.currentElement.appendChild(charNode);\n            } else if (/^\\s*$/.test(chars)) {\n              this.doc.appendChild(charNode);\n            }\n            this.locator && position(this.locator, charNode);\n          }\n        },\n        skippedEntity: function(name2) {\n        },\n        endDocument: function() {\n          this.doc.normalize();\n        },\n        /**\n         * Stores the locator to be able to set the `columnNumber` and `lineNumber`\n         * on the created DOM nodes.\n         *\n         * @param {Locator} locator\n         */\n        setDocumentLocator: function(locator) {\n          if (locator) {\n            locator.lineNumber = 0;\n          }\n          this.locator = locator;\n        },\n        //LexicalHandler\n        comment: function(chars, start, length) {\n          chars = _toString.apply(this, arguments);\n          var comm = this.doc.createComment(chars);\n          this.locator && position(this.locator, comm);\n          appendElement(this, comm);\n        },\n        startCDATA: function() {\n          this.cdata = true;\n        },\n        endCDATA: function() {\n          this.cdata = false;\n        },\n        startDTD: function(name2, publicId, systemId, internalSubset) {\n          var impl = this.doc.implementation;\n          if (impl && impl.createDocumentType) {\n            var dt = impl.createDocumentType(name2, publicId, systemId, internalSubset);\n            this.locator && position(this.locator, dt);\n            appendElement(this, dt);\n            this.doc.doctype = dt;\n          }\n        },\n        reportError: function(level, message) {\n          if (typeof this.onError === "function") {\n            try {\n              this.onError(level, message, this);\n            } catch (e) {\n              throw new ParseError("Reporting " + level + \' "\' + message + \'" caused \' + e, this.locator);\n            }\n          } else {\n            console.error("[xmldom " + level + "]	" + message, _locator(this.locator));\n          }\n        },\n        /**\n         * @see http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html\n         */\n        warning: function(message) {\n          this.reportError("warning", message);\n        },\n        error: function(message) {\n          this.reportError("error", message);\n        },\n        /**\n         * This function reports a fatal error and throws a ParseError.\n         *\n         * @param {string} message\n         * - The message to be used for reporting and throwing the error.\n         * @returns {never}\n         * This function always throws an error and never returns a value.\n         * @throws {ParseError}\n         * Always throws a ParseError with the provided message.\n         */\n        fatalError: function(message) {\n          this.reportError("fatalError", message);\n          throw new ParseError(message, this.locator);\n        }\n      };\n      function _locator(l) {\n        if (l) {\n          return "\\n@#[line:" + l.lineNumber + ",col:" + l.columnNumber + "]";\n        }\n      }\n      function _toString(chars, start, length) {\n        if (typeof chars == "string") {\n          return chars.substr(start, length);\n        } else {\n          if (chars.length >= start + length || start) {\n            return new java.lang.String(chars, start, length) + "";\n          }\n          return chars;\n        }\n      }\n      "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(\n        /\\w+/g,\n        function(key) {\n          DOMHandler.prototype[key] = function() {\n            return null;\n          };\n        }\n      );\n      function appendElement(handler, node) {\n        if (!handler.currentElement) {\n          handler.doc.appendChild(node);\n        } else {\n          handler.currentElement.appendChild(node);\n        }\n      }\n      function onErrorStopParsing(level) {\n        if (level === "error") throw "onErrorStopParsing";\n      }\n      function onWarningStopParsing() {\n        throw "onWarningStopParsing";\n      }\n      exports2.__DOMHandler = DOMHandler;\n      exports2.DOMParser = DOMParser2;\n      exports2.normalizeLineEndings = normalizeLineEndings;\n      exports2.onErrorStopParsing = onErrorStopParsing;\n      exports2.onWarningStopParsing = onWarningStopParsing;\n    }\n  });\n\n  // node_modules/@xmldom/xmldom/lib/index.js\n  var require_lib = __commonJS({\n    "node_modules/@xmldom/xmldom/lib/index.js"(exports2) {\n      "use strict";\n      var conventions = require_conventions();\n      exports2.assign = conventions.assign;\n      exports2.hasDefaultHTMLNamespace = conventions.hasDefaultHTMLNamespace;\n      exports2.isHTMLMimeType = conventions.isHTMLMimeType;\n      exports2.isValidMimeType = conventions.isValidMimeType;\n      exports2.MIME_TYPE = conventions.MIME_TYPE;\n      exports2.NAMESPACE = conventions.NAMESPACE;\n      var errors = require_errors2();\n      exports2.DOMException = errors.DOMException;\n      exports2.DOMExceptionName = errors.DOMExceptionName;\n      exports2.ExceptionCode = errors.ExceptionCode;\n      exports2.ParseError = errors.ParseError;\n      var dom = require_dom();\n      exports2.Attr = dom.Attr;\n      exports2.CDATASection = dom.CDATASection;\n      exports2.CharacterData = dom.CharacterData;\n      exports2.Comment = dom.Comment;\n      exports2.Document = dom.Document;\n      exports2.DocumentFragment = dom.DocumentFragment;\n      exports2.DocumentType = dom.DocumentType;\n      exports2.DOMImplementation = dom.DOMImplementation;\n      exports2.Element = dom.Element;\n      exports2.Entity = dom.Entity;\n      exports2.EntityReference = dom.EntityReference;\n      exports2.LiveNodeList = dom.LiveNodeList;\n      exports2.NamedNodeMap = dom.NamedNodeMap;\n      exports2.Node = dom.Node;\n      exports2.NodeList = dom.NodeList;\n      exports2.Notation = dom.Notation;\n      exports2.ProcessingInstruction = dom.ProcessingInstruction;\n      exports2.Text = dom.Text;\n      exports2.XMLSerializer = dom.XMLSerializer;\n      var domParser = require_dom_parser();\n      exports2.DOMParser = domParser.DOMParser;\n      exports2.normalizeLineEndings = domParser.normalizeLineEndings;\n      exports2.onErrorStopParsing = domParser.onErrorStopParsing;\n      exports2.onWarningStopParsing = domParser.onWarningStopParsing;\n    }\n  });\n\n  // node_modules/xpath/xpath.js\n  var require_xpath = __commonJS({\n    "node_modules/xpath/xpath.js"(exports2) {\n      var xpath = typeof exports2 === "undefined" ? {} : exports2;\n      (function(exports3) {\n        "use strict";\n        var NAMESPACE_NODE_NODETYPE = "__namespace";\n        var isNil = function(x) {\n          return x === null || x === void 0;\n        };\n        var isValidNodeType = function(nodeType) {\n          return nodeType === NAMESPACE_NODE_NODETYPE || Number.isInteger(nodeType) && nodeType >= 1 && nodeType <= 11;\n        };\n        var isNodeLike = function(value) {\n          return value && isValidNodeType(value.nodeType) && typeof value.nodeName === "string";\n        };\n        function curry(func) {\n          var slice = Array.prototype.slice, totalargs = func.length, partial = function(args, fn3) {\n            return function() {\n              return fn3.apply(this, args.concat(slice.call(arguments)));\n            };\n          }, fn2 = function() {\n            var args = slice.call(arguments);\n            return args.length < totalargs ? partial(args, fn2) : func.apply(this, slice.apply(arguments, [0, totalargs]));\n          };\n          return fn2;\n        }\n        var forEach = function(f, xs) {\n          for (var i = 0; i < xs.length; i += 1) {\n            f(xs[i], i, xs);\n          }\n        };\n        var reduce = function(f, seed, xs) {\n          var acc = seed;\n          forEach(function(x, i) {\n            acc = f(acc, x, i);\n          }, xs);\n          return acc;\n        };\n        var map = function(f, xs) {\n          var mapped = new Array(xs.length);\n          forEach(function(x, i) {\n            mapped[i] = f(x);\n          }, xs);\n          return mapped;\n        };\n        var filter = function(f, xs) {\n          var filtered = [];\n          forEach(function(x, i) {\n            if (f(x, i)) {\n              filtered.push(x);\n            }\n          }, xs);\n          return filtered;\n        };\n        var includes = function(values, value) {\n          for (var i = 0; i < values.length; i += 1) {\n            if (values[i] === value) {\n              return true;\n            }\n          }\n          return false;\n        };\n        function always(value) {\n          return function() {\n            return value;\n          };\n        }\n        function toString(x) {\n          return x.toString();\n        }\n        var join = function(s, xs) {\n          return xs.join(s);\n        };\n        var wrap = function(pref, suf, str) {\n          return pref + str + suf;\n        };\n        var prototypeConcat = Array.prototype.concat;\n        var sortNodes = function(nodes, reverse) {\n          var ns = new XNodeSet();\n          ns.addArray(nodes);\n          var sorted = ns.toArray();\n          return reverse ? sorted.reverse() : sorted;\n        };\n        var MAX_ARGUMENT_LENGTH = 32767;\n        function flatten(arr) {\n          var result = [];\n          for (var start = 0; start < arr.length; start += MAX_ARGUMENT_LENGTH) {\n            var chunk = arr.slice(start, start + MAX_ARGUMENT_LENGTH);\n            result = prototypeConcat.apply(result, chunk);\n          }\n          return result;\n        }\n        function assign(target, varArgs) {\n          var to = Object(target);\n          for (var index = 1; index < arguments.length; index++) {\n            var nextSource = arguments[index];\n            if (nextSource != null) {\n              for (var nextKey in nextSource) {\n                if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {\n                  to[nextKey] = nextSource[nextKey];\n                }\n              }\n            }\n          }\n          return to;\n        }\n        var NodeTypes = {\n          ELEMENT_NODE: 1,\n          ATTRIBUTE_NODE: 2,\n          TEXT_NODE: 3,\n          CDATA_SECTION_NODE: 4,\n          PROCESSING_INSTRUCTION_NODE: 7,\n          COMMENT_NODE: 8,\n          DOCUMENT_NODE: 9,\n          DOCUMENT_TYPE_NODE: 10,\n          DOCUMENT_FRAGMENT_NODE: 11,\n          NAMESPACE_NODE: NAMESPACE_NODE_NODETYPE\n        };\n        XPathParser.prototype = new Object();\n        XPathParser.prototype.constructor = XPathParser;\n        XPathParser.superclass = Object.prototype;\n        function XPathParser() {\n          this.init();\n        }\n        XPathParser.prototype.init = function() {\n          this.reduceActions = [];\n          this.reduceActions[3] = function(rhs) {\n            return new OrOperation(rhs[0], rhs[2]);\n          };\n          this.reduceActions[5] = function(rhs) {\n            return new AndOperation(rhs[0], rhs[2]);\n          };\n          this.reduceActions[7] = function(rhs) {\n            return new EqualsOperation(rhs[0], rhs[2]);\n          };\n          this.reduceActions[8] = function(rhs) {\n            return new NotEqualOperation(rhs[0], rhs[2]);\n          };\n          this.reduceActions[10] = function(rhs) {\n            return new LessThanOperation(rhs[0], rhs[2]);\n          };\n          this.reduceActions[11] = function(rhs) {\n            return new GreaterThanOperation(rhs[0], rhs[2]);\n          };\n          this.reduceActions[12] = function(rhs) {\n            return new LessThanOrEqualOperation(rhs[0], rhs[2]);\n          };\n          this.reduceActions[13] = function(rhs) {\n            return new GreaterThanOrEqualOperation(rhs[0], rhs[2]);\n          };\n          this.reduceActions[15] = function(rhs) {\n            return new PlusOperation(rhs[0], rhs[2]);\n          };\n          this.reduceActions[16] = function(rhs) {\n            return new MinusOperation(rhs[0], rhs[2]);\n          };\n          this.reduceActions[18] = function(rhs) {\n            return new MultiplyOperation(rhs[0], rhs[2]);\n          };\n          this.reduceActions[19] = function(rhs) {\n            return new DivOperation(rhs[0], rhs[2]);\n          };\n          this.reduceActions[20] = function(rhs) {\n            return new ModOperation(rhs[0], rhs[2]);\n          };\n          this.reduceActions[22] = function(rhs) {\n            return new UnaryMinusOperation(rhs[1]);\n          };\n          this.reduceActions[24] = function(rhs) {\n            return new BarOperation(rhs[0], rhs[2]);\n          };\n          this.reduceActions[25] = function(rhs) {\n            return new PathExpr(void 0, void 0, rhs[0]);\n          };\n          this.reduceActions[27] = function(rhs) {\n            rhs[0].locationPath = rhs[2];\n            return rhs[0];\n          };\n          this.reduceActions[28] = function(rhs) {\n            rhs[0].locationPath = rhs[2];\n            rhs[0].locationPath.steps.unshift(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, []));\n            return rhs[0];\n          };\n          this.reduceActions[29] = function(rhs) {\n            return new PathExpr(rhs[0], [], void 0);\n          };\n          this.reduceActions[30] = function(rhs) {\n            if (Utilities.instance_of(rhs[0], PathExpr)) {\n              if (rhs[0].filterPredicates == void 0) {\n                rhs[0].filterPredicates = [];\n              }\n              rhs[0].filterPredicates.push(rhs[1]);\n              return rhs[0];\n            } else {\n              return new PathExpr(rhs[0], [rhs[1]], void 0);\n            }\n          };\n          this.reduceActions[32] = function(rhs) {\n            return rhs[1];\n          };\n          this.reduceActions[33] = function(rhs) {\n            return new XString(rhs[0]);\n          };\n          this.reduceActions[34] = function(rhs) {\n            return new XNumber(rhs[0]);\n          };\n          this.reduceActions[36] = function(rhs) {\n            return new FunctionCall(rhs[0], []);\n          };\n          this.reduceActions[37] = function(rhs) {\n            return new FunctionCall(rhs[0], rhs[2]);\n          };\n          this.reduceActions[38] = function(rhs) {\n            return [rhs[0]];\n          };\n          this.reduceActions[39] = function(rhs) {\n            rhs[2].unshift(rhs[0]);\n            return rhs[2];\n          };\n          this.reduceActions[43] = function(rhs) {\n            return new LocationPath(true, []);\n          };\n          this.reduceActions[44] = function(rhs) {\n            rhs[1].absolute = true;\n            return rhs[1];\n          };\n          this.reduceActions[46] = function(rhs) {\n            return new LocationPath(false, [rhs[0]]);\n          };\n          this.reduceActions[47] = function(rhs) {\n            rhs[0].steps.push(rhs[2]);\n            return rhs[0];\n          };\n          this.reduceActions[49] = function(rhs) {\n            return new Step(rhs[0], rhs[1], []);\n          };\n          this.reduceActions[50] = function(rhs) {\n            return new Step(Step.CHILD, rhs[0], []);\n          };\n          this.reduceActions[51] = function(rhs) {\n            return new Step(rhs[0], rhs[1], rhs[2]);\n          };\n          this.reduceActions[52] = function(rhs) {\n            return new Step(Step.CHILD, rhs[0], rhs[1]);\n          };\n          this.reduceActions[54] = function(rhs) {\n            return [rhs[0]];\n          };\n          this.reduceActions[55] = function(rhs) {\n            rhs[1].unshift(rhs[0]);\n            return rhs[1];\n          };\n          this.reduceActions[56] = function(rhs) {\n            if (rhs[0] == "ancestor") {\n              return Step.ANCESTOR;\n            } else if (rhs[0] == "ancestor-or-self") {\n              return Step.ANCESTORORSELF;\n            } else if (rhs[0] == "attribute") {\n              return Step.ATTRIBUTE;\n            } else if (rhs[0] == "child") {\n              return Step.CHILD;\n            } else if (rhs[0] == "descendant") {\n              return Step.DESCENDANT;\n            } else if (rhs[0] == "descendant-or-self") {\n              return Step.DESCENDANTORSELF;\n            } else if (rhs[0] == "following") {\n              return Step.FOLLOWING;\n            } else if (rhs[0] == "following-sibling") {\n              return Step.FOLLOWINGSIBLING;\n            } else if (rhs[0] == "namespace") {\n              return Step.NAMESPACE;\n            } else if (rhs[0] == "parent") {\n              return Step.PARENT;\n            } else if (rhs[0] == "preceding") {\n              return Step.PRECEDING;\n            } else if (rhs[0] == "preceding-sibling") {\n              return Step.PRECEDINGSIBLING;\n            } else if (rhs[0] == "self") {\n              return Step.SELF;\n            }\n            return -1;\n          };\n          this.reduceActions[57] = function(rhs) {\n            return Step.ATTRIBUTE;\n          };\n          this.reduceActions[59] = function(rhs) {\n            if (rhs[0] == "comment") {\n              return NodeTest.commentTest;\n            } else if (rhs[0] == "text") {\n              return NodeTest.textTest;\n            } else if (rhs[0] == "processing-instruction") {\n              return NodeTest.anyPiTest;\n            } else if (rhs[0] == "node") {\n              return NodeTest.nodeTest;\n            }\n            return new NodeTest(-1, void 0);\n          };\n          this.reduceActions[60] = function(rhs) {\n            return new NodeTest.PITest(rhs[2]);\n          };\n          this.reduceActions[61] = function(rhs) {\n            return rhs[1];\n          };\n          this.reduceActions[63] = function(rhs) {\n            rhs[1].absolute = true;\n            rhs[1].steps.unshift(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, []));\n            return rhs[1];\n          };\n          this.reduceActions[64] = function(rhs) {\n            rhs[0].steps.push(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, []));\n            rhs[0].steps.push(rhs[2]);\n            return rhs[0];\n          };\n          this.reduceActions[65] = function(rhs) {\n            return new Step(Step.SELF, NodeTest.nodeTest, []);\n          };\n          this.reduceActions[66] = function(rhs) {\n            return new Step(Step.PARENT, NodeTest.nodeTest, []);\n          };\n          this.reduceActions[67] = function(rhs) {\n            return new VariableReference(rhs[1]);\n          };\n          this.reduceActions[68] = function(rhs) {\n            return NodeTest.nameTestAny;\n          };\n          this.reduceActions[69] = function(rhs) {\n            return new NodeTest.NameTestPrefixAny(rhs[0].split(":")[0]);\n          };\n          this.reduceActions[70] = function(rhs) {\n            return new NodeTest.NameTestQName(rhs[0]);\n          };\n        };\n        XPathParser.actionTable = [\n          " s s        sssssssss    s ss  s  ss",\n          "                 s                  ",\n          "r  rrrrrrrrr         rrrrrrr rr  r  ",\n          "                rrrrr               ",\n          " s s        sssssssss    s ss  s  ss",\n          "rs  rrrrrrrr s  sssssrrrrrr  rrs rs ",\n          " s s        sssssssss    s ss  s  ss",\n          "                            s       ",\n          "                            s       ",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          "  s                                 ",\n          "                            s       ",\n          " s           s  sssss          s  s ",\n          "r  rrrrrrrrr         rrrrrrr rr  r  ",\n          "a                                   ",\n          "r       s                    rr  r  ",\n          "r      sr                    rr  r  ",\n          "r   s  rr            s       rr  r  ",\n          "r   rssrr            rss     rr  r  ",\n          "r   rrrrr            rrrss   rr  r  ",\n          "r   rrrrrsss         rrrrr   rr  r  ",\n          "r   rrrrrrrr         rrrrr   rr  r  ",\n          "r   rrrrrrrr         rrrrrs  rr  r  ",\n          "r   rrrrrrrr         rrrrrr  rr  r  ",\n          "r   rrrrrrrr         rrrrrr  rr  r  ",\n          "r  srrrrrrrr         rrrrrrs rr sr  ",\n          "r  srrrrrrrr         rrrrrrs rr  r  ",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          "r   rrrrrrrr         rrrrrr  rr  r  ",\n          "r   rrrrrrrr         rrrrrr  rr  r  ",\n          "r  rrrrrrrrr         rrrrrrr rr  r  ",\n          "r  rrrrrrrrr         rrrrrrr rr  r  ",\n          "                sssss               ",\n          "r  rrrrrrrrr         rrrrrrr rr sr  ",\n          "r  rrrrrrrrr         rrrrrrr rr  r  ",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          "                             s      ",\n          "r  srrrrrrrr         rrrrrrs rr  r  ",\n          "r   rrrrrrrr         rrrrr   rr  r  ",\n          "              s                     ",\n          "                             s      ",\n          "                rrrrr               ",\n          " s s        sssssssss    s sss s  ss",\n          "r  srrrrrrrr         rrrrrrs rr  r  ",\n          " s s        sssssssss    s ss  s  ss",\n          " s s        sssssssss    s ss  s  ss",\n          " s s        sssssssss    s ss  s  ss",\n          " s s        sssssssss    s ss  s  ss",\n          " s s        sssssssss    s ss  s  ss",\n          " s s        sssssssss    s ss  s  ss",\n          " s s        sssssssss    s ss  s  ss",\n          " s s        sssssssss    s ss  s  ss",\n          " s s        sssssssss    s ss  s  ss",\n          " s s        sssssssss    s ss  s  ss",\n          " s s        sssssssss    s ss  s  ss",\n          " s s        sssssssss    s ss  s  ss",\n          " s s        sssssssss    s ss  s  ss",\n          " s s        sssssssss      ss  s  ss",\n          " s s        sssssssss    s ss  s  ss",\n          " s           s  sssss          s  s ",\n          " s           s  sssss          s  s ",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          " s           s  sssss          s  s ",\n          " s           s  sssss          s  s ",\n          "r  rrrrrrrrr         rrrrrrr rr sr  ",\n          "r  rrrrrrrrr         rrrrrrr rr sr  ",\n          "r  rrrrrrrrr         rrrrrrr rr  r  ",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          "                             s      ",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          "                             rr     ",\n          "                             s      ",\n          "                             rs     ",\n          "r      sr                    rr  r  ",\n          "r   s  rr            s       rr  r  ",\n          "r   rssrr            rss     rr  r  ",\n          "r   rssrr            rss     rr  r  ",\n          "r   rrrrr            rrrss   rr  r  ",\n          "r   rrrrr            rrrss   rr  r  ",\n          "r   rrrrr            rrrss   rr  r  ",\n          "r   rrrrr            rrrss   rr  r  ",\n          "r   rrrrrsss         rrrrr   rr  r  ",\n          "r   rrrrrsss         rrrrr   rr  r  ",\n          "r   rrrrrrrr         rrrrr   rr  r  ",\n          "r   rrrrrrrr         rrrrr   rr  r  ",\n          "r   rrrrrrrr         rrrrr   rr  r  ",\n          "r   rrrrrrrr         rrrrrr  rr  r  ",\n          "                                 r  ",\n          "                                 s  ",\n          "r  srrrrrrrr         rrrrrrs rr  r  ",\n          "r  srrrrrrrr         rrrrrrs rr  r  ",\n          "r  rrrrrrrrr         rrrrrrr rr  r  ",\n          "r  rrrrrrrrr         rrrrrrr rr  r  ",\n          "r  rrrrrrrrr         rrrrrrr rr  r  ",\n          "r  rrrrrrrrr         rrrrrrr rr  r  ",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          " s s        sssssssss    s ss  s  ss",\n          "r  rrrrrrrrr         rrrrrrr rr rr  ",\n          "                             r      "\n        ];\n        XPathParser.actionTableNumber = [\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          "                 J                  ",\n          "a  aaaaaaaaa         aaaaaaa aa  a  ",\n          "                YYYYY               ",\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          `K1  KKKKKKKK .  +*)(\'KKKKKK  KK# K" `,\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          "                            N       ",\n          "                            O       ",\n          "e  eeeeeeeee         eeeeeee ee ee  ",\n          "f  fffffffff         fffffff ff ff  ",\n          "d  ddddddddd         ddddddd dd dd  ",\n          "B  BBBBBBBBB         BBBBBBB BB BB  ",\n          "A  AAAAAAAAA         AAAAAAA AA AA  ",\n          "  P                                 ",\n          "                            Q       ",\n          ` 1           .  +*)(\'          #  " `,\n          "b  bbbbbbbbb         bbbbbbb bb  b  ",\n          "                                    ",\n          "!       S                    !!  !  ",\n          \'"      T"                    ""  "  \',\n          "$   V  $$            U       $$  $  ",\n          "&   &ZY&&            &XW     &&  &  ",\n          ")   )))))            )))\\\\[   ))  )  ",\n          ".   ....._^]         .....   ..  .  ",\n          "1   11111111         11111   11  1  ",\n          "5   55555555         55555`  55  5  ",\n          "7   77777777         777777  77  7  ",\n          "9   99999999         999999  99  9  ",\n          ":  c::::::::         ::::::b :: a:  ",\n          "I  fIIIIIIII         IIIIIIe II  I  ",\n          "=  =========         ======= == ==  ",\n          "?  ?????????         ??????? ?? ??  ",\n          "C  CCCCCCCCC         CCCCCCC CC CC  ",\n          "J   JJJJJJJJ         JJJJJJ  JJ  J  ",\n          "M   MMMMMMMM         MMMMMM  MM  M  ",\n          "N  NNNNNNNNN         NNNNNNN NN  N  ",\n          "P  PPPPPPPPP         PPPPPPP PP  P  ",\n          "                +*)(\'               ",\n          "R  RRRRRRRRR         RRRRRRR RR aR  ",\n          "U  UUUUUUUUU         UUUUUUU UU  U  ",\n          "Z  ZZZZZZZZZ         ZZZZZZZ ZZ ZZ  ",\n          "c  ccccccccc         ccccccc cc cc  ",\n          "                             j      ",\n          "L  fLLLLLLLL         LLLLLLe LL  L  ",\n          "6   66666666         66666   66  6  ",\n          "              k                     ",\n          "                             l      ",\n          "                XXXXX               ",\n          ` 1 0        /.-,+*)(\'    & %$m #  "!`,\n          "_  f________         ______e __  _  ",\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          ` 1 0        /.-,+*)(\'      %$  #  "!`,\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          ` 1           .  +*)(\'          #  " `,\n          ` 1           .  +*)(\'          #  " `,\n          ">  >>>>>>>>>         >>>>>>> >> >>  ",\n          ` 1           .  +*)(\'          #  " `,\n          ` 1           .  +*)(\'          #  " `,\n          "Q  QQQQQQQQQ         QQQQQQQ QQ aQ  ",\n          "V  VVVVVVVVV         VVVVVVV VV aV  ",\n          "T  TTTTTTTTT         TTTTTTT TT  T  ",\n          "@  @@@@@@@@@         @@@@@@@ @@ @@  ",\n          "                             \\x87      ",\n          "[  [[[[[[[[[         [[[[[[[ [[ [[  ",\n          "D  DDDDDDDDD         DDDDDDD DD DD  ",\n          "                             HH     ",\n          "                             \\x88      ",\n          "                             F\\x89     ",\n          "#      T#                    ##  #  ",\n          "%   V  %%            U       %%  %  ",\n          "\'   \'ZY\'\'            \'XW     \'\'  \'  ",\n          "(   (ZY((            (XW     ((  (  ",\n          "+   +++++            +++\\\\[   ++  +  ",\n          "*   *****            ***\\\\[   **  *  ",\n          "-   -----            ---\\\\[   --  -  ",\n          ",   ,,,,,            ,,,\\\\[   ,,  ,  ",\n          "0   00000_^]         00000   00  0  ",\n          "/   /////_^]         /////   //  /  ",\n          "2   22222222         22222   22  2  ",\n          "3   33333333         33333   33  3  ",\n          "4   44444444         44444   44  4  ",\n          "8   88888888         888888  88  8  ",\n          "                                 ^  ",\n          "                                 \\x8A  ",\n          ";  f;;;;;;;;         ;;;;;;e ;;  ;  ",\n          "<  f<<<<<<<<         <<<<<<e <<  <  ",\n          "O  OOOOOOOOO         OOOOOOO OO  O  ",\n          "`  `````````         ``````` ``  `  ",\n          "S  SSSSSSSSS         SSSSSSS SS  S  ",\n          "W  WWWWWWWWW         WWWWWWW WW  W  ",\n          "\\\\  \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\         \\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\ \\\\\\\\  ",\n          "E  EEEEEEEEE         EEEEEEE EE EE  ",\n          ` 1 0        /.-,+*)(\'    & %$  #  "!`,\n          "]  ]]]]]]]]]         ]]]]]]] ]] ]]  ",\n          "                             G      "\n        ];\n        XPathParser.gotoTable = [\n          "3456789:;<=>?@ AB  CDEFGH IJ ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "L456789:;<=>?@ AB  CDEFGH IJ ",\n          "            M        EFGH IJ ",\n          "       N;<=>?@ AB  CDEFGH IJ ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "            S        EFGH IJ ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "              e              ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                        h  J ",\n          "              i          j   ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "o456789:;<=>?@ ABpqCDEFGH IJ ",\n          "                             ",\n          "  r6789:;<=>?@ AB  CDEFGH IJ ",\n          "   s789:;<=>?@ AB  CDEFGH IJ ",\n          "    t89:;<=>?@ AB  CDEFGH IJ ",\n          "    u89:;<=>?@ AB  CDEFGH IJ ",\n          "     v9:;<=>?@ AB  CDEFGH IJ ",\n          "     w9:;<=>?@ AB  CDEFGH IJ ",\n          "     x9:;<=>?@ AB  CDEFGH IJ ",\n          "     y9:;<=>?@ AB  CDEFGH IJ ",\n          "      z:;<=>?@ AB  CDEFGH IJ ",\n          "      {:;<=>?@ AB  CDEFGH IJ ",\n          "       |;<=>?@ AB  CDEFGH IJ ",\n          "       };<=>?@ AB  CDEFGH IJ ",\n          "       ~;<=>?@ AB  CDEFGH IJ ",\n          "         \\x7F=>?@ AB  CDEFGH IJ ",\n          "\\x80456789:;<=>?@ AB  CDEFGH IJ\\x81",\n          "            \\x82        EFGH IJ ",\n          "            \\x83        EFGH IJ ",\n          "                             ",\n          "                     \\x84 GH IJ ",\n          "                     \\x85 GH IJ ",\n          "              i          \\x86   ",\n          "              i          \\x87   ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "                             ",\n          "o456789:;<=>?@ AB\\x8CqCDEFGH IJ ",\n          "                             ",\n          "                             "\n        ];\n        XPathParser.productions = [\n          [1, 1, 2],\n          [2, 1, 3],\n          [3, 1, 4],\n          [3, 3, 3, -9, 4],\n          [4, 1, 5],\n          [4, 3, 4, -8, 5],\n          [5, 1, 6],\n          [5, 3, 5, -22, 6],\n          [5, 3, 5, -5, 6],\n          [6, 1, 7],\n          [6, 3, 6, -23, 7],\n          [6, 3, 6, -24, 7],\n          [6, 3, 6, -6, 7],\n          [6, 3, 6, -7, 7],\n          [7, 1, 8],\n          [7, 3, 7, -25, 8],\n          [7, 3, 7, -26, 8],\n          [8, 1, 9],\n          [8, 3, 8, -12, 9],\n          [8, 3, 8, -11, 9],\n          [8, 3, 8, -10, 9],\n          [9, 1, 10],\n          [9, 2, -26, 9],\n          [10, 1, 11],\n          [10, 3, 10, -27, 11],\n          [11, 1, 12],\n          [11, 1, 13],\n          [11, 3, 13, -28, 14],\n          [11, 3, 13, -4, 14],\n          [13, 1, 15],\n          [13, 2, 13, 16],\n          [15, 1, 17],\n          [15, 3, -29, 2, -30],\n          [15, 1, -15],\n          [15, 1, -16],\n          [15, 1, 18],\n          [18, 3, -13, -29, -30],\n          [18, 4, -13, -29, 19, -30],\n          [19, 1, 20],\n          [19, 3, 20, -31, 19],\n          [20, 1, 2],\n          [12, 1, 14],\n          [12, 1, 21],\n          [21, 1, -28],\n          [21, 2, -28, 14],\n          [21, 1, 22],\n          [14, 1, 23],\n          [14, 3, 14, -28, 23],\n          [14, 1, 24],\n          [23, 2, 25, 26],\n          [23, 1, 26],\n          [23, 3, 25, 26, 27],\n          [23, 2, 26, 27],\n          [23, 1, 28],\n          [27, 1, 16],\n          [27, 2, 16, 27],\n          [25, 2, -14, -3],\n          [25, 1, -32],\n          [26, 1, 29],\n          [26, 3, -20, -29, -30],\n          [26, 4, -21, -29, -15, -30],\n          [16, 3, -33, 30, -34],\n          [30, 1, 2],\n          [22, 2, -4, 14],\n          [24, 3, 14, -4, 23],\n          [28, 1, -35],\n          [28, 1, -2],\n          [17, 2, -36, -18],\n          [29, 1, -17],\n          [29, 1, -19],\n          [29, 1, -18]\n        ];\n        XPathParser.DOUBLEDOT = 2;\n        XPathParser.DOUBLECOLON = 3;\n        XPathParser.DOUBLESLASH = 4;\n        XPathParser.NOTEQUAL = 5;\n        XPathParser.LESSTHANOREQUAL = 6;\n        XPathParser.GREATERTHANOREQUAL = 7;\n        XPathParser.AND = 8;\n        XPathParser.OR = 9;\n        XPathParser.MOD = 10;\n        XPathParser.DIV = 11;\n        XPathParser.MULTIPLYOPERATOR = 12;\n        XPathParser.FUNCTIONNAME = 13;\n        XPathParser.AXISNAME = 14;\n        XPathParser.LITERAL = 15;\n        XPathParser.NUMBER = 16;\n        XPathParser.ASTERISKNAMETEST = 17;\n        XPathParser.QNAME = 18;\n        XPathParser.NCNAMECOLONASTERISK = 19;\n        XPathParser.NODETYPE = 20;\n        XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL = 21;\n        XPathParser.EQUALS = 22;\n        XPathParser.LESSTHAN = 23;\n        XPathParser.GREATERTHAN = 24;\n        XPathParser.PLUS = 25;\n        XPathParser.MINUS = 26;\n        XPathParser.BAR = 27;\n        XPathParser.SLASH = 28;\n        XPathParser.LEFTPARENTHESIS = 29;\n        XPathParser.RIGHTPARENTHESIS = 30;\n        XPathParser.COMMA = 31;\n        XPathParser.AT = 32;\n        XPathParser.LEFTBRACKET = 33;\n        XPathParser.RIGHTBRACKET = 34;\n        XPathParser.DOT = 35;\n        XPathParser.DOLLAR = 36;\n        XPathParser.prototype.tokenize = function(s1) {\n          var types = [];\n          var values = [];\n          var s = s1 + "\\0";\n          var pos = 0;\n          var c = s.charAt(pos++);\n          while (1) {\n            while (c == " " || c == "	" || c == "\\r" || c == "\\n") {\n              c = s.charAt(pos++);\n            }\n            if (c == "\\0" || pos >= s.length) {\n              break;\n            }\n            if (c == "(") {\n              types.push(XPathParser.LEFTPARENTHESIS);\n              values.push(c);\n              c = s.charAt(pos++);\n              continue;\n            }\n            if (c == ")") {\n              types.push(XPathParser.RIGHTPARENTHESIS);\n              values.push(c);\n              c = s.charAt(pos++);\n              continue;\n            }\n            if (c == "[") {\n              types.push(XPathParser.LEFTBRACKET);\n              values.push(c);\n              c = s.charAt(pos++);\n              continue;\n            }\n            if (c == "]") {\n              types.push(XPathParser.RIGHTBRACKET);\n              values.push(c);\n              c = s.charAt(pos++);\n              continue;\n            }\n            if (c == "@") {\n              types.push(XPathParser.AT);\n              values.push(c);\n              c = s.charAt(pos++);\n              continue;\n            }\n            if (c == ",") {\n              types.push(XPathParser.COMMA);\n              values.push(c);\n              c = s.charAt(pos++);\n              continue;\n            }\n            if (c == "|") {\n              types.push(XPathParser.BAR);\n              values.push(c);\n              c = s.charAt(pos++);\n              continue;\n            }\n            if (c == "+") {\n              types.push(XPathParser.PLUS);\n              values.push(c);\n              c = s.charAt(pos++);\n              continue;\n            }\n            if (c == "-") {\n              types.push(XPathParser.MINUS);\n              values.push(c);\n              c = s.charAt(pos++);\n              continue;\n            }\n            if (c == "=") {\n              types.push(XPathParser.EQUALS);\n              values.push(c);\n              c = s.charAt(pos++);\n              continue;\n            }\n            if (c == "$") {\n              types.push(XPathParser.DOLLAR);\n              values.push(c);\n              c = s.charAt(pos++);\n              continue;\n            }\n            if (c == ".") {\n              c = s.charAt(pos++);\n              if (c == ".") {\n                types.push(XPathParser.DOUBLEDOT);\n                values.push("..");\n                c = s.charAt(pos++);\n                continue;\n              }\n              if (c >= "0" && c <= "9") {\n                var number = "." + c;\n                c = s.charAt(pos++);\n                while (c >= "0" && c <= "9") {\n                  number += c;\n                  c = s.charAt(pos++);\n                }\n                types.push(XPathParser.NUMBER);\n                values.push(number);\n                continue;\n              }\n              types.push(XPathParser.DOT);\n              values.push(".");\n              continue;\n            }\n            if (c == "\'" || c == \'"\') {\n              var delimiter = c;\n              var literal = "";\n              while (pos < s.length && (c = s.charAt(pos)) !== delimiter) {\n                literal += c;\n                pos += 1;\n              }\n              if (c !== delimiter) {\n                throw XPathException.fromMessage("Unterminated string literal: " + delimiter + literal);\n              }\n              pos += 1;\n              types.push(XPathParser.LITERAL);\n              values.push(literal);\n              c = s.charAt(pos++);\n              continue;\n            }\n            if (c >= "0" && c <= "9") {\n              var number = c;\n              c = s.charAt(pos++);\n              while (c >= "0" && c <= "9") {\n                number += c;\n                c = s.charAt(pos++);\n              }\n              if (c == ".") {\n                if (s.charAt(pos) >= "0" && s.charAt(pos) <= "9") {\n                  number += c;\n                  number += s.charAt(pos++);\n                  c = s.charAt(pos++);\n                  while (c >= "0" && c <= "9") {\n                    number += c;\n                    c = s.charAt(pos++);\n                  }\n                }\n              }\n              types.push(XPathParser.NUMBER);\n              values.push(number);\n              continue;\n            }\n            if (c == "*") {\n              if (types.length > 0) {\n                var last = types[types.length - 1];\n                if (last != XPathParser.AT && last != XPathParser.DOUBLECOLON && last != XPathParser.LEFTPARENTHESIS && last != XPathParser.LEFTBRACKET && last != XPathParser.AND && last != XPathParser.OR && last != XPathParser.MOD && last != XPathParser.DIV && last != XPathParser.MULTIPLYOPERATOR && last != XPathParser.SLASH && last != XPathParser.DOUBLESLASH && last != XPathParser.BAR && last != XPathParser.PLUS && last != XPathParser.MINUS && last != XPathParser.EQUALS && last != XPathParser.NOTEQUAL && last != XPathParser.LESSTHAN && last != XPathParser.LESSTHANOREQUAL && last != XPathParser.GREATERTHAN && last != XPathParser.GREATERTHANOREQUAL) {\n                  types.push(XPathParser.MULTIPLYOPERATOR);\n                  values.push(c);\n                  c = s.charAt(pos++);\n                  continue;\n                }\n              }\n              types.push(XPathParser.ASTERISKNAMETEST);\n              values.push(c);\n              c = s.charAt(pos++);\n              continue;\n            }\n            if (c == ":") {\n              if (s.charAt(pos) == ":") {\n                types.push(XPathParser.DOUBLECOLON);\n                values.push("::");\n                pos++;\n                c = s.charAt(pos++);\n                continue;\n              }\n            }\n            if (c == "/") {\n              c = s.charAt(pos++);\n              if (c == "/") {\n                types.push(XPathParser.DOUBLESLASH);\n                values.push("//");\n                c = s.charAt(pos++);\n                continue;\n              }\n              types.push(XPathParser.SLASH);\n              values.push("/");\n              continue;\n            }\n            if (c == "!") {\n              if (s.charAt(pos) == "=") {\n                types.push(XPathParser.NOTEQUAL);\n                values.push("!=");\n                pos++;\n                c = s.charAt(pos++);\n                continue;\n              }\n            }\n            if (c == "<") {\n              if (s.charAt(pos) == "=") {\n                types.push(XPathParser.LESSTHANOREQUAL);\n                values.push("<=");\n                pos++;\n                c = s.charAt(pos++);\n                continue;\n              }\n              types.push(XPathParser.LESSTHAN);\n              values.push("<");\n              c = s.charAt(pos++);\n              continue;\n            }\n            if (c == ">") {\n              if (s.charAt(pos) == "=") {\n                types.push(XPathParser.GREATERTHANOREQUAL);\n                values.push(">=");\n                pos++;\n                c = s.charAt(pos++);\n                continue;\n              }\n              types.push(XPathParser.GREATERTHAN);\n              values.push(">");\n              c = s.charAt(pos++);\n              continue;\n            }\n            if (c == "_" || Utilities.isLetter(c.charCodeAt(0))) {\n              var name2 = c;\n              c = s.charAt(pos++);\n              while (Utilities.isNCNameChar(c.charCodeAt(0))) {\n                name2 += c;\n                c = s.charAt(pos++);\n              }\n              if (types.length > 0) {\n                var last = types[types.length - 1];\n                if (last != XPathParser.AT && last != XPathParser.DOUBLECOLON && last != XPathParser.LEFTPARENTHESIS && last != XPathParser.LEFTBRACKET && last != XPathParser.AND && last != XPathParser.OR && last != XPathParser.MOD && last != XPathParser.DIV && last != XPathParser.MULTIPLYOPERATOR && last != XPathParser.SLASH && last != XPathParser.DOUBLESLASH && last != XPathParser.BAR && last != XPathParser.PLUS && last != XPathParser.MINUS && last != XPathParser.EQUALS && last != XPathParser.NOTEQUAL && last != XPathParser.LESSTHAN && last != XPathParser.LESSTHANOREQUAL && last != XPathParser.GREATERTHAN && last != XPathParser.GREATERTHANOREQUAL) {\n                  if (name2 == "and") {\n                    types.push(XPathParser.AND);\n                    values.push(name2);\n                    continue;\n                  }\n                  if (name2 == "or") {\n                    types.push(XPathParser.OR);\n                    values.push(name2);\n                    continue;\n                  }\n                  if (name2 == "mod") {\n                    types.push(XPathParser.MOD);\n                    values.push(name2);\n                    continue;\n                  }\n                  if (name2 == "div") {\n                    types.push(XPathParser.DIV);\n                    values.push(name2);\n                    continue;\n                  }\n                }\n              }\n              if (c == ":") {\n                if (s.charAt(pos) == "*") {\n                  types.push(XPathParser.NCNAMECOLONASTERISK);\n                  values.push(name2 + ":*");\n                  pos++;\n                  c = s.charAt(pos++);\n                  continue;\n                }\n                if (s.charAt(pos) == "_" || Utilities.isLetter(s.charCodeAt(pos))) {\n                  name2 += ":";\n                  c = s.charAt(pos++);\n                  while (Utilities.isNCNameChar(c.charCodeAt(0))) {\n                    name2 += c;\n                    c = s.charAt(pos++);\n                  }\n                  if (c == "(") {\n                    types.push(XPathParser.FUNCTIONNAME);\n                    values.push(name2);\n                    continue;\n                  }\n                  types.push(XPathParser.QNAME);\n                  values.push(name2);\n                  continue;\n                }\n                if (s.charAt(pos) == ":") {\n                  types.push(XPathParser.AXISNAME);\n                  values.push(name2);\n                  continue;\n                }\n              }\n              if (c == "(") {\n                if (name2 == "comment" || name2 == "text" || name2 == "node") {\n                  types.push(XPathParser.NODETYPE);\n                  values.push(name2);\n                  continue;\n                }\n                if (name2 == "processing-instruction") {\n                  if (s.charAt(pos) == ")") {\n                    types.push(XPathParser.NODETYPE);\n                  } else {\n                    types.push(XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL);\n                  }\n                  values.push(name2);\n                  continue;\n                }\n                types.push(XPathParser.FUNCTIONNAME);\n                values.push(name2);\n                continue;\n              }\n              types.push(XPathParser.QNAME);\n              values.push(name2);\n              continue;\n            }\n            throw new Error("Unexpected character " + c);\n          }\n          types.push(1);\n          values.push("[EOF]");\n          return [types, values];\n        };\n        XPathParser.SHIFT = "s";\n        XPathParser.REDUCE = "r";\n        XPathParser.ACCEPT = "a";\n        XPathParser.prototype.parse = function(s) {\n          if (!s) {\n            throw new Error("XPath expression unspecified.");\n          }\n          if (typeof s !== "string") {\n            throw new Error("XPath expression must be a string.");\n          }\n          var types;\n          var values;\n          var res = this.tokenize(s);\n          if (res == void 0) {\n            return void 0;\n          }\n          types = res[0];\n          values = res[1];\n          var tokenPos = 0;\n          var state = [];\n          var tokenType = [];\n          var tokenValue = [];\n          var s;\n          var a;\n          var t;\n          state.push(0);\n          tokenType.push(1);\n          tokenValue.push("_S");\n          a = types[tokenPos];\n          t = values[tokenPos++];\n          while (1) {\n            s = state[state.length - 1];\n            switch (XPathParser.actionTable[s].charAt(a - 1)) {\n              case XPathParser.SHIFT:\n                tokenType.push(-a);\n                tokenValue.push(t);\n                state.push(XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32);\n                a = types[tokenPos];\n                t = values[tokenPos++];\n                break;\n              case XPathParser.REDUCE:\n                var num = XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][1];\n                var rhs = [];\n                for (var i = 0; i < num; i++) {\n                  tokenType.pop();\n                  rhs.unshift(tokenValue.pop());\n                  state.pop();\n                }\n                var s_ = state[state.length - 1];\n                tokenType.push(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0]);\n                if (this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32] == void 0) {\n                  tokenValue.push(rhs[0]);\n                } else {\n                  tokenValue.push(this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32](rhs));\n                }\n                state.push(XPathParser.gotoTable[s_].charCodeAt(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0] - 2) - 33);\n                break;\n              case XPathParser.ACCEPT:\n                return new XPath(tokenValue.pop());\n              default:\n                throw new Error("XPath parse error");\n            }\n          }\n        };\n        XPath.prototype = new Object();\n        XPath.prototype.constructor = XPath;\n        XPath.superclass = Object.prototype;\n        function XPath(e) {\n          this.expression = e;\n        }\n        XPath.prototype.toString = function() {\n          return this.expression.toString();\n        };\n        function setIfUnset(obj, prop, value) {\n          if (!(prop in obj)) {\n            obj[prop] = value;\n          }\n        }\n        XPath.prototype.evaluate = function(c) {\n          var node = c.expressionContextNode;\n          if (!(isNil(node) || isNodeLike(node))) {\n            throw new Error("Context node does not appear to be a valid DOM node.");\n          }\n          c.contextNode = c.expressionContextNode;\n          c.contextSize = 1;\n          c.contextPosition = 1;\n          if (c.isHtml) {\n            setIfUnset(c, "caseInsensitive", true);\n            setIfUnset(c, "allowAnyNamespaceForNoPrefix", true);\n          }\n          setIfUnset(c, "caseInsensitive", false);\n          return this.expression.evaluate(c);\n        };\n        XPath.XML_NAMESPACE_URI = "http://www.w3.org/XML/1998/namespace";\n        XPath.XMLNS_NAMESPACE_URI = "http://www.w3.org/2000/xmlns/";\n        Expression.prototype = new Object();\n        Expression.prototype.constructor = Expression;\n        Expression.superclass = Object.prototype;\n        function Expression() {\n        }\n        Expression.prototype.init = function() {\n        };\n        Expression.prototype.toString = function() {\n          return "<Expression>";\n        };\n        Expression.prototype.evaluate = function(c) {\n          throw new Error("Could not evaluate expression.");\n        };\n        UnaryOperation.prototype = new Expression();\n        UnaryOperation.prototype.constructor = UnaryOperation;\n        UnaryOperation.superclass = Expression.prototype;\n        function UnaryOperation(rhs) {\n          if (arguments.length > 0) {\n            this.init(rhs);\n          }\n        }\n        UnaryOperation.prototype.init = function(rhs) {\n          this.rhs = rhs;\n        };\n        UnaryMinusOperation.prototype = new UnaryOperation();\n        UnaryMinusOperation.prototype.constructor = UnaryMinusOperation;\n        UnaryMinusOperation.superclass = UnaryOperation.prototype;\n        function UnaryMinusOperation(rhs) {\n          if (arguments.length > 0) {\n            this.init(rhs);\n          }\n        }\n        UnaryMinusOperation.prototype.init = function(rhs) {\n          UnaryMinusOperation.superclass.init.call(this, rhs);\n        };\n        UnaryMinusOperation.prototype.evaluate = function(c) {\n          return this.rhs.evaluate(c).number().negate();\n        };\n        UnaryMinusOperation.prototype.toString = function() {\n          return "-" + this.rhs.toString();\n        };\n        BinaryOperation.prototype = new Expression();\n        BinaryOperation.prototype.constructor = BinaryOperation;\n        BinaryOperation.superclass = Expression.prototype;\n        function BinaryOperation(lhs, rhs) {\n          if (arguments.length > 0) {\n            this.init(lhs, rhs);\n          }\n        }\n        BinaryOperation.prototype.init = function(lhs, rhs) {\n          this.lhs = lhs;\n          this.rhs = rhs;\n        };\n        OrOperation.prototype = new BinaryOperation();\n        OrOperation.prototype.constructor = OrOperation;\n        OrOperation.superclass = BinaryOperation.prototype;\n        function OrOperation(lhs, rhs) {\n          if (arguments.length > 0) {\n            this.init(lhs, rhs);\n          }\n        }\n        OrOperation.prototype.init = function(lhs, rhs) {\n          OrOperation.superclass.init.call(this, lhs, rhs);\n        };\n        OrOperation.prototype.toString = function() {\n          return "(" + this.lhs.toString() + " or " + this.rhs.toString() + ")";\n        };\n        OrOperation.prototype.evaluate = function(c) {\n          var b = this.lhs.evaluate(c).bool();\n          if (b.booleanValue()) {\n            return b;\n          }\n          return this.rhs.evaluate(c).bool();\n        };\n        AndOperation.prototype = new BinaryOperation();\n        AndOperation.prototype.constructor = AndOperation;\n        AndOperation.superclass = BinaryOperation.prototype;\n        function AndOperation(lhs, rhs) {\n          if (arguments.length > 0) {\n            this.init(lhs, rhs);\n          }\n        }\n        AndOperation.prototype.init = function(lhs, rhs) {\n          AndOperation.superclass.init.call(this, lhs, rhs);\n        };\n        AndOperation.prototype.toString = function() {\n          return "(" + this.lhs.toString() + " and " + this.rhs.toString() + ")";\n        };\n        AndOperation.prototype.evaluate = function(c) {\n          var b = this.lhs.evaluate(c).bool();\n          if (!b.booleanValue()) {\n            return b;\n          }\n          return this.rhs.evaluate(c).bool();\n        };\n        EqualsOperation.prototype = new BinaryOperation();\n        EqualsOperation.prototype.constructor = EqualsOperation;\n        EqualsOperation.superclass = BinaryOperation.prototype;\n        function EqualsOperation(lhs, rhs) {\n          if (arguments.length > 0) {\n            this.init(lhs, rhs);\n          }\n        }\n        EqualsOperation.prototype.init = function(lhs, rhs) {\n          EqualsOperation.superclass.init.call(this, lhs, rhs);\n        };\n        EqualsOperation.prototype.toString = function() {\n          return "(" + this.lhs.toString() + " = " + this.rhs.toString() + ")";\n        };\n        EqualsOperation.prototype.evaluate = function(c) {\n          return this.lhs.evaluate(c).equals(this.rhs.evaluate(c));\n        };\n        NotEqualOperation.prototype = new BinaryOperation();\n        NotEqualOperation.prototype.constructor = NotEqualOperation;\n        NotEqualOperation.superclass = BinaryOperation.prototype;\n        function NotEqualOperation(lhs, rhs) {\n          if (arguments.length > 0) {\n            this.init(lhs, rhs);\n          }\n        }\n        NotEqualOperation.prototype.init = function(lhs, rhs) {\n          NotEqualOperation.superclass.init.call(this, lhs, rhs);\n        };\n        NotEqualOperation.prototype.toString = function() {\n          return "(" + this.lhs.toString() + " != " + this.rhs.toString() + ")";\n        };\n        NotEqualOperation.prototype.evaluate = function(c) {\n          return this.lhs.evaluate(c).notequal(this.rhs.evaluate(c));\n        };\n        LessThanOperation.prototype = new BinaryOperation();\n        LessThanOperation.prototype.constructor = LessThanOperation;\n        LessThanOperation.superclass = BinaryOperation.prototype;\n        function LessThanOperation(lhs, rhs) {\n          if (arguments.length > 0) {\n            this.init(lhs, rhs);\n          }\n        }\n        LessThanOperation.prototype.init = function(lhs, rhs) {\n          LessThanOperation.superclass.init.call(this, lhs, rhs);\n        };\n        LessThanOperation.prototype.evaluate = function(c) {\n          return this.lhs.evaluate(c).lessthan(this.rhs.evaluate(c));\n        };\n        LessThanOperation.prototype.toString = function() {\n          return "(" + this.lhs.toString() + " < " + this.rhs.toString() + ")";\n        };\n        GreaterThanOperation.prototype = new BinaryOperation();\n        GreaterThanOperation.prototype.constructor = GreaterThanOperation;\n        GreaterThanOperation.superclass = BinaryOperation.prototype;\n        function GreaterThanOperation(lhs, rhs) {\n          if (arguments.length > 0) {\n            this.init(lhs, rhs);\n          }\n        }\n        GreaterThanOperation.prototype.init = function(lhs, rhs) {\n          GreaterThanOperation.superclass.init.call(this, lhs, rhs);\n        };\n        GreaterThanOperation.prototype.evaluate = function(c) {\n          return this.lhs.evaluate(c).greaterthan(this.rhs.evaluate(c));\n        };\n        GreaterThanOperation.prototype.toString = function() {\n          return "(" + this.lhs.toString() + " > " + this.rhs.toString() + ")";\n        };\n        LessThanOrEqualOperation.prototype = new BinaryOperation();\n        LessThanOrEqualOperation.prototype.constructor = LessThanOrEqualOperation;\n        LessThanOrEqualOperation.superclass = BinaryOperation.prototype;\n        function LessThanOrEqualOperation(lhs, rhs) {\n          if (arguments.length > 0) {\n            this.init(lhs, rhs);\n          }\n        }\n        LessThanOrEqualOperation.prototype.init = function(lhs, rhs) {\n          LessThanOrEqualOperation.superclass.init.call(this, lhs, rhs);\n        };\n        LessThanOrEqualOperation.prototype.evaluate = function(c) {\n          return this.lhs.evaluate(c).lessthanorequal(this.rhs.evaluate(c));\n        };\n        LessThanOrEqualOperation.prototype.toString = function() {\n          return "(" + this.lhs.toString() + " <= " + this.rhs.toString() + ")";\n        };\n        GreaterThanOrEqualOperation.prototype = new BinaryOperation();\n        GreaterThanOrEqualOperation.prototype.constructor = GreaterThanOrEqualOperation;\n        GreaterThanOrEqualOperation.superclass = BinaryOperation.prototype;\n        function GreaterThanOrEqualOperation(lhs, rhs) {\n          if (arguments.length > 0) {\n            this.init(lhs, rhs);\n          }\n        }\n        GreaterThanOrEqualOperation.prototype.init = function(lhs, rhs) {\n          GreaterThanOrEqualOperation.superclass.init.call(this, lhs, rhs);\n        };\n        GreaterThanOrEqualOperation.prototype.evaluate = function(c) {\n          return this.lhs.evaluate(c).greaterthanorequal(this.rhs.evaluate(c));\n        };\n        GreaterThanOrEqualOperation.prototype.toString = function() {\n          return "(" + this.lhs.toString() + " >= " + this.rhs.toString() + ")";\n        };\n        PlusOperation.prototype = new BinaryOperation();\n        PlusOperation.prototype.constructor = PlusOperation;\n        PlusOperation.superclass = BinaryOperation.prototype;\n        function PlusOperation(lhs, rhs) {\n          if (arguments.length > 0) {\n            this.init(lhs, rhs);\n          }\n        }\n        PlusOperation.prototype.init = function(lhs, rhs) {\n          PlusOperation.superclass.init.call(this, lhs, rhs);\n        };\n        PlusOperation.prototype.evaluate = function(c) {\n          return this.lhs.evaluate(c).number().plus(this.rhs.evaluate(c).number());\n        };\n        PlusOperation.prototype.toString = function() {\n          return "(" + this.lhs.toString() + " + " + this.rhs.toString() + ")";\n        };\n        MinusOperation.prototype = new BinaryOperation();\n        MinusOperation.prototype.constructor = MinusOperation;\n        MinusOperation.superclass = BinaryOperation.prototype;\n        function MinusOperation(lhs, rhs) {\n          if (arguments.length > 0) {\n            this.init(lhs, rhs);\n          }\n        }\n        MinusOperation.prototype.init = function(lhs, rhs) {\n          MinusOperation.superclass.init.call(this, lhs, rhs);\n        };\n        MinusOperation.prototype.evaluate = function(c) {\n          return this.lhs.evaluate(c).number().minus(this.rhs.evaluate(c).number());\n        };\n        MinusOperation.prototype.toString = function() {\n          return "(" + this.lhs.toString() + " - " + this.rhs.toString() + ")";\n        };\n        MultiplyOperation.prototype = new BinaryOperation();\n        MultiplyOperation.prototype.constructor = MultiplyOperation;\n        MultiplyOperation.superclass = BinaryOperation.prototype;\n        function MultiplyOperation(lhs, rhs) {\n          if (arguments.length > 0) {\n            this.init(lhs, rhs);\n          }\n        }\n        MultiplyOperation.prototype.init = function(lhs, rhs) {\n          MultiplyOperation.superclass.init.call(this, lhs, rhs);\n        };\n        MultiplyOperation.prototype.evaluate = function(c) {\n          return this.lhs.evaluate(c).number().multiply(this.rhs.evaluate(c).number());\n        };\n        MultiplyOperation.prototype.toString = function() {\n          return "(" + this.lhs.toString() + " * " + this.rhs.toString() + ")";\n        };\n        DivOperation.prototype = new BinaryOperation();\n        DivOperation.prototype.constructor = DivOperation;\n        DivOperation.superclass = BinaryOperation.prototype;\n        function DivOperation(lhs, rhs) {\n          if (arguments.length > 0) {\n            this.init(lhs, rhs);\n          }\n        }\n        DivOperation.prototype.init = function(lhs, rhs) {\n          DivOperation.superclass.init.call(this, lhs, rhs);\n        };\n        DivOperation.prototype.evaluate = function(c) {\n          return this.lhs.evaluate(c).number().div(this.rhs.evaluate(c).number());\n        };\n        DivOperation.prototype.toString = function() {\n          return "(" + this.lhs.toString() + " div " + this.rhs.toString() + ")";\n        };\n        ModOperation.prototype = new BinaryOperation();\n        ModOperation.prototype.constructor = ModOperation;\n        ModOperation.superclass = BinaryOperation.prototype;\n        function ModOperation(lhs, rhs) {\n          if (arguments.length > 0) {\n            this.init(lhs, rhs);\n          }\n        }\n        ModOperation.prototype.init = function(lhs, rhs) {\n          ModOperation.superclass.init.call(this, lhs, rhs);\n        };\n        ModOperation.prototype.evaluate = function(c) {\n          return this.lhs.evaluate(c).number().mod(this.rhs.evaluate(c).number());\n        };\n        ModOperation.prototype.toString = function() {\n          return "(" + this.lhs.toString() + " mod " + this.rhs.toString() + ")";\n        };\n        BarOperation.prototype = new BinaryOperation();\n        BarOperation.prototype.constructor = BarOperation;\n        BarOperation.superclass = BinaryOperation.prototype;\n        function BarOperation(lhs, rhs) {\n          if (arguments.length > 0) {\n            this.init(lhs, rhs);\n          }\n        }\n        BarOperation.prototype.init = function(lhs, rhs) {\n          BarOperation.superclass.init.call(this, lhs, rhs);\n        };\n        BarOperation.prototype.evaluate = function(c) {\n          return this.lhs.evaluate(c).nodeset().union(this.rhs.evaluate(c).nodeset());\n        };\n        BarOperation.prototype.toString = function() {\n          return map(toString, [this.lhs, this.rhs]).join(" | ");\n        };\n        PathExpr.prototype = new Expression();\n        PathExpr.prototype.constructor = PathExpr;\n        PathExpr.superclass = Expression.prototype;\n        function PathExpr(filter2, filterPreds, locpath) {\n          if (arguments.length > 0) {\n            this.init(filter2, filterPreds, locpath);\n          }\n        }\n        PathExpr.prototype.init = function(filter2, filterPreds, locpath) {\n          PathExpr.superclass.init.call(this);\n          this.filter = filter2;\n          this.filterPredicates = filterPreds;\n          this.locationPath = locpath;\n        };\n        function findRoot(node) {\n          while (node && node.parentNode) {\n            node = node.parentNode;\n          }\n          return node;\n        }\n        var applyPredicates = function(predicates, c, nodes, reverse) {\n          if (predicates.length === 0) {\n            return nodes;\n          }\n          var ctx = c.extend({});\n          return reduce(\n            function(inNodes, pred) {\n              ctx.contextSize = inNodes.length;\n              return filter(\n                function(node, i) {\n                  ctx.contextNode = node;\n                  ctx.contextPosition = i + 1;\n                  return PathExpr.predicateMatches(pred, ctx);\n                },\n                inNodes\n              );\n            },\n            sortNodes(nodes, reverse),\n            predicates\n          );\n        };\n        PathExpr.getRoot = function(xpc, nodes) {\n          var firstNode = nodes[0];\n          if (firstNode && firstNode.nodeType === NodeTypes.DOCUMENT_NODE) {\n            return firstNode;\n          }\n          if (xpc.virtualRoot) {\n            return xpc.virtualRoot;\n          }\n          if (!firstNode) {\n            throw new Error("Context node not found when determining document root.");\n          }\n          var ownerDoc = firstNode.ownerDocument;\n          if (ownerDoc) {\n            return ownerDoc;\n          }\n          var n = firstNode;\n          while (n.parentNode != null) {\n            n = n.parentNode;\n          }\n          return n;\n        };\n        var getPrefixForNamespaceNode = function(attrNode) {\n          var nm = String(attrNode.name);\n          if (nm === "xmlns") {\n            return "";\n          }\n          if (nm.substring(0, 6) === "xmlns:") {\n            return nm.substring(6, nm.length);\n          }\n          return null;\n        };\n        PathExpr.applyStep = function(step, xpc, node) {\n          if (!node) {\n            throw new Error("Context node not found when evaluating XPath step: " + step);\n          }\n          var newNodes = [];\n          xpc.contextNode = node;\n          switch (step.axis) {\n            case Step.ANCESTOR:\n              if (xpc.contextNode === xpc.virtualRoot) {\n                break;\n              }\n              var m;\n              if (xpc.contextNode.nodeType == NodeTypes.ATTRIBUTE_NODE) {\n                m = PathExpr.getOwnerElement(xpc.contextNode);\n              } else {\n                m = xpc.contextNode.parentNode;\n              }\n              while (m != null) {\n                if (step.nodeTest.matches(m, xpc)) {\n                  newNodes.push(m);\n                }\n                if (m === xpc.virtualRoot) {\n                  break;\n                }\n                m = m.parentNode;\n              }\n              break;\n            case Step.ANCESTORORSELF:\n              for (var m = xpc.contextNode; m != null; m = m.nodeType == NodeTypes.ATTRIBUTE_NODE ? PathExpr.getOwnerElement(m) : m.parentNode) {\n                if (step.nodeTest.matches(m, xpc)) {\n                  newNodes.push(m);\n                }\n                if (m === xpc.virtualRoot) {\n                  break;\n                }\n              }\n              break;\n            case Step.ATTRIBUTE:\n              var nnm = xpc.contextNode.attributes;\n              if (nnm != null) {\n                for (var k = 0; k < nnm.length; k++) {\n                  var m = nnm.item(k);\n                  if (step.nodeTest.matches(m, xpc)) {\n                    newNodes.push(m);\n                  }\n                }\n              }\n              break;\n            case Step.CHILD:\n              for (var m = xpc.contextNode.firstChild; m != null; m = m.nextSibling) {\n                if (step.nodeTest.matches(m, xpc)) {\n                  newNodes.push(m);\n                }\n              }\n              break;\n            case Step.DESCENDANT:\n              var st = [xpc.contextNode.firstChild];\n              while (st.length > 0) {\n                for (var m = st.pop(); m != null; ) {\n                  if (step.nodeTest.matches(m, xpc)) {\n                    newNodes.push(m);\n                  }\n                  if (m.firstChild != null) {\n                    st.push(m.nextSibling);\n                    m = m.firstChild;\n                  } else {\n                    m = m.nextSibling;\n                  }\n                }\n              }\n              break;\n            case Step.DESCENDANTORSELF:\n              if (step.nodeTest.matches(xpc.contextNode, xpc)) {\n                newNodes.push(xpc.contextNode);\n              }\n              var st = [xpc.contextNode.firstChild];\n              while (st.length > 0) {\n                for (var m = st.pop(); m != null; ) {\n                  if (step.nodeTest.matches(m, xpc)) {\n                    newNodes.push(m);\n                  }\n                  if (m.firstChild != null) {\n                    st.push(m.nextSibling);\n                    m = m.firstChild;\n                  } else {\n                    m = m.nextSibling;\n                  }\n                }\n              }\n              break;\n            case Step.FOLLOWING:\n              if (xpc.contextNode === xpc.virtualRoot) {\n                break;\n              }\n              var st = [];\n              if (xpc.contextNode.firstChild != null) {\n                st.unshift(xpc.contextNode.firstChild);\n              } else {\n                st.unshift(xpc.contextNode.nextSibling);\n              }\n              for (var m = xpc.contextNode.parentNode; m != null && m.nodeType != NodeTypes.DOCUMENT_NODE && m !== xpc.virtualRoot; m = m.parentNode) {\n                st.unshift(m.nextSibling);\n              }\n              do {\n                for (var m = st.pop(); m != null; ) {\n                  if (step.nodeTest.matches(m, xpc)) {\n                    newNodes.push(m);\n                  }\n                  if (m.firstChild != null) {\n                    st.push(m.nextSibling);\n                    m = m.firstChild;\n                  } else {\n                    m = m.nextSibling;\n                  }\n                }\n              } while (st.length > 0);\n              break;\n            case Step.FOLLOWINGSIBLING:\n              if (xpc.contextNode === xpc.virtualRoot) {\n                break;\n              }\n              for (var m = xpc.contextNode.nextSibling; m != null; m = m.nextSibling) {\n                if (step.nodeTest.matches(m, xpc)) {\n                  newNodes.push(m);\n                }\n              }\n              break;\n            case Step.NAMESPACE:\n              var nodes = {};\n              if (xpc.contextNode.nodeType == NodeTypes.ELEMENT_NODE) {\n                nodes["xml"] = new XPathNamespace("xml", null, XPath.XML_NAMESPACE_URI, xpc.contextNode);\n                for (var m = xpc.contextNode; m != null && m.nodeType == NodeTypes.ELEMENT_NODE; m = m.parentNode) {\n                  for (var k = 0; k < m.attributes.length; k++) {\n                    var attr = m.attributes.item(k);\n                    var pre = getPrefixForNamespaceNode(attr);\n                    if (pre != null && nodes[pre] == void 0) {\n                      nodes[pre] = new XPathNamespace(pre, attr, attr.value, xpc.contextNode);\n                    }\n                  }\n                }\n                for (var pre in nodes) {\n                  var node = nodes[pre];\n                  if (step.nodeTest.matches(node, xpc)) {\n                    newNodes.push(node);\n                  }\n                }\n              }\n              break;\n            case Step.PARENT:\n              m = null;\n              if (xpc.contextNode !== xpc.virtualRoot) {\n                if (xpc.contextNode.nodeType == NodeTypes.ATTRIBUTE_NODE) {\n                  m = PathExpr.getOwnerElement(xpc.contextNode);\n                } else {\n                  m = xpc.contextNode.parentNode;\n                }\n              }\n              if (m != null && step.nodeTest.matches(m, xpc)) {\n                newNodes.push(m);\n              }\n              break;\n            case Step.PRECEDING:\n              var st;\n              if (xpc.virtualRoot != null) {\n                st = [xpc.virtualRoot];\n              } else {\n                st = [findRoot(xpc.contextNode)];\n              }\n              outer: while (st.length > 0) {\n                for (var m = st.pop(); m != null; ) {\n                  if (m == xpc.contextNode) {\n                    break outer;\n                  }\n                  if (step.nodeTest.matches(m, xpc)) {\n                    newNodes.unshift(m);\n                  }\n                  if (m.firstChild != null) {\n                    st.push(m.nextSibling);\n                    m = m.firstChild;\n                  } else {\n                    m = m.nextSibling;\n                  }\n                }\n              }\n              break;\n            case Step.PRECEDINGSIBLING:\n              if (xpc.contextNode === xpc.virtualRoot) {\n                break;\n              }\n              for (var m = xpc.contextNode.previousSibling; m != null; m = m.previousSibling) {\n                if (step.nodeTest.matches(m, xpc)) {\n                  newNodes.push(m);\n                }\n              }\n              break;\n            case Step.SELF:\n              if (step.nodeTest.matches(xpc.contextNode, xpc)) {\n                newNodes.push(xpc.contextNode);\n              }\n              break;\n            default:\n          }\n          return newNodes;\n        };\n        function applyStepWithPredicates(step, xpc, node) {\n          return applyPredicates(\n            step.predicates,\n            xpc,\n            PathExpr.applyStep(step, xpc, node),\n            includes(REVERSE_AXES, step.axis)\n          );\n        }\n        function applyStepToNodes(context, nodes, step) {\n          return flatten(\n            map(\n              applyStepWithPredicates.bind(null, step, context),\n              nodes\n            )\n          );\n        }\n        PathExpr.applySteps = function(steps, xpc, nodes) {\n          return reduce(\n            applyStepToNodes.bind(null, xpc),\n            nodes,\n            steps\n          );\n        };\n        PathExpr.prototype.applyFilter = function(c, xpc) {\n          if (!this.filter) {\n            return { nodes: [c.contextNode] };\n          }\n          var ns = this.filter.evaluate(c);\n          if (!Utilities.instance_of(ns, XNodeSet)) {\n            if (this.filterPredicates != null && this.filterPredicates.length > 0 || this.locationPath != null) {\n              throw new Error("Path expression filter must evaluate to a nodeset if predicates or location path are used");\n            }\n            return { nonNodes: ns };\n          }\n          return {\n            nodes: applyPredicates(\n              this.filterPredicates || [],\n              xpc,\n              ns.toUnsortedArray(),\n              false\n              // reverse\n            )\n          };\n        };\n        PathExpr.applyLocationPath = function(locationPath, xpc, nodes) {\n          if (!locationPath) {\n            return nodes;\n          }\n          var startNodes = locationPath.absolute ? [PathExpr.getRoot(xpc, nodes)] : nodes;\n          return PathExpr.applySteps(locationPath.steps, xpc, startNodes);\n        };\n        PathExpr.prototype.evaluate = function(c) {\n          var xpc = assign(new XPathContext(), c);\n          var filterResult = this.applyFilter(c, xpc);\n          if ("nonNodes" in filterResult) {\n            return filterResult.nonNodes;\n          }\n          var ns = new XNodeSet();\n          ns.addArray(PathExpr.applyLocationPath(this.locationPath, xpc, filterResult.nodes));\n          return ns;\n        };\n        PathExpr.predicateMatches = function(pred, c) {\n          var res = pred.evaluate(c);\n          return Utilities.instance_of(res, XNumber) ? c.contextPosition === res.numberValue() : res.booleanValue();\n        };\n        PathExpr.predicateString = function(predicate) {\n          return wrap("[", "]", predicate.toString());\n        };\n        PathExpr.predicatesString = function(predicates) {\n          return join(\n            "",\n            map(PathExpr.predicateString, predicates)\n          );\n        };\n        PathExpr.prototype.toString = function() {\n          if (this.filter != void 0) {\n            var filterStr = toString(this.filter);\n            if (Utilities.instance_of(this.filter, XString)) {\n              return wrap("\'", "\'", filterStr);\n            }\n            if (this.filterPredicates != void 0 && this.filterPredicates.length) {\n              return wrap("(", ")", filterStr) + PathExpr.predicatesString(this.filterPredicates);\n            }\n            if (this.locationPath != void 0) {\n              return filterStr + (this.locationPath.absolute ? "" : "/") + toString(this.locationPath);\n            }\n            return filterStr;\n          }\n          return toString(this.locationPath);\n        };\n        PathExpr.getOwnerElement = function(n) {\n          if (n.ownerElement) {\n            return n.ownerElement;\n          }\n          try {\n            if (n.selectSingleNode) {\n              return n.selectSingleNode("..");\n            }\n          } catch (e) {\n          }\n          var doc = n.nodeType == NodeTypes.DOCUMENT_NODE ? n : n.ownerDocument;\n          var elts = doc.getElementsByTagName("*");\n          for (var i = 0; i < elts.length; i++) {\n            var elt = elts.item(i);\n            var nnm = elt.attributes;\n            for (var j = 0; j < nnm.length; j++) {\n              var an = nnm.item(j);\n              if (an === n) {\n                return elt;\n              }\n            }\n          }\n          return null;\n        };\n        LocationPath.prototype = new Object();\n        LocationPath.prototype.constructor = LocationPath;\n        LocationPath.superclass = Object.prototype;\n        function LocationPath(abs, steps) {\n          if (arguments.length > 0) {\n            this.init(abs, steps);\n          }\n        }\n        LocationPath.prototype.init = function(abs, steps) {\n          this.absolute = abs;\n          this.steps = steps;\n        };\n        LocationPath.prototype.toString = function() {\n          return (this.absolute ? "/" : "") + map(toString, this.steps).join("/");\n        };\n        Step.prototype = new Object();\n        Step.prototype.constructor = Step;\n        Step.superclass = Object.prototype;\n        function Step(axis, nodetest, preds) {\n          if (arguments.length > 0) {\n            this.init(axis, nodetest, preds);\n          }\n        }\n        Step.prototype.init = function(axis, nodetest, preds) {\n          this.axis = axis;\n          this.nodeTest = nodetest;\n          this.predicates = preds;\n        };\n        Step.prototype.toString = function() {\n          return Step.STEPNAMES[this.axis] + "::" + this.nodeTest.toString() + PathExpr.predicatesString(this.predicates);\n        };\n        Step.ANCESTOR = 0;\n        Step.ANCESTORORSELF = 1;\n        Step.ATTRIBUTE = 2;\n        Step.CHILD = 3;\n        Step.DESCENDANT = 4;\n        Step.DESCENDANTORSELF = 5;\n        Step.FOLLOWING = 6;\n        Step.FOLLOWINGSIBLING = 7;\n        Step.NAMESPACE = 8;\n        Step.PARENT = 9;\n        Step.PRECEDING = 10;\n        Step.PRECEDINGSIBLING = 11;\n        Step.SELF = 12;\n        Step.STEPNAMES = reduce(function(acc, x) {\n          return acc[x[0]] = x[1], acc;\n        }, {}, [\n          [Step.ANCESTOR, "ancestor"],\n          [Step.ANCESTORORSELF, "ancestor-or-self"],\n          [Step.ATTRIBUTE, "attribute"],\n          [Step.CHILD, "child"],\n          [Step.DESCENDANT, "descendant"],\n          [Step.DESCENDANTORSELF, "descendant-or-self"],\n          [Step.FOLLOWING, "following"],\n          [Step.FOLLOWINGSIBLING, "following-sibling"],\n          [Step.NAMESPACE, "namespace"],\n          [Step.PARENT, "parent"],\n          [Step.PRECEDING, "preceding"],\n          [Step.PRECEDINGSIBLING, "preceding-sibling"],\n          [Step.SELF, "self"]\n        ]);\n        var REVERSE_AXES = [\n          Step.ANCESTOR,\n          Step.ANCESTORORSELF,\n          Step.PARENT,\n          Step.PRECEDING,\n          Step.PRECEDINGSIBLING\n        ];\n        NodeTest.prototype = new Object();\n        NodeTest.prototype.constructor = NodeTest;\n        NodeTest.superclass = Object.prototype;\n        function NodeTest(type, value) {\n          if (arguments.length > 0) {\n            this.init(type, value);\n          }\n        }\n        NodeTest.prototype.init = function(type, value) {\n          this.type = type;\n          this.value = value;\n        };\n        NodeTest.prototype.toString = function() {\n          return "<unknown nodetest type>";\n        };\n        NodeTest.prototype.matches = function(n, xpc) {\n          console.warn("unknown node test type");\n        };\n        NodeTest.NAMETESTANY = 0;\n        NodeTest.NAMETESTPREFIXANY = 1;\n        NodeTest.NAMETESTQNAME = 2;\n        NodeTest.COMMENT = 3;\n        NodeTest.TEXT = 4;\n        NodeTest.PI = 5;\n        NodeTest.NODE = 6;\n        NodeTest.isNodeType = function(types) {\n          return function(node) {\n            return includes(types, node.nodeType);\n          };\n        };\n        NodeTest.makeNodeTestType = function(type, members, ctor) {\n          var newType = ctor || function() {\n          };\n          newType.prototype = new NodeTest(type);\n          newType.prototype.constructor = newType;\n          assign(newType.prototype, members);\n          return newType;\n        };\n        NodeTest.makeNodeTypeTest = function(type, nodeTypes, stringVal) {\n          return new (NodeTest.makeNodeTestType(type, {\n            matches: NodeTest.isNodeType(nodeTypes),\n            toString: always(stringVal)\n          }))();\n        };\n        NodeTest.hasPrefix = function(node) {\n          return node.prefix || (node.nodeName || node.tagName).indexOf(":") !== -1;\n        };\n        NodeTest.isElementOrAttribute = NodeTest.isNodeType([1, 2]);\n        NodeTest.nameSpaceMatches = function(prefix, xpc, n) {\n          var nNamespace = n.namespaceURI || "";\n          if (!prefix) {\n            return !nNamespace || xpc.allowAnyNamespaceForNoPrefix && !NodeTest.hasPrefix(n);\n          }\n          var ns = xpc.namespaceResolver.getNamespace(prefix, xpc.expressionContextNode);\n          if (ns == null) {\n            throw new Error("Cannot resolve QName " + prefix);\n          }\n          return ns === nNamespace;\n        };\n        NodeTest.localNameMatches = function(localName, xpc, n) {\n          var nLocalName = n.localName || n.nodeName;\n          return xpc.caseInsensitive ? localName.toLowerCase() === nLocalName.toLowerCase() : localName === nLocalName;\n        };\n        NodeTest.NameTestPrefixAny = NodeTest.makeNodeTestType(\n          NodeTest.NAMETESTPREFIXANY,\n          {\n            matches: function(n, xpc) {\n              return NodeTest.isElementOrAttribute(n) && NodeTest.nameSpaceMatches(this.prefix, xpc, n);\n            },\n            toString: function() {\n              return this.prefix + ":*";\n            }\n          },\n          function NameTestPrefixAny(prefix) {\n            this.prefix = prefix;\n          }\n        );\n        NodeTest.NameTestQName = NodeTest.makeNodeTestType(\n          NodeTest.NAMETESTQNAME,\n          {\n            matches: function(n, xpc) {\n              return NodeTest.isNodeType(\n                [\n                  NodeTypes.ELEMENT_NODE,\n                  NodeTypes.ATTRIBUTE_NODE,\n                  NodeTypes.NAMESPACE_NODE\n                ]\n              )(n) && NodeTest.nameSpaceMatches(this.prefix, xpc, n) && NodeTest.localNameMatches(this.localName, xpc, n);\n            },\n            toString: function() {\n              return this.name;\n            }\n          },\n          function NameTestQName(name2) {\n            var nameParts = name2.split(":");\n            this.name = name2;\n            this.prefix = nameParts.length > 1 ? nameParts[0] : null;\n            this.localName = nameParts[nameParts.length > 1 ? 1 : 0];\n          }\n        );\n        NodeTest.PITest = NodeTest.makeNodeTestType(NodeTest.PI, {\n          matches: function(n, xpc) {\n            return NodeTest.isNodeType(\n              [NodeTypes.PROCESSING_INSTRUCTION_NODE]\n            )(n) && (n.target || n.nodeName) === this.name;\n          },\n          toString: function() {\n            return wrap(\'processing-instruction("\', \'")\', this.name);\n          }\n        }, function(name2) {\n          this.name = name2;\n        });\n        NodeTest.nameTestAny = NodeTest.makeNodeTypeTest(\n          NodeTest.NAMETESTANY,\n          [\n            NodeTypes.ELEMENT_NODE,\n            NodeTypes.ATTRIBUTE_NODE,\n            NodeTypes.NAMESPACE_NODE\n          ],\n          "*"\n        );\n        NodeTest.textTest = NodeTest.makeNodeTypeTest(\n          NodeTest.TEXT,\n          [\n            NodeTypes.TEXT_NODE,\n            NodeTypes.CDATA_SECTION_NODE\n          ],\n          "text()"\n        );\n        NodeTest.commentTest = NodeTest.makeNodeTypeTest(\n          NodeTest.COMMENT,\n          [NodeTypes.COMMENT_NODE],\n          "comment()"\n        );\n        NodeTest.nodeTest = NodeTest.makeNodeTypeTest(\n          NodeTest.NODE,\n          [\n            NodeTypes.ELEMENT_NODE,\n            NodeTypes.ATTRIBUTE_NODE,\n            NodeTypes.TEXT_NODE,\n            NodeTypes.CDATA_SECTION_NODE,\n            NodeTypes.PROCESSING_INSTRUCTION_NODE,\n            NodeTypes.COMMENT_NODE,\n            NodeTypes.DOCUMENT_NODE\n          ],\n          "node()"\n        );\n        NodeTest.anyPiTest = NodeTest.makeNodeTypeTest(\n          NodeTest.PI,\n          [NodeTypes.PROCESSING_INSTRUCTION_NODE],\n          "processing-instruction()"\n        );\n        VariableReference.prototype = new Expression();\n        VariableReference.prototype.constructor = VariableReference;\n        VariableReference.superclass = Expression.prototype;\n        function VariableReference(v) {\n          if (arguments.length > 0) {\n            this.init(v);\n          }\n        }\n        VariableReference.prototype.init = function(v) {\n          this.variable = v;\n        };\n        VariableReference.prototype.toString = function() {\n          return "$" + this.variable;\n        };\n        VariableReference.prototype.evaluate = function(c) {\n          var parts = Utilities.resolveQName(this.variable, c.namespaceResolver, c.contextNode, false);\n          if (parts[0] == null) {\n            throw new Error("Cannot resolve QName " + fn);\n          }\n          var result = c.variableResolver.getVariable(parts[1], parts[0]);\n          if (!result) {\n            throw XPathException.fromMessage("Undeclared variable: " + this.toString());\n          }\n          return result;\n        };\n        FunctionCall.prototype = new Expression();\n        FunctionCall.prototype.constructor = FunctionCall;\n        FunctionCall.superclass = Expression.prototype;\n        function FunctionCall(fn2, args) {\n          if (arguments.length > 0) {\n            this.init(fn2, args);\n          }\n        }\n        FunctionCall.prototype.init = function(fn2, args) {\n          this.functionName = fn2;\n          this.arguments = args;\n        };\n        FunctionCall.prototype.toString = function() {\n          var s = this.functionName + "(";\n          for (var i = 0; i < this.arguments.length; i++) {\n            if (i > 0) {\n              s += ", ";\n            }\n            s += this.arguments[i].toString();\n          }\n          return s + ")";\n        };\n        FunctionCall.prototype.evaluate = function(c) {\n          var f = FunctionResolver.getFunctionFromContext(this.functionName, c);\n          if (!f) {\n            throw new Error("Unknown function " + this.functionName);\n          }\n          var a = [c].concat(this.arguments);\n          return f.apply(c.functionResolver.thisArg, a);\n        };\n        var Operators = new Object();\n        Operators.equals = function(l, r) {\n          return l.equals(r);\n        };\n        Operators.notequal = function(l, r) {\n          return l.notequal(r);\n        };\n        Operators.lessthan = function(l, r) {\n          return l.lessthan(r);\n        };\n        Operators.greaterthan = function(l, r) {\n          return l.greaterthan(r);\n        };\n        Operators.lessthanorequal = function(l, r) {\n          return l.lessthanorequal(r);\n        };\n        Operators.greaterthanorequal = function(l, r) {\n          return l.greaterthanorequal(r);\n        };\n        XString.prototype = new Expression();\n        XString.prototype.constructor = XString;\n        XString.superclass = Expression.prototype;\n        function XString(s) {\n          if (arguments.length > 0) {\n            this.init(s);\n          }\n        }\n        XString.prototype.init = function(s) {\n          this.str = String(s);\n        };\n        XString.prototype.toString = function() {\n          return this.str;\n        };\n        XString.prototype.evaluate = function(c) {\n          return this;\n        };\n        XString.prototype.string = function() {\n          return this;\n        };\n        XString.prototype.number = function() {\n          return new XNumber(this.str);\n        };\n        XString.prototype.bool = function() {\n          return new XBoolean(this.str);\n        };\n        XString.prototype.nodeset = function() {\n          throw new Error("Cannot convert string to nodeset");\n        };\n        XString.prototype.stringValue = function() {\n          return this.str;\n        };\n        XString.prototype.numberValue = function() {\n          return this.number().numberValue();\n        };\n        XString.prototype.booleanValue = function() {\n          return this.bool().booleanValue();\n        };\n        XString.prototype.equals = function(r) {\n          if (Utilities.instance_of(r, XBoolean)) {\n            return this.bool().equals(r);\n          }\n          if (Utilities.instance_of(r, XNumber)) {\n            return this.number().equals(r);\n          }\n          if (Utilities.instance_of(r, XNodeSet)) {\n            return r.compareWithString(this, Operators.equals);\n          }\n          return new XBoolean(this.str == r.str);\n        };\n        XString.prototype.notequal = function(r) {\n          if (Utilities.instance_of(r, XBoolean)) {\n            return this.bool().notequal(r);\n          }\n          if (Utilities.instance_of(r, XNumber)) {\n            return this.number().notequal(r);\n          }\n          if (Utilities.instance_of(r, XNodeSet)) {\n            return r.compareWithString(this, Operators.notequal);\n          }\n          return new XBoolean(this.str != r.str);\n        };\n        XString.prototype.lessthan = function(r) {\n          return this.number().lessthan(r);\n        };\n        XString.prototype.greaterthan = function(r) {\n          return this.number().greaterthan(r);\n        };\n        XString.prototype.lessthanorequal = function(r) {\n          return this.number().lessthanorequal(r);\n        };\n        XString.prototype.greaterthanorequal = function(r) {\n          return this.number().greaterthanorequal(r);\n        };\n        XNumber.prototype = new Expression();\n        XNumber.prototype.constructor = XNumber;\n        XNumber.superclass = Expression.prototype;\n        function XNumber(n) {\n          if (arguments.length > 0) {\n            this.init(n);\n          }\n        }\n        XNumber.prototype.init = function(n) {\n          this.num = typeof n === "string" ? this.parse(n) : Number(n);\n        };\n        XNumber.prototype.numberFormat = /^\\s*-?[0-9]*\\.?[0-9]+\\s*$/;\n        XNumber.prototype.parse = function(s) {\n          return this.numberFormat.test(s) ? parseFloat(s) : Number.NaN;\n        };\n        function padSmallNumber(numberStr) {\n          var parts = numberStr.split("e-");\n          var base = parts[0].replace(".", "");\n          var exponent = Number(parts[1]);\n          for (var i = 0; i < exponent - 1; i += 1) {\n            base = "0" + base;\n          }\n          return "0." + base;\n        }\n        function padLargeNumber(numberStr) {\n          var parts = numberStr.split("e");\n          var base = parts[0].replace(".", "");\n          var exponent = Number(parts[1]);\n          var zerosToAppend = exponent + 1 - base.length;\n          for (var i = 0; i < zerosToAppend; i += 1) {\n            base += "0";\n          }\n          return base;\n        }\n        XNumber.prototype.toString = function() {\n          var strValue = this.num.toString();\n          if (strValue.indexOf("e-") !== -1) {\n            return padSmallNumber(strValue);\n          }\n          if (strValue.indexOf("e") !== -1) {\n            return padLargeNumber(strValue);\n          }\n          return strValue;\n        };\n        XNumber.prototype.evaluate = function(c) {\n          return this;\n        };\n        XNumber.prototype.string = function() {\n          return new XString(this.toString());\n        };\n        XNumber.prototype.number = function() {\n          return this;\n        };\n        XNumber.prototype.bool = function() {\n          return new XBoolean(this.num);\n        };\n        XNumber.prototype.nodeset = function() {\n          throw new Error("Cannot convert number to nodeset");\n        };\n        XNumber.prototype.stringValue = function() {\n          return this.string().stringValue();\n        };\n        XNumber.prototype.numberValue = function() {\n          return this.num;\n        };\n        XNumber.prototype.booleanValue = function() {\n          return this.bool().booleanValue();\n        };\n        XNumber.prototype.negate = function() {\n          return new XNumber(-this.num);\n        };\n        XNumber.prototype.equals = function(r) {\n          if (Utilities.instance_of(r, XBoolean)) {\n            return this.bool().equals(r);\n          }\n          if (Utilities.instance_of(r, XString)) {\n            return this.equals(r.number());\n          }\n          if (Utilities.instance_of(r, XNodeSet)) {\n            return r.compareWithNumber(this, Operators.equals);\n          }\n          return new XBoolean(this.num == r.num);\n        };\n        XNumber.prototype.notequal = function(r) {\n          if (Utilities.instance_of(r, XBoolean)) {\n            return this.bool().notequal(r);\n          }\n          if (Utilities.instance_of(r, XString)) {\n            return this.notequal(r.number());\n          }\n          if (Utilities.instance_of(r, XNodeSet)) {\n            return r.compareWithNumber(this, Operators.notequal);\n          }\n          return new XBoolean(this.num != r.num);\n        };\n        XNumber.prototype.lessthan = function(r) {\n          if (Utilities.instance_of(r, XNodeSet)) {\n            return r.compareWithNumber(this, Operators.greaterthan);\n          }\n          if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) {\n            return this.lessthan(r.number());\n          }\n          return new XBoolean(this.num < r.num);\n        };\n        XNumber.prototype.greaterthan = function(r) {\n          if (Utilities.instance_of(r, XNodeSet)) {\n            return r.compareWithNumber(this, Operators.lessthan);\n          }\n          if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) {\n            return this.greaterthan(r.number());\n          }\n          return new XBoolean(this.num > r.num);\n        };\n        XNumber.prototype.lessthanorequal = function(r) {\n          if (Utilities.instance_of(r, XNodeSet)) {\n            return r.compareWithNumber(this, Operators.greaterthanorequal);\n          }\n          if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) {\n            return this.lessthanorequal(r.number());\n          }\n          return new XBoolean(this.num <= r.num);\n        };\n        XNumber.prototype.greaterthanorequal = function(r) {\n          if (Utilities.instance_of(r, XNodeSet)) {\n            return r.compareWithNumber(this, Operators.lessthanorequal);\n          }\n          if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) {\n            return this.greaterthanorequal(r.number());\n          }\n          return new XBoolean(this.num >= r.num);\n        };\n        XNumber.prototype.plus = function(r) {\n          return new XNumber(this.num + r.num);\n        };\n        XNumber.prototype.minus = function(r) {\n          return new XNumber(this.num - r.num);\n        };\n        XNumber.prototype.multiply = function(r) {\n          return new XNumber(this.num * r.num);\n        };\n        XNumber.prototype.div = function(r) {\n          return new XNumber(this.num / r.num);\n        };\n        XNumber.prototype.mod = function(r) {\n          return new XNumber(this.num % r.num);\n        };\n        XBoolean.prototype = new Expression();\n        XBoolean.prototype.constructor = XBoolean;\n        XBoolean.superclass = Expression.prototype;\n        function XBoolean(b) {\n          if (arguments.length > 0) {\n            this.init(b);\n          }\n        }\n        XBoolean.prototype.init = function(b) {\n          this.b = Boolean(b);\n        };\n        XBoolean.prototype.toString = function() {\n          return this.b.toString();\n        };\n        XBoolean.prototype.evaluate = function(c) {\n          return this;\n        };\n        XBoolean.prototype.string = function() {\n          return new XString(this.b);\n        };\n        XBoolean.prototype.number = function() {\n          return new XNumber(this.b);\n        };\n        XBoolean.prototype.bool = function() {\n          return this;\n        };\n        XBoolean.prototype.nodeset = function() {\n          throw new Error("Cannot convert boolean to nodeset");\n        };\n        XBoolean.prototype.stringValue = function() {\n          return this.string().stringValue();\n        };\n        XBoolean.prototype.numberValue = function() {\n          return this.number().numberValue();\n        };\n        XBoolean.prototype.booleanValue = function() {\n          return this.b;\n        };\n        XBoolean.prototype.not = function() {\n          return new XBoolean(!this.b);\n        };\n        XBoolean.prototype.equals = function(r) {\n          if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) {\n            return this.equals(r.bool());\n          }\n          if (Utilities.instance_of(r, XNodeSet)) {\n            return r.compareWithBoolean(this, Operators.equals);\n          }\n          return new XBoolean(this.b == r.b);\n        };\n        XBoolean.prototype.notequal = function(r) {\n          if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) {\n            return this.notequal(r.bool());\n          }\n          if (Utilities.instance_of(r, XNodeSet)) {\n            return r.compareWithBoolean(this, Operators.notequal);\n          }\n          return new XBoolean(this.b != r.b);\n        };\n        XBoolean.prototype.lessthan = function(r) {\n          return this.number().lessthan(r);\n        };\n        XBoolean.prototype.greaterthan = function(r) {\n          return this.number().greaterthan(r);\n        };\n        XBoolean.prototype.lessthanorequal = function(r) {\n          return this.number().lessthanorequal(r);\n        };\n        XBoolean.prototype.greaterthanorequal = function(r) {\n          return this.number().greaterthanorequal(r);\n        };\n        XBoolean.true_ = new XBoolean(true);\n        XBoolean.false_ = new XBoolean(false);\n        AVLTree.prototype = new Object();\n        AVLTree.prototype.constructor = AVLTree;\n        AVLTree.superclass = Object.prototype;\n        function AVLTree(n) {\n          this.init(n);\n        }\n        AVLTree.prototype.init = function(n) {\n          this.left = null;\n          this.right = null;\n          this.node = n;\n          this.depth = 1;\n        };\n        AVLTree.prototype.balance = function() {\n          var ldepth = this.left == null ? 0 : this.left.depth;\n          var rdepth = this.right == null ? 0 : this.right.depth;\n          if (ldepth > rdepth + 1) {\n            var lldepth = this.left.left == null ? 0 : this.left.left.depth;\n            var lrdepth = this.left.right == null ? 0 : this.left.right.depth;\n            if (lldepth < lrdepth) {\n              this.left.rotateRR();\n            }\n            this.rotateLL();\n          } else if (ldepth + 1 < rdepth) {\n            var rrdepth = this.right.right == null ? 0 : this.right.right.depth;\n            var rldepth = this.right.left == null ? 0 : this.right.left.depth;\n            if (rldepth > rrdepth) {\n              this.right.rotateLL();\n            }\n            this.rotateRR();\n          }\n        };\n        AVLTree.prototype.rotateLL = function() {\n          var nodeBefore = this.node;\n          var rightBefore = this.right;\n          this.node = this.left.node;\n          this.right = this.left;\n          this.left = this.left.left;\n          this.right.left = this.right.right;\n          this.right.right = rightBefore;\n          this.right.node = nodeBefore;\n          this.right.updateInNewLocation();\n          this.updateInNewLocation();\n        };\n        AVLTree.prototype.rotateRR = function() {\n          var nodeBefore = this.node;\n          var leftBefore = this.left;\n          this.node = this.right.node;\n          this.left = this.right;\n          this.right = this.right.right;\n          this.left.right = this.left.left;\n          this.left.left = leftBefore;\n          this.left.node = nodeBefore;\n          this.left.updateInNewLocation();\n          this.updateInNewLocation();\n        };\n        AVLTree.prototype.updateInNewLocation = function() {\n          this.getDepthFromChildren();\n        };\n        AVLTree.prototype.getDepthFromChildren = function() {\n          this.depth = this.node == null ? 0 : 1;\n          if (this.left != null) {\n            this.depth = this.left.depth + 1;\n          }\n          if (this.right != null && this.depth <= this.right.depth) {\n            this.depth = this.right.depth + 1;\n          }\n        };\n        function nodeOrder(n1, n2) {\n          if (n1 === n2) {\n            return 0;\n          }\n          if (n1.compareDocumentPosition) {\n            var cpos = n1.compareDocumentPosition(n2);\n            if (cpos & 1) {\n              return 1;\n            }\n            if (cpos & 10) {\n              return 1;\n            }\n            if (cpos & 20) {\n              return -1;\n            }\n            return 0;\n          }\n          var d1 = 0, d2 = 0;\n          for (var m1 = n1; m1 != null; m1 = m1.parentNode || m1.ownerElement) {\n            d1++;\n          }\n          for (var m2 = n2; m2 != null; m2 = m2.parentNode || m2.ownerElement) {\n            d2++;\n          }\n          if (d1 > d2) {\n            while (d1 > d2) {\n              n1 = n1.parentNode || n1.ownerElement;\n              d1--;\n            }\n            if (n1 === n2) {\n              return 1;\n            }\n          } else if (d2 > d1) {\n            while (d2 > d1) {\n              n2 = n2.parentNode || n2.ownerElement;\n              d2--;\n            }\n            if (n1 === n2) {\n              return -1;\n            }\n          }\n          var n1Par = n1.parentNode || n1.ownerElement, n2Par = n2.parentNode || n2.ownerElement;\n          while (n1Par !== n2Par) {\n            n1 = n1Par;\n            n2 = n2Par;\n            n1Par = n1.parentNode || n1.ownerElement;\n            n2Par = n2.parentNode || n2.ownerElement;\n          }\n          var n1isAttr = isAttributeLike(n1);\n          var n2isAttr = isAttributeLike(n2);\n          if (n1isAttr && !n2isAttr) {\n            return -1;\n          }\n          if (!n1isAttr && n2isAttr) {\n            return 1;\n          }\n          if (n1.isXPathNamespace) {\n            if (n1.nodeValue === XPath.XML_NAMESPACE_URI) {\n              return -1;\n            }\n            if (!n2.isXPathNamespace) {\n              return -1;\n            }\n            if (n2.nodeValue === XPath.XML_NAMESPACE_URI) {\n              return 1;\n            }\n          } else if (n2.isXPathNamespace) {\n            return 1;\n          }\n          if (n1Par) {\n            var cn = n1isAttr ? n1Par.attributes : n1Par.childNodes;\n            var len = cn.length;\n            var n1Compare = n1.baseNode || n1;\n            var n2Compare = n2.baseNode || n2;\n            for (var i = 0; i < len; i += 1) {\n              var n = cn[i];\n              if (n === n1Compare) {\n                return -1;\n              }\n              if (n === n2Compare) {\n                return 1;\n              }\n            }\n          }\n          throw new Error("Unexpected: could not determine node order");\n        }\n        AVLTree.prototype.add = function(n) {\n          if (n === this.node) {\n            return false;\n          }\n          var o = nodeOrder(n, this.node);\n          var ret = false;\n          if (o == -1) {\n            if (this.left == null) {\n              this.left = new AVLTree(n);\n              ret = true;\n            } else {\n              ret = this.left.add(n);\n              if (ret) {\n                this.balance();\n              }\n            }\n          } else if (o == 1) {\n            if (this.right == null) {\n              this.right = new AVLTree(n);\n              ret = true;\n            } else {\n              ret = this.right.add(n);\n              if (ret) {\n                this.balance();\n              }\n            }\n          }\n          if (ret) {\n            this.getDepthFromChildren();\n          }\n          return ret;\n        };\n        XNodeSet.prototype = new Expression();\n        XNodeSet.prototype.constructor = XNodeSet;\n        XNodeSet.superclass = Expression.prototype;\n        function XNodeSet() {\n          this.init();\n        }\n        XNodeSet.prototype.init = function() {\n          this.tree = null;\n          this.nodes = [];\n          this.size = 0;\n        };\n        XNodeSet.prototype.toString = function() {\n          var p = this.first();\n          if (p == null) {\n            return "";\n          }\n          return this.stringForNode(p);\n        };\n        XNodeSet.prototype.evaluate = function(c) {\n          return this;\n        };\n        XNodeSet.prototype.string = function() {\n          return new XString(this.toString());\n        };\n        XNodeSet.prototype.stringValue = function() {\n          return this.toString();\n        };\n        XNodeSet.prototype.number = function() {\n          return new XNumber(this.string());\n        };\n        XNodeSet.prototype.numberValue = function() {\n          return Number(this.string());\n        };\n        XNodeSet.prototype.bool = function() {\n          return new XBoolean(this.booleanValue());\n        };\n        XNodeSet.prototype.booleanValue = function() {\n          return !!this.size;\n        };\n        XNodeSet.prototype.nodeset = function() {\n          return this;\n        };\n        XNodeSet.prototype.stringForNode = function(n) {\n          if (n.nodeType == NodeTypes.DOCUMENT_NODE || n.nodeType == NodeTypes.ELEMENT_NODE || n.nodeType === NodeTypes.DOCUMENT_FRAGMENT_NODE) {\n            return this.stringForContainerNode(n);\n          }\n          if (n.nodeType === NodeTypes.ATTRIBUTE_NODE) {\n            return n.value || n.nodeValue;\n          }\n          if (n.isNamespaceNode) {\n            return n.namespace;\n          }\n          return n.nodeValue;\n        };\n        XNodeSet.prototype.stringForContainerNode = function(n) {\n          var s = "";\n          for (var n2 = n.firstChild; n2 != null; n2 = n2.nextSibling) {\n            var nt = n2.nodeType;\n            if (nt === 1 || nt === 3 || nt === 4 || nt === 9 || nt === 11) {\n              s += this.stringForNode(n2);\n            }\n          }\n          return s;\n        };\n        XNodeSet.prototype.buildTree = function() {\n          if (!this.tree && this.nodes.length) {\n            this.tree = new AVLTree(this.nodes[0]);\n            for (var i = 1; i < this.nodes.length; i += 1) {\n              this.tree.add(this.nodes[i]);\n            }\n          }\n          return this.tree;\n        };\n        XNodeSet.prototype.first = function() {\n          var p = this.buildTree();\n          if (p == null) {\n            return null;\n          }\n          while (p.left != null) {\n            p = p.left;\n          }\n          return p.node;\n        };\n        XNodeSet.prototype.add = function(n) {\n          for (var i = 0; i < this.nodes.length; i += 1) {\n            if (n === this.nodes[i]) {\n              return;\n            }\n          }\n          this.tree = null;\n          this.nodes.push(n);\n          this.size += 1;\n        };\n        XNodeSet.prototype.addArray = function(ns) {\n          var self = this;\n          forEach(function(x) {\n            self.add(x);\n          }, ns);\n        };\n        XNodeSet.prototype.toArray = function() {\n          var a = [];\n          this.toArrayRec(this.buildTree(), a);\n          return a;\n        };\n        XNodeSet.prototype.toArrayRec = function(t, a) {\n          if (t != null) {\n            this.toArrayRec(t.left, a);\n            a.push(t.node);\n            this.toArrayRec(t.right, a);\n          }\n        };\n        XNodeSet.prototype.toUnsortedArray = function() {\n          return this.nodes.slice();\n        };\n        XNodeSet.prototype.compareWithString = function(r, o) {\n          var a = this.toUnsortedArray();\n          for (var i = 0; i < a.length; i++) {\n            var n = a[i];\n            var l = new XString(this.stringForNode(n));\n            var res = o(l, r);\n            if (res.booleanValue()) {\n              return res;\n            }\n          }\n          return new XBoolean(false);\n        };\n        XNodeSet.prototype.compareWithNumber = function(r, o) {\n          var a = this.toUnsortedArray();\n          for (var i = 0; i < a.length; i++) {\n            var n = a[i];\n            var l = new XNumber(this.stringForNode(n));\n            var res = o(l, r);\n            if (res.booleanValue()) {\n              return res;\n            }\n          }\n          return new XBoolean(false);\n        };\n        XNodeSet.prototype.compareWithBoolean = function(r, o) {\n          return o(this.bool(), r);\n        };\n        XNodeSet.prototype.compareWithNodeSet = function(r, o) {\n          var arr = this.toUnsortedArray();\n          var oInvert = function(lop, rop) {\n            return o(rop, lop);\n          };\n          for (var i = 0; i < arr.length; i++) {\n            var l = new XString(this.stringForNode(arr[i]));\n            var res = r.compareWithString(l, oInvert);\n            if (res.booleanValue()) {\n              return res;\n            }\n          }\n          return new XBoolean(false);\n        };\n        XNodeSet.compareWith = curry(function(o, r) {\n          if (Utilities.instance_of(r, XString)) {\n            return this.compareWithString(r, o);\n          }\n          if (Utilities.instance_of(r, XNumber)) {\n            return this.compareWithNumber(r, o);\n          }\n          if (Utilities.instance_of(r, XBoolean)) {\n            return this.compareWithBoolean(r, o);\n          }\n          return this.compareWithNodeSet(r, o);\n        });\n        XNodeSet.prototype.equals = XNodeSet.compareWith(Operators.equals);\n        XNodeSet.prototype.notequal = XNodeSet.compareWith(Operators.notequal);\n        XNodeSet.prototype.lessthan = XNodeSet.compareWith(Operators.lessthan);\n        XNodeSet.prototype.greaterthan = XNodeSet.compareWith(Operators.greaterthan);\n        XNodeSet.prototype.lessthanorequal = XNodeSet.compareWith(Operators.lessthanorequal);\n        XNodeSet.prototype.greaterthanorequal = XNodeSet.compareWith(Operators.greaterthanorequal);\n        XNodeSet.prototype.union = function(r) {\n          var ns = new XNodeSet();\n          ns.addArray(this.toUnsortedArray());\n          ns.addArray(r.toUnsortedArray());\n          return ns;\n        };\n        XPathNamespace.prototype = new Object();\n        XPathNamespace.prototype.constructor = XPathNamespace;\n        XPathNamespace.superclass = Object.prototype;\n        function XPathNamespace(pre, node, uri, p) {\n          this.isXPathNamespace = true;\n          this.baseNode = node;\n          this.ownerDocument = p.ownerDocument;\n          this.nodeName = pre;\n          this.prefix = pre;\n          this.localName = pre;\n          this.namespaceURI = null;\n          this.nodeValue = uri;\n          this.ownerElement = p;\n          this.nodeType = NodeTypes.NAMESPACE_NODE;\n        }\n        XPathNamespace.prototype.toString = function() {\n          return \'{ "\' + this.prefix + \'", "\' + this.namespaceURI + \'" }\';\n        };\n        XPathContext.prototype = new Object();\n        XPathContext.prototype.constructor = XPathContext;\n        XPathContext.superclass = Object.prototype;\n        function XPathContext(vr, nr, fr) {\n          this.variableResolver = vr != null ? vr : new VariableResolver();\n          this.namespaceResolver = nr != null ? nr : new NamespaceResolver();\n          this.functionResolver = fr != null ? fr : new FunctionResolver();\n        }\n        XPathContext.prototype.extend = function(newProps) {\n          return assign(new XPathContext(), this, newProps);\n        };\n        VariableResolver.prototype = new Object();\n        VariableResolver.prototype.constructor = VariableResolver;\n        VariableResolver.superclass = Object.prototype;\n        function VariableResolver() {\n        }\n        VariableResolver.prototype.getVariable = function(ln, ns) {\n          return null;\n        };\n        FunctionResolver.prototype = new Object();\n        FunctionResolver.prototype.constructor = FunctionResolver;\n        FunctionResolver.superclass = Object.prototype;\n        function FunctionResolver(thisArg) {\n          this.thisArg = thisArg != null ? thisArg : Functions;\n          this.functions = new Object();\n          this.addStandardFunctions();\n        }\n        FunctionResolver.prototype.addStandardFunctions = function() {\n          this.functions["{}last"] = Functions.last;\n          this.functions["{}position"] = Functions.position;\n          this.functions["{}count"] = Functions.count;\n          this.functions["{}id"] = Functions.id;\n          this.functions["{}local-name"] = Functions.localName;\n          this.functions["{}namespace-uri"] = Functions.namespaceURI;\n          this.functions["{}name"] = Functions.name;\n          this.functions["{}string"] = Functions.string;\n          this.functions["{}concat"] = Functions.concat;\n          this.functions["{}starts-with"] = Functions.startsWith;\n          this.functions["{}contains"] = Functions.contains;\n          this.functions["{}substring-before"] = Functions.substringBefore;\n          this.functions["{}substring-after"] = Functions.substringAfter;\n          this.functions["{}substring"] = Functions.substring;\n          this.functions["{}string-length"] = Functions.stringLength;\n          this.functions["{}normalize-space"] = Functions.normalizeSpace;\n          this.functions["{}translate"] = Functions.translate;\n          this.functions["{}boolean"] = Functions.boolean_;\n          this.functions["{}not"] = Functions.not;\n          this.functions["{}true"] = Functions.true_;\n          this.functions["{}false"] = Functions.false_;\n          this.functions["{}lang"] = Functions.lang;\n          this.functions["{}number"] = Functions.number;\n          this.functions["{}sum"] = Functions.sum;\n          this.functions["{}floor"] = Functions.floor;\n          this.functions["{}ceiling"] = Functions.ceiling;\n          this.functions["{}round"] = Functions.round;\n        };\n        FunctionResolver.prototype.addFunction = function(ns, ln, f) {\n          this.functions["{" + ns + "}" + ln] = f;\n        };\n        FunctionResolver.getFunctionFromContext = function(qName, context) {\n          var parts = Utilities.resolveQName(qName, context.namespaceResolver, context.contextNode, false);\n          if (parts[0] === null) {\n            throw new Error("Cannot resolve QName " + name);\n          }\n          return context.functionResolver.getFunction(parts[1], parts[0]);\n        };\n        FunctionResolver.prototype.getFunction = function(localName, namespace) {\n          return this.functions["{" + namespace + "}" + localName];\n        };\n        NamespaceResolver.prototype = new Object();\n        NamespaceResolver.prototype.constructor = NamespaceResolver;\n        NamespaceResolver.superclass = Object.prototype;\n        function NamespaceResolver() {\n        }\n        NamespaceResolver.prototype.getNamespace = function(prefix, n) {\n          if (prefix == "xml") {\n            return XPath.XML_NAMESPACE_URI;\n          } else if (prefix == "xmlns") {\n            return XPath.XMLNS_NAMESPACE_URI;\n          }\n          if (n.nodeType == NodeTypes.DOCUMENT_NODE) {\n            n = n.documentElement;\n          } else if (n.nodeType == NodeTypes.ATTRIBUTE_NODE) {\n            n = PathExpr.getOwnerElement(n);\n          } else if (n.nodeType != NodeTypes.ELEMENT_NODE) {\n            n = n.parentNode;\n          }\n          while (n != null && n.nodeType == NodeTypes.ELEMENT_NODE) {\n            var nnm = n.attributes;\n            for (var i = 0; i < nnm.length; i++) {\n              var a = nnm.item(i);\n              var aname = a.name || a.nodeName;\n              if (aname === "xmlns" && prefix === "" || aname === "xmlns:" + prefix) {\n                return String(a.value || a.nodeValue);\n              }\n            }\n            n = n.parentNode;\n          }\n          return null;\n        };\n        var Functions = new Object();\n        Functions.last = function(c) {\n          if (arguments.length != 1) {\n            throw new Error("Function last expects ()");\n          }\n          return new XNumber(c.contextSize);\n        };\n        Functions.position = function(c) {\n          if (arguments.length != 1) {\n            throw new Error("Function position expects ()");\n          }\n          return new XNumber(c.contextPosition);\n        };\n        Functions.count = function() {\n          var c = arguments[0];\n          var ns;\n          if (arguments.length != 2 || !Utilities.instance_of(ns = arguments[1].evaluate(c), XNodeSet)) {\n            throw new Error("Function count expects (node-set)");\n          }\n          return new XNumber(ns.size);\n        };\n        Functions.id = function() {\n          var c = arguments[0];\n          var id;\n          if (arguments.length != 2) {\n            throw new Error("Function id expects (object)");\n          }\n          id = arguments[1].evaluate(c);\n          if (Utilities.instance_of(id, XNodeSet)) {\n            id = id.toArray().join(" ");\n          } else {\n            id = id.stringValue();\n          }\n          var ids = id.split(/[\\x0d\\x0a\\x09\\x20]+/);\n          var count = 0;\n          var ns = new XNodeSet();\n          var doc = c.contextNode.nodeType == NodeTypes.DOCUMENT_NODE ? c.contextNode : c.contextNode.ownerDocument;\n          for (var i = 0; i < ids.length; i++) {\n            var n;\n            if (doc.getElementById) {\n              n = doc.getElementById(ids[i]);\n            } else {\n              n = Utilities.getElementById(doc, ids[i]);\n            }\n            if (n != null) {\n              ns.add(n);\n              count++;\n            }\n          }\n          return ns;\n        };\n        Functions.localName = function(c, eNode) {\n          var n;\n          if (arguments.length == 1) {\n            n = c.contextNode;\n          } else if (arguments.length == 2) {\n            n = eNode.evaluate(c).first();\n          } else {\n            throw new Error("Function local-name expects (node-set?)");\n          }\n          if (n == null) {\n            return new XString("");\n          }\n          return new XString(\n            n.localName || //  standard elements and attributes\n            n.baseName || //  IE\n            n.target || //  processing instructions\n            n.nodeName || //  DOM1 elements\n            ""\n            //  fallback\n          );\n        };\n        Functions.namespaceURI = function() {\n          var c = arguments[0];\n          var n;\n          if (arguments.length == 1) {\n            n = c.contextNode;\n          } else if (arguments.length == 2) {\n            n = arguments[1].evaluate(c).first();\n          } else {\n            throw new Error("Function namespace-uri expects (node-set?)");\n          }\n          if (n == null) {\n            return new XString("");\n          }\n          return new XString(n.namespaceURI || "");\n        };\n        Functions.name = function() {\n          var c = arguments[0];\n          var n;\n          if (arguments.length == 1) {\n            n = c.contextNode;\n          } else if (arguments.length == 2) {\n            n = arguments[1].evaluate(c).first();\n          } else {\n            throw new Error("Function name expects (node-set?)");\n          }\n          if (n == null) {\n            return new XString("");\n          }\n          if (n.nodeType == NodeTypes.ELEMENT_NODE) {\n            return new XString(n.nodeName);\n          } else if (n.nodeType == NodeTypes.ATTRIBUTE_NODE) {\n            return new XString(n.name || n.nodeName);\n          } else if (n.nodeType === NodeTypes.PROCESSING_INSTRUCTION_NODE) {\n            return new XString(n.target || n.nodeName);\n          } else if (n.localName == null) {\n            return new XString("");\n          } else {\n            return new XString(n.localName);\n          }\n        };\n        Functions.string = function() {\n          var c = arguments[0];\n          if (arguments.length == 1) {\n            return new XString(XNodeSet.prototype.stringForNode(c.contextNode));\n          } else if (arguments.length == 2) {\n            return arguments[1].evaluate(c).string();\n          }\n          throw new Error("Function string expects (object?)");\n        };\n        Functions.concat = function(c) {\n          if (arguments.length < 3) {\n            throw new Error("Function concat expects (string, string[, string]*)");\n          }\n          var s = "";\n          for (var i = 1; i < arguments.length; i++) {\n            s += arguments[i].evaluate(c).stringValue();\n          }\n          return new XString(s);\n        };\n        Functions.startsWith = function() {\n          var c = arguments[0];\n          if (arguments.length != 3) {\n            throw new Error("Function startsWith expects (string, string)");\n          }\n          var s1 = arguments[1].evaluate(c).stringValue();\n          var s2 = arguments[2].evaluate(c).stringValue();\n          return new XBoolean(s1.substring(0, s2.length) == s2);\n        };\n        Functions.contains = function() {\n          var c = arguments[0];\n          if (arguments.length != 3) {\n            throw new Error("Function contains expects (string, string)");\n          }\n          var s1 = arguments[1].evaluate(c).stringValue();\n          var s2 = arguments[2].evaluate(c).stringValue();\n          return new XBoolean(s1.indexOf(s2) !== -1);\n        };\n        Functions.substringBefore = function() {\n          var c = arguments[0];\n          if (arguments.length != 3) {\n            throw new Error("Function substring-before expects (string, string)");\n          }\n          var s1 = arguments[1].evaluate(c).stringValue();\n          var s2 = arguments[2].evaluate(c).stringValue();\n          return new XString(s1.substring(0, s1.indexOf(s2)));\n        };\n        Functions.substringAfter = function() {\n          var c = arguments[0];\n          if (arguments.length != 3) {\n            throw new Error("Function substring-after expects (string, string)");\n          }\n          var s1 = arguments[1].evaluate(c).stringValue();\n          var s2 = arguments[2].evaluate(c).stringValue();\n          if (s2.length == 0) {\n            return new XString(s1);\n          }\n          var i = s1.indexOf(s2);\n          if (i == -1) {\n            return new XString("");\n          }\n          return new XString(s1.substring(i + s2.length));\n        };\n        Functions.substring = function() {\n          var c = arguments[0];\n          if (!(arguments.length == 3 || arguments.length == 4)) {\n            throw new Error("Function substring expects (string, number, number?)");\n          }\n          var s = arguments[1].evaluate(c).stringValue();\n          var n1 = Math.round(arguments[2].evaluate(c).numberValue()) - 1;\n          var n2 = arguments.length == 4 ? n1 + Math.round(arguments[3].evaluate(c).numberValue()) : void 0;\n          return new XString(s.substring(n1, n2));\n        };\n        Functions.stringLength = function() {\n          var c = arguments[0];\n          var s;\n          if (arguments.length == 1) {\n            s = XNodeSet.prototype.stringForNode(c.contextNode);\n          } else if (arguments.length == 2) {\n            s = arguments[1].evaluate(c).stringValue();\n          } else {\n            throw new Error("Function string-length expects (string?)");\n          }\n          return new XNumber(s.length);\n        };\n        Functions.normalizeSpace = function() {\n          var c = arguments[0];\n          var s;\n          if (arguments.length == 1) {\n            s = XNodeSet.prototype.stringForNode(c.contextNode);\n          } else if (arguments.length == 2) {\n            s = arguments[1].evaluate(c).stringValue();\n          } else {\n            throw new Error("Function normalize-space expects (string?)");\n          }\n          var i = 0;\n          var j = s.length - 1;\n          while (Utilities.isSpace(s.charCodeAt(j))) {\n            j--;\n          }\n          var t = "";\n          while (i <= j && Utilities.isSpace(s.charCodeAt(i))) {\n            i++;\n          }\n          while (i <= j) {\n            if (Utilities.isSpace(s.charCodeAt(i))) {\n              t += " ";\n              while (i <= j && Utilities.isSpace(s.charCodeAt(i))) {\n                i++;\n              }\n            } else {\n              t += s.charAt(i);\n              i++;\n            }\n          }\n          return new XString(t);\n        };\n        Functions.translate = function(c, eValue, eFrom, eTo) {\n          if (arguments.length != 4) {\n            throw new Error("Function translate expects (string, string, string)");\n          }\n          var value = eValue.evaluate(c).stringValue();\n          var from = eFrom.evaluate(c).stringValue();\n          var to = eTo.evaluate(c).stringValue();\n          var cMap = reduce(function(acc, ch, i) {\n            if (!(ch in acc)) {\n              acc[ch] = i > to.length ? "" : to[i];\n            }\n            return acc;\n          }, {}, from);\n          var t = join(\n            "",\n            map(function(ch) {\n              return ch in cMap ? cMap[ch] : ch;\n            }, value)\n          );\n          return new XString(t);\n        };\n        Functions.boolean_ = function() {\n          var c = arguments[0];\n          if (arguments.length != 2) {\n            throw new Error("Function boolean expects (object)");\n          }\n          return arguments[1].evaluate(c).bool();\n        };\n        Functions.not = function(c, eValue) {\n          if (arguments.length != 2) {\n            throw new Error("Function not expects (object)");\n          }\n          return eValue.evaluate(c).bool().not();\n        };\n        Functions.true_ = function() {\n          if (arguments.length != 1) {\n            throw new Error("Function true expects ()");\n          }\n          return XBoolean.true_;\n        };\n        Functions.false_ = function() {\n          if (arguments.length != 1) {\n            throw new Error("Function false expects ()");\n          }\n          return XBoolean.false_;\n        };\n        Functions.lang = function() {\n          var c = arguments[0];\n          if (arguments.length != 2) {\n            throw new Error("Function lang expects (string)");\n          }\n          var lang;\n          for (var n = c.contextNode; n != null && n.nodeType != NodeTypes.DOCUMENT_NODE; n = n.parentNode) {\n            var a = n.getAttributeNS(XPath.XML_NAMESPACE_URI, "lang");\n            if (a != null) {\n              lang = String(a);\n              break;\n            }\n          }\n          if (lang == null) {\n            return XBoolean.false_;\n          }\n          var s = arguments[1].evaluate(c).stringValue();\n          return new XBoolean(lang.substring(0, s.length) == s && (lang.length == s.length || lang.charAt(s.length) == "-"));\n        };\n        Functions.number = function() {\n          var c = arguments[0];\n          if (!(arguments.length == 1 || arguments.length == 2)) {\n            throw new Error("Function number expects (object?)");\n          }\n          if (arguments.length == 1) {\n            return new XNumber(XNodeSet.prototype.stringForNode(c.contextNode));\n          }\n          return arguments[1].evaluate(c).number();\n        };\n        Functions.sum = function() {\n          var c = arguments[0];\n          var ns;\n          if (arguments.length != 2 || !Utilities.instance_of(ns = arguments[1].evaluate(c), XNodeSet)) {\n            throw new Error("Function sum expects (node-set)");\n          }\n          ns = ns.toUnsortedArray();\n          var n = 0;\n          for (var i = 0; i < ns.length; i++) {\n            n += new XNumber(XNodeSet.prototype.stringForNode(ns[i])).numberValue();\n          }\n          return new XNumber(n);\n        };\n        Functions.floor = function() {\n          var c = arguments[0];\n          if (arguments.length != 2) {\n            throw new Error("Function floor expects (number)");\n          }\n          return new XNumber(Math.floor(arguments[1].evaluate(c).numberValue()));\n        };\n        Functions.ceiling = function() {\n          var c = arguments[0];\n          if (arguments.length != 2) {\n            throw new Error("Function ceiling expects (number)");\n          }\n          return new XNumber(Math.ceil(arguments[1].evaluate(c).numberValue()));\n        };\n        Functions.round = function() {\n          var c = arguments[0];\n          if (arguments.length != 2) {\n            throw new Error("Function round expects (number)");\n          }\n          return new XNumber(Math.round(arguments[1].evaluate(c).numberValue()));\n        };\n        var Utilities = new Object();\n        var isAttributeLike = function(val) {\n          return val && (val.nodeType === NodeTypes.ATTRIBUTE_NODE || val.ownerElement || val.isXPathNamespace);\n        };\n        Utilities.splitQName = function(qn) {\n          var i = qn.indexOf(":");\n          if (i == -1) {\n            return [null, qn];\n          }\n          return [qn.substring(0, i), qn.substring(i + 1)];\n        };\n        Utilities.resolveQName = function(qn, nr, n, useDefault) {\n          var parts = Utilities.splitQName(qn);\n          if (parts[0] != null) {\n            parts[0] = nr.getNamespace(parts[0], n);\n          } else {\n            if (useDefault) {\n              parts[0] = nr.getNamespace("", n);\n              if (parts[0] == null) {\n                parts[0] = "";\n              }\n            } else {\n              parts[0] = "";\n            }\n          }\n          return parts;\n        };\n        Utilities.isSpace = function(c) {\n          return c == 9 || c == 13 || c == 10 || c == 32;\n        };\n        Utilities.isLetter = function(c) {\n          return c >= 65 && c <= 90 || c >= 97 && c <= 122 || c >= 192 && c <= 214 || c >= 216 && c <= 246 || c >= 248 && c <= 255 || c >= 256 && c <= 305 || c >= 308 && c <= 318 || c >= 321 && c <= 328 || c >= 330 && c <= 382 || c >= 384 && c <= 451 || c >= 461 && c <= 496 || c >= 500 && c <= 501 || c >= 506 && c <= 535 || c >= 592 && c <= 680 || c >= 699 && c <= 705 || c == 902 || c >= 904 && c <= 906 || c == 908 || c >= 910 && c <= 929 || c >= 931 && c <= 974 || c >= 976 && c <= 982 || c == 986 || c == 988 || c == 990 || c == 992 || c >= 994 && c <= 1011 || c >= 1025 && c <= 1036 || c >= 1038 && c <= 1103 || c >= 1105 && c <= 1116 || c >= 1118 && c <= 1153 || c >= 1168 && c <= 1220 || c >= 1223 && c <= 1224 || c >= 1227 && c <= 1228 || c >= 1232 && c <= 1259 || c >= 1262 && c <= 1269 || c >= 1272 && c <= 1273 || c >= 1329 && c <= 1366 || c == 1369 || c >= 1377 && c <= 1414 || c >= 1488 && c <= 1514 || c >= 1520 && c <= 1522 || c >= 1569 && c <= 1594 || c >= 1601 && c <= 1610 || c >= 1649 && c <= 1719 || c >= 1722 && c <= 1726 || c >= 1728 && c <= 1742 || c >= 1744 && c <= 1747 || c == 1749 || c >= 1765 && c <= 1766 || c >= 2309 && c <= 2361 || c == 2365 || c >= 2392 && c <= 2401 || c >= 2437 && c <= 2444 || c >= 2447 && c <= 2448 || c >= 2451 && c <= 2472 || c >= 2474 && c <= 2480 || c == 2482 || c >= 2486 && c <= 2489 || c >= 2524 && c <= 2525 || c >= 2527 && c <= 2529 || c >= 2544 && c <= 2545 || c >= 2565 && c <= 2570 || c >= 2575 && c <= 2576 || c >= 2579 && c <= 2600 || c >= 2602 && c <= 2608 || c >= 2610 && c <= 2611 || c >= 2613 && c <= 2614 || c >= 2616 && c <= 2617 || c >= 2649 && c <= 2652 || c == 2654 || c >= 2674 && c <= 2676 || c >= 2693 && c <= 2699 || c == 2701 || c >= 2703 && c <= 2705 || c >= 2707 && c <= 2728 || c >= 2730 && c <= 2736 || c >= 2738 && c <= 2739 || c >= 2741 && c <= 2745 || c == 2749 || c == 2784 || c >= 2821 && c <= 2828 || c >= 2831 && c <= 2832 || c >= 2835 && c <= 2856 || c >= 2858 && c <= 2864 || c >= 2866 && c <= 2867 || c >= 2870 && c <= 2873 || c == 2877 || c >= 2908 && c <= 2909 || c >= 2911 && c <= 2913 || c >= 2949 && c <= 2954 || c >= 2958 && c <= 2960 || c >= 2962 && c <= 2965 || c >= 2969 && c <= 2970 || c == 2972 || c >= 2974 && c <= 2975 || c >= 2979 && c <= 2980 || c >= 2984 && c <= 2986 || c >= 2990 && c <= 2997 || c >= 2999 && c <= 3001 || c >= 3077 && c <= 3084 || c >= 3086 && c <= 3088 || c >= 3090 && c <= 3112 || c >= 3114 && c <= 3123 || c >= 3125 && c <= 3129 || c >= 3168 && c <= 3169 || c >= 3205 && c <= 3212 || c >= 3214 && c <= 3216 || c >= 3218 && c <= 3240 || c >= 3242 && c <= 3251 || c >= 3253 && c <= 3257 || c == 3294 || c >= 3296 && c <= 3297 || c >= 3333 && c <= 3340 || c >= 3342 && c <= 3344 || c >= 3346 && c <= 3368 || c >= 3370 && c <= 3385 || c >= 3424 && c <= 3425 || c >= 3585 && c <= 3630 || c == 3632 || c >= 3634 && c <= 3635 || c >= 3648 && c <= 3653 || c >= 3713 && c <= 3714 || c == 3716 || c >= 3719 && c <= 3720 || c == 3722 || c == 3725 || c >= 3732 && c <= 3735 || c >= 3737 && c <= 3743 || c >= 3745 && c <= 3747 || c == 3749 || c == 3751 || c >= 3754 && c <= 3755 || c >= 3757 && c <= 3758 || c == 3760 || c >= 3762 && c <= 3763 || c == 3773 || c >= 3776 && c <= 3780 || c >= 3904 && c <= 3911 || c >= 3913 && c <= 3945 || c >= 4256 && c <= 4293 || c >= 4304 && c <= 4342 || c == 4352 || c >= 4354 && c <= 4355 || c >= 4357 && c <= 4359 || c == 4361 || c >= 4363 && c <= 4364 || c >= 4366 && c <= 4370 || c == 4412 || c == 4414 || c == 4416 || c == 4428 || c == 4430 || c == 4432 || c >= 4436 && c <= 4437 || c == 4441 || c >= 4447 && c <= 4449 || c == 4451 || c == 4453 || c == 4455 || c == 4457 || c >= 4461 && c <= 4462 || c >= 4466 && c <= 4467 || c == 4469 || c == 4510 || c == 4520 || c == 4523 || c >= 4526 && c <= 4527 || c >= 4535 && c <= 4536 || c == 4538 || c >= 4540 && c <= 4546 || c == 4587 || c == 4592 || c == 4601 || c >= 7680 && c <= 7835 || c >= 7840 && c <= 7929 || c >= 7936 && c <= 7957 || c >= 7960 && c <= 7965 || c >= 7968 && c <= 8005 || c >= 8008 && c <= 8013 || c >= 8016 && c <= 8023 || c == 8025 || c == 8027 || c == 8029 || c >= 8031 && c <= 8061 || c >= 8064 && c <= 8116 || c >= 8118 && c <= 8124 || c == 8126 || c >= 8130 && c <= 8132 || c >= 8134 && c <= 8140 || c >= 8144 && c <= 8147 || c >= 8150 && c <= 8155 || c >= 8160 && c <= 8172 || c >= 8178 && c <= 8180 || c >= 8182 && c <= 8188 || c == 8486 || c >= 8490 && c <= 8491 || c == 8494 || c >= 8576 && c <= 8578 || c >= 12353 && c <= 12436 || c >= 12449 && c <= 12538 || c >= 12549 && c <= 12588 || c >= 44032 && c <= 55203 || c >= 19968 && c <= 40869 || c == 12295 || c >= 12321 && c <= 12329;\n        };\n        Utilities.isNCNameChar = function(c) {\n          return c >= 48 && c <= 57 || c >= 1632 && c <= 1641 || c >= 1776 && c <= 1785 || c >= 2406 && c <= 2415 || c >= 2534 && c <= 2543 || c >= 2662 && c <= 2671 || c >= 2790 && c <= 2799 || c >= 2918 && c <= 2927 || c >= 3047 && c <= 3055 || c >= 3174 && c <= 3183 || c >= 3302 && c <= 3311 || c >= 3430 && c <= 3439 || c >= 3664 && c <= 3673 || c >= 3792 && c <= 3801 || c >= 3872 && c <= 3881 || c == 46 || c == 45 || c == 95 || Utilities.isLetter(c) || c >= 768 && c <= 837 || c >= 864 && c <= 865 || c >= 1155 && c <= 1158 || c >= 1425 && c <= 1441 || c >= 1443 && c <= 1465 || c >= 1467 && c <= 1469 || c == 1471 || c >= 1473 && c <= 1474 || c == 1476 || c >= 1611 && c <= 1618 || c == 1648 || c >= 1750 && c <= 1756 || c >= 1757 && c <= 1759 || c >= 1760 && c <= 1764 || c >= 1767 && c <= 1768 || c >= 1770 && c <= 1773 || c >= 2305 && c <= 2307 || c == 2364 || c >= 2366 && c <= 2380 || c == 2381 || c >= 2385 && c <= 2388 || c >= 2402 && c <= 2403 || c >= 2433 && c <= 2435 || c == 2492 || c == 2494 || c == 2495 || c >= 2496 && c <= 2500 || c >= 2503 && c <= 2504 || c >= 2507 && c <= 2509 || c == 2519 || c >= 2530 && c <= 2531 || c == 2562 || c == 2620 || c == 2622 || c == 2623 || c >= 2624 && c <= 2626 || c >= 2631 && c <= 2632 || c >= 2635 && c <= 2637 || c >= 2672 && c <= 2673 || c >= 2689 && c <= 2691 || c == 2748 || c >= 2750 && c <= 2757 || c >= 2759 && c <= 2761 || c >= 2763 && c <= 2765 || c >= 2817 && c <= 2819 || c == 2876 || c >= 2878 && c <= 2883 || c >= 2887 && c <= 2888 || c >= 2891 && c <= 2893 || c >= 2902 && c <= 2903 || c >= 2946 && c <= 2947 || c >= 3006 && c <= 3010 || c >= 3014 && c <= 3016 || c >= 3018 && c <= 3021 || c == 3031 || c >= 3073 && c <= 3075 || c >= 3134 && c <= 3140 || c >= 3142 && c <= 3144 || c >= 3146 && c <= 3149 || c >= 3157 && c <= 3158 || c >= 3202 && c <= 3203 || c >= 3262 && c <= 3268 || c >= 3270 && c <= 3272 || c >= 3274 && c <= 3277 || c >= 3285 && c <= 3286 || c >= 3330 && c <= 3331 || c >= 3390 && c <= 3395 || c >= 3398 && c <= 3400 || c >= 3402 && c <= 3405 || c == 3415 || c == 3633 || c >= 3636 && c <= 3642 || c >= 3655 && c <= 3662 || c == 3761 || c >= 3764 && c <= 3769 || c >= 3771 && c <= 3772 || c >= 3784 && c <= 3789 || c >= 3864 && c <= 3865 || c == 3893 || c == 3895 || c == 3897 || c == 3902 || c == 3903 || c >= 3953 && c <= 3972 || c >= 3974 && c <= 3979 || c >= 3984 && c <= 3989 || c == 3991 || c >= 3993 && c <= 4013 || c >= 4017 && c <= 4023 || c == 4025 || c >= 8400 && c <= 8412 || c == 8417 || c >= 12330 && c <= 12335 || c == 12441 || c == 12442 || c == 183 || c == 720 || c == 721 || c == 903 || c == 1600 || c == 3654 || c == 3782 || c == 12293 || c >= 12337 && c <= 12341 || c >= 12445 && c <= 12446 || c >= 12540 && c <= 12542;\n        };\n        Utilities.coalesceText = function(n) {\n          for (var m = n.firstChild; m != null; m = m.nextSibling) {\n            if (m.nodeType == NodeTypes.TEXT_NODE || m.nodeType == NodeTypes.CDATA_SECTION_NODE) {\n              var s = m.nodeValue;\n              var first = m;\n              m = m.nextSibling;\n              while (m != null && (m.nodeType == NodeTypes.TEXT_NODE || m.nodeType == NodeTypes.CDATA_SECTION_NODE)) {\n                s += m.nodeValue;\n                var del = m;\n                m = m.nextSibling;\n                del.parentNode.removeChild(del);\n              }\n              if (first.nodeType == NodeTypes.CDATA_SECTION_NODE) {\n                var p = first.parentNode;\n                if (first.nextSibling == null) {\n                  p.removeChild(first);\n                  p.appendChild(p.ownerDocument.createTextNode(s));\n                } else {\n                  var next = first.nextSibling;\n                  p.removeChild(first);\n                  p.insertBefore(p.ownerDocument.createTextNode(s), next);\n                }\n              } else {\n                first.nodeValue = s;\n              }\n              if (m == null) {\n                break;\n              }\n            } else if (m.nodeType == NodeTypes.ELEMENT_NODE) {\n              Utilities.coalesceText(m);\n            }\n          }\n        };\n        Utilities.instance_of = function(o, c) {\n          while (o != null) {\n            if (o.constructor === c) {\n              return true;\n            }\n            if (o === Object) {\n              return false;\n            }\n            o = o.constructor.superclass;\n          }\n          return false;\n        };\n        Utilities.getElementById = function(n, id) {\n          if (n.nodeType == NodeTypes.ELEMENT_NODE) {\n            if (n.getAttribute("id") == id || n.getAttributeNS(null, "id") == id) {\n              return n;\n            }\n          }\n          for (var m = n.firstChild; m != null; m = m.nextSibling) {\n            var res = Utilities.getElementById(m, id);\n            if (res != null) {\n              return res;\n            }\n          }\n          return null;\n        };\n        var XPathException = (function() {\n          function getMessage(code, exception) {\n            var msg = exception ? ": " + exception.toString() : "";\n            switch (code) {\n              case XPathException2.INVALID_EXPRESSION_ERR:\n                return "Invalid expression" + msg;\n              case XPathException2.TYPE_ERR:\n                return "Type error" + msg;\n            }\n            return null;\n          }\n          function XPathException2(code, error, message) {\n            var err = Error.call(this, getMessage(code, error) || message);\n            err.code = code;\n            err.exception = error;\n            return err;\n          }\n          XPathException2.prototype = Object.create(Error.prototype);\n          XPathException2.prototype.constructor = XPathException2;\n          XPathException2.superclass = Error;\n          XPathException2.prototype.toString = function() {\n            return this.message;\n          };\n          XPathException2.fromMessage = function(message, error) {\n            return new XPathException2(null, error, message);\n          };\n          XPathException2.INVALID_EXPRESSION_ERR = 51;\n          XPathException2.TYPE_ERR = 52;\n          return XPathException2;\n        })();\n        XPathExpression.prototype = {};\n        XPathExpression.prototype.constructor = XPathExpression;\n        XPathExpression.superclass = Object.prototype;\n        function XPathExpression(e, r, p) {\n          this.xpath = p.parse(e);\n          this.context = new XPathContext();\n          this.context.namespaceResolver = new XPathNSResolverWrapper(r);\n        }\n        XPathExpression.getOwnerDocument = function(n) {\n          return n.nodeType === NodeTypes.DOCUMENT_NODE ? n : n.ownerDocument;\n        };\n        XPathExpression.detectHtmlDom = function(n) {\n          if (!n) {\n            return false;\n          }\n          var doc = XPathExpression.getOwnerDocument(n);\n          try {\n            return doc.implementation.hasFeature("HTML", "2.0");\n          } catch (e) {\n            return true;\n          }\n        };\n        XPathExpression.prototype.evaluate = function(n, t, res) {\n          this.context.expressionContextNode = n;\n          this.context.caseInsensitive = XPathExpression.detectHtmlDom(n);\n          var result = this.xpath.evaluate(this.context);\n          return new XPathResult2(result, t);\n        };\n        XPathNSResolverWrapper.prototype = {};\n        XPathNSResolverWrapper.prototype.constructor = XPathNSResolverWrapper;\n        XPathNSResolverWrapper.superclass = Object.prototype;\n        function XPathNSResolverWrapper(r) {\n          this.xpathNSResolver = r;\n        }\n        XPathNSResolverWrapper.prototype.getNamespace = function(prefix, n) {\n          if (this.xpathNSResolver == null) {\n            return null;\n          }\n          return this.xpathNSResolver.lookupNamespaceURI(prefix);\n        };\n        NodeXPathNSResolver.prototype = {};\n        NodeXPathNSResolver.prototype.constructor = NodeXPathNSResolver;\n        NodeXPathNSResolver.superclass = Object.prototype;\n        function NodeXPathNSResolver(n) {\n          this.node = n;\n          this.namespaceResolver = new NamespaceResolver();\n        }\n        NodeXPathNSResolver.prototype.lookupNamespaceURI = function(prefix) {\n          return this.namespaceResolver.getNamespace(prefix, this.node);\n        };\n        XPathResult2.prototype = {};\n        XPathResult2.prototype.constructor = XPathResult2;\n        XPathResult2.superclass = Object.prototype;\n        function XPathResult2(v, t) {\n          if (t == XPathResult2.ANY_TYPE) {\n            if (v.constructor === XString) {\n              t = XPathResult2.STRING_TYPE;\n            } else if (v.constructor === XNumber) {\n              t = XPathResult2.NUMBER_TYPE;\n            } else if (v.constructor === XBoolean) {\n              t = XPathResult2.BOOLEAN_TYPE;\n            } else if (v.constructor === XNodeSet) {\n              t = XPathResult2.UNORDERED_NODE_ITERATOR_TYPE;\n            }\n          }\n          this.resultType = t;\n          switch (t) {\n            case XPathResult2.NUMBER_TYPE:\n              this.numberValue = v.numberValue();\n              return;\n            case XPathResult2.STRING_TYPE:\n              this.stringValue = v.stringValue();\n              return;\n            case XPathResult2.BOOLEAN_TYPE:\n              this.booleanValue = v.booleanValue();\n              return;\n            case XPathResult2.ANY_UNORDERED_NODE_TYPE:\n            case XPathResult2.FIRST_ORDERED_NODE_TYPE:\n              if (v.constructor === XNodeSet) {\n                this.singleNodeValue = v.first();\n                return;\n              }\n              break;\n            case XPathResult2.UNORDERED_NODE_ITERATOR_TYPE:\n            case XPathResult2.ORDERED_NODE_ITERATOR_TYPE:\n              if (v.constructor === XNodeSet) {\n                this.invalidIteratorState = false;\n                this.nodes = v.toArray();\n                this.iteratorIndex = 0;\n                return;\n              }\n              break;\n            case XPathResult2.UNORDERED_NODE_SNAPSHOT_TYPE:\n            case XPathResult2.ORDERED_NODE_SNAPSHOT_TYPE:\n              if (v.constructor === XNodeSet) {\n                this.nodes = v.toArray();\n                this.snapshotLength = this.nodes.length;\n                return;\n              }\n              break;\n          }\n          throw new XPathException(XPathException.TYPE_ERR);\n        }\n        ;\n        XPathResult2.prototype.iterateNext = function() {\n          if (this.resultType != XPathResult2.UNORDERED_NODE_ITERATOR_TYPE && this.resultType != XPathResult2.ORDERED_NODE_ITERATOR_TYPE) {\n            throw new XPathException(XPathException.TYPE_ERR);\n          }\n          return this.nodes[this.iteratorIndex++];\n        };\n        XPathResult2.prototype.snapshotItem = function(i) {\n          if (this.resultType != XPathResult2.UNORDERED_NODE_SNAPSHOT_TYPE && this.resultType != XPathResult2.ORDERED_NODE_SNAPSHOT_TYPE) {\n            throw new XPathException(XPathException.TYPE_ERR);\n          }\n          return this.nodes[i];\n        };\n        XPathResult2.ANY_TYPE = 0;\n        XPathResult2.NUMBER_TYPE = 1;\n        XPathResult2.STRING_TYPE = 2;\n        XPathResult2.BOOLEAN_TYPE = 3;\n        XPathResult2.UNORDERED_NODE_ITERATOR_TYPE = 4;\n        XPathResult2.ORDERED_NODE_ITERATOR_TYPE = 5;\n        XPathResult2.UNORDERED_NODE_SNAPSHOT_TYPE = 6;\n        XPathResult2.ORDERED_NODE_SNAPSHOT_TYPE = 7;\n        XPathResult2.ANY_UNORDERED_NODE_TYPE = 8;\n        XPathResult2.FIRST_ORDERED_NODE_TYPE = 9;\n        function installDOM3XPathSupport(doc, p) {\n          doc.createExpression = function(e, r) {\n            try {\n              return new XPathExpression(e, r, p);\n            } catch (e2) {\n              throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, e2);\n            }\n          };\n          doc.createNSResolver = function(n) {\n            return new NodeXPathNSResolver(n);\n          };\n          doc.evaluate = function(e, cn, r, t, res) {\n            if (t < 0 || t > 9) {\n              throw { code: 0, toString: function() {\n                return "Request type not supported";\n              } };\n            }\n            return doc.createExpression(e, r, p).evaluate(cn, t, res);\n          };\n        }\n        ;\n        try {\n          var shouldInstall = true;\n          try {\n            if (document.implementation && document.implementation.hasFeature && document.implementation.hasFeature("XPath", null)) {\n              shouldInstall = false;\n            }\n          } catch (e) {\n          }\n          if (shouldInstall) {\n            installDOM3XPathSupport(document, new XPathParser());\n          }\n        } catch (e) {\n        }\n        installDOM3XPathSupport(exports3, new XPathParser());\n        (function() {\n          var parser = new XPathParser();\n          var defaultNSResolver = new NamespaceResolver();\n          var defaultFunctionResolver = new FunctionResolver();\n          var defaultVariableResolver = new VariableResolver();\n          function makeNSResolverFromFunction(func) {\n            return {\n              getNamespace: function(prefix, node) {\n                var ns = func(prefix, node);\n                return ns || defaultNSResolver.getNamespace(prefix, node);\n              }\n            };\n          }\n          function makeNSResolverFromObject(obj) {\n            return makeNSResolverFromFunction(obj.getNamespace.bind(obj));\n          }\n          function makeNSResolverFromMap(map2) {\n            return makeNSResolverFromFunction(function(prefix) {\n              return map2[prefix];\n            });\n          }\n          function makeNSResolver(resolver) {\n            if (resolver && typeof resolver.getNamespace === "function") {\n              return makeNSResolverFromObject(resolver);\n            }\n            if (typeof resolver === "function") {\n              return makeNSResolverFromFunction(resolver);\n            }\n            if (typeof resolver === "object") {\n              return makeNSResolverFromMap(resolver);\n            }\n            return defaultNSResolver;\n          }\n          function convertValue(value) {\n            if (value === null || typeof value === "undefined" || value instanceof XString || value instanceof XBoolean || value instanceof XNumber || value instanceof XNodeSet) {\n              return value;\n            }\n            switch (typeof value) {\n              case "string":\n                return new XString(value);\n              case "boolean":\n                return new XBoolean(value);\n              case "number":\n                return new XNumber(value);\n            }\n            var ns = new XNodeSet();\n            ns.addArray([].concat(value));\n            return ns;\n          }\n          function makeEvaluator(func) {\n            return function(context) {\n              var args = Array.prototype.slice.call(arguments, 1).map(function(arg) {\n                return arg.evaluate(context);\n              });\n              var result = func.apply(this, [].concat(context, args));\n              return convertValue(result);\n            };\n          }\n          function makeFunctionResolverFromFunction(func) {\n            return {\n              getFunction: function(name2, namespace) {\n                var found = func(name2, namespace);\n                if (found) {\n                  return makeEvaluator(found);\n                }\n                return defaultFunctionResolver.getFunction(name2, namespace);\n              }\n            };\n          }\n          function makeFunctionResolverFromObject(obj) {\n            return makeFunctionResolverFromFunction(obj.getFunction.bind(obj));\n          }\n          function makeFunctionResolverFromMap(map2) {\n            return makeFunctionResolverFromFunction(function(name2) {\n              return map2[name2];\n            });\n          }\n          function makeFunctionResolver(resolver) {\n            if (resolver && typeof resolver.getFunction === "function") {\n              return makeFunctionResolverFromObject(resolver);\n            }\n            if (typeof resolver === "function") {\n              return makeFunctionResolverFromFunction(resolver);\n            }\n            if (typeof resolver === "object") {\n              return makeFunctionResolverFromMap(resolver);\n            }\n            return defaultFunctionResolver;\n          }\n          function makeVariableResolverFromFunction(func) {\n            return {\n              getVariable: function(name2, namespace) {\n                var value = func(name2, namespace);\n                return convertValue(value);\n              }\n            };\n          }\n          function makeVariableResolver(resolver) {\n            if (resolver) {\n              if (typeof resolver.getVariable === "function") {\n                return makeVariableResolverFromFunction(resolver.getVariable.bind(resolver));\n              }\n              if (typeof resolver === "function") {\n                return makeVariableResolverFromFunction(resolver);\n              }\n              if (typeof resolver === "object") {\n                return makeVariableResolverFromFunction(function(name2) {\n                  return resolver[name2];\n                });\n              }\n            }\n            return defaultVariableResolver;\n          }\n          function copyIfPresent(prop, dest, source) {\n            if (prop in source) {\n              dest[prop] = source[prop];\n            }\n          }\n          function makeContext(options) {\n            var context = new XPathContext();\n            if (options) {\n              context.namespaceResolver = makeNSResolver(options.namespaces);\n              context.functionResolver = makeFunctionResolver(options.functions);\n              context.variableResolver = makeVariableResolver(options.variables);\n              context.expressionContextNode = options.node;\n              copyIfPresent("allowAnyNamespaceForNoPrefix", context, options);\n              copyIfPresent("isHtml", context, options);\n            } else {\n              context.namespaceResolver = defaultNSResolver;\n            }\n            return context;\n          }\n          function evaluate(parsedExpression, options) {\n            var context = makeContext(options);\n            return parsedExpression.evaluate(context);\n          }\n          var evaluatorPrototype = {\n            evaluate: function(options) {\n              return evaluate(this.expression, options);\n            },\n            evaluateNumber: function(options) {\n              return this.evaluate(options).numberValue();\n            },\n            evaluateString: function(options) {\n              return this.evaluate(options).stringValue();\n            },\n            evaluateBoolean: function(options) {\n              return this.evaluate(options).booleanValue();\n            },\n            evaluateNodeSet: function(options) {\n              return this.evaluate(options).nodeset();\n            },\n            select: function(options) {\n              return this.evaluateNodeSet(options).toArray();\n            },\n            select1: function(options) {\n              return this.select(options)[0];\n            }\n          };\n          function parse(xpath2) {\n            var parsed = parser.parse(xpath2);\n            return Object.create(evaluatorPrototype, {\n              expression: {\n                value: parsed\n              }\n            });\n          }\n          exports3.parse = parse;\n        })();\n        assign(\n          exports3,\n          {\n            XPath,\n            XPathParser,\n            XPathResult: XPathResult2,\n            Step,\n            PathExpr,\n            NodeTest,\n            LocationPath,\n            OrOperation,\n            AndOperation,\n            BarOperation,\n            EqualsOperation,\n            NotEqualOperation,\n            LessThanOperation,\n            GreaterThanOperation,\n            LessThanOrEqualOperation,\n            GreaterThanOrEqualOperation,\n            PlusOperation,\n            MinusOperation,\n            MultiplyOperation,\n            DivOperation,\n            ModOperation,\n            UnaryMinusOperation,\n            FunctionCall,\n            VariableReference,\n            XPathContext,\n            XNodeSet,\n            XBoolean,\n            XString,\n            XNumber,\n            NamespaceResolver,\n            FunctionResolver,\n            VariableResolver,\n            Utilities\n          }\n        );\n        exports3.select = function(e, doc, single) {\n          return exports3.selectWithResolver(e, doc, null, single);\n        };\n        exports3.useNamespaces = function(mappings) {\n          var resolver = {\n            mappings: mappings || {},\n            lookupNamespaceURI: function(prefix) {\n              return this.mappings[prefix];\n            }\n          };\n          return function(e, doc, single) {\n            return exports3.selectWithResolver(e, doc, resolver, single);\n          };\n        };\n        exports3.selectWithResolver = function(e, doc, resolver, single) {\n          var expression = new XPathExpression(e, resolver, new XPathParser());\n          var type = XPathResult2.ANY_TYPE;\n          var result = expression.evaluate(doc, type, null);\n          if (result.resultType == XPathResult2.STRING_TYPE) {\n            result = result.stringValue;\n          } else if (result.resultType == XPathResult2.NUMBER_TYPE) {\n            result = result.numberValue;\n          } else if (result.resultType == XPathResult2.BOOLEAN_TYPE) {\n            result = result.booleanValue;\n          } else {\n            result = result.nodes;\n            if (single) {\n              result = result[0];\n            }\n          }\n          return result;\n        };\n        exports3.select1 = function(e, doc) {\n          return exports3.select(e, doc, true);\n        };\n        var isArrayOfNodes = function(value) {\n          return Array.isArray(value) && value.every(isNodeLike);\n        };\n        var isNodeOfType = function(type) {\n          return function(value) {\n            return isNodeLike(value) && value.nodeType === type;\n          };\n        };\n        assign(\n          exports3,\n          {\n            isNodeLike,\n            isArrayOfNodes,\n            isElement: isNodeOfType(NodeTypes.ELEMENT_NODE),\n            isAttribute: isNodeOfType(NodeTypes.ATTRIBUTE_NODE),\n            isTextNode: isNodeOfType(NodeTypes.TEXT_NODE),\n            isCDATASection: isNodeOfType(NodeTypes.CDATA_SECTION_NODE),\n            isProcessingInstruction: isNodeOfType(NodeTypes.PROCESSING_INSTRUCTION_NODE),\n            isComment: isNodeOfType(NodeTypes.COMMENT_NODE),\n            isDocumentNode: isNodeOfType(NodeTypes.DOCUMENT_NODE),\n            isDocumentTypeNode: isNodeOfType(NodeTypes.DOCUMENT_TYPE_NODE),\n            isDocumentFragment: isNodeOfType(NodeTypes.DOCUMENT_FRAGMENT_NODE)\n          }\n        );\n      })(xpath);\n    }\n  });\n\n  // modules/std/data/xml.js\n  var require_xml = __commonJS({\n    "modules/std/data/xml.js"(exports2, module2) {\n      "use strict";\n      var nextId = 1;\n      var nodeIds = /* @__PURE__ */ new WeakMap();\n      var wrappers = /* @__PURE__ */ new WeakMap();\n      function withSafeObjectPrototype(fn2) {\n        const hidden = [];\n        for (const name2 of ["get", "set"]) {\n          const desc = Object.prototype.hasOwnProperty.call(Object.prototype, name2) ? Object.getOwnPropertyDescriptor(Object.prototype, name2) : null;\n          if (desc && desc.configurable) {\n            hidden.push([name2, desc]);\n            delete Object.prototype[name2];\n          }\n        }\n        try {\n          return fn2();\n        } finally {\n          for (const [name2, desc] of hidden) {\n            Object.defineProperty(Object.prototype, name2, desc);\n          }\n        }\n      }\n      function domClasses() {\n        if (typeof DOMParser !== "undefined" && typeof XMLSerializer !== "undefined") {\n          return { DOMParser, XMLSerializer };\n        }\n        return withSafeObjectPrototype(() => require_lib());\n      }\n      function xpathEngine() {\n        if (typeof document !== "undefined" && document.evaluate) {\n          return null;\n        }\n        return withSafeObjectPrototype(() => require_xpath());\n      }\n      function isPath(value) {\n        return value && value.constructor && value.constructor.name === "Path" && typeof value.slurp_utf8 === "function" && typeof value.spew_utf8 === "function";\n      }\n      function nodeKey(node) {\n        if (!nodeIds.has(node)) {\n          nodeIds.set(node, nextId++);\n        }\n        return String(nodeIds.get(node));\n      }\n      function wrap(node) {\n        if (!node) {\n          return null;\n        }\n        if (wrappers.has(node)) {\n          return wrappers.get(node);\n        }\n        let wrapped;\n        if (node.nodeType === 9) {\n          wrapped = new XMLDocument(node);\n        } else if (node.nodeType === 1) {\n          wrapped = new XMLElement(node);\n        } else if (node.nodeType === 2) {\n          wrapped = new DOMAttr(node);\n        } else if (node.nodeType === 3 || node.nodeType === 4) {\n          wrapped = new DOMText(node);\n        } else if (node.nodeType === 8) {\n          wrapped = new DOMComment(node);\n        } else {\n          wrapped = new XMLNode(node);\n        }\n        wrappers.set(node, wrapped);\n        return wrapped;\n      }\n      function unwrap(value) {\n        return value instanceof XMLNode ? value._node : null;\n      }\n      function nodeArray(list) {\n        return Array.from(list || []).map(wrap).filter(Boolean);\n      }\n      function elementChildren(node) {\n        return Array.from(node.childNodes || []).filter((child) => child.nodeType === 1);\n      }\n      function descendants(node, includeSelf = false) {\n        const out = [];\n        const visit = (current) => {\n          out.push(current);\n          for (const child of Array.from(current.childNodes || [])) {\n            visit(child);\n          }\n        };\n        if (includeSelf) {\n          visit(node);\n        } else {\n          for (const child of Array.from(node.childNodes || [])) {\n            visit(child);\n          }\n        }\n        return out;\n      }\n      function simpleSelectorAll(node, selector) {\n        const text = String(selector || "").trim();\n        if (text === "") {\n          return [];\n        }\n        if (typeof node.querySelectorAll === "function") {\n          try {\n            return nodeArray(node.querySelectorAll(text));\n          } catch (_err) {\n          }\n        }\n        if (text.startsWith(".")) {\n          const klass = text.slice(1);\n          return descendants(node, false).filter((child) => child.nodeType === 1).filter((child) => {\n            const className = child.getAttribute("class");\n            return className && className.split(/\\s+/u).includes(klass);\n          }).map(wrap);\n        }\n        if (typeof node.getElementsByTagName === "function") {\n          return nodeArray(node.getElementsByTagName(text));\n        }\n        return descendants(node, false).filter((child) => child.nodeType === 1 && child.nodeName === text).map(wrap);\n      }\n      function evaluateBrowserXPath(node, expr, type) {\n        if (typeof XPathResult === "undefined") {\n          return null;\n        }\n        const doc = node.nodeType === 9 ? node : node.ownerDocument;\n        if (!doc || typeof doc.evaluate !== "function") {\n          return null;\n        }\n        return doc.evaluate(expr, node, null, type, null);\n      }\n      function findNodes(node, expr) {\n        const text = String(expr || "").trim();\n        if (text === "") {\n          return [];\n        }\n        const snapshotType = typeof XPathResult !== "undefined" ? XPathResult.ORDERED_NODE_SNAPSHOT_TYPE : 0;\n        const browserResult = evaluateBrowserXPath(node, text, snapshotType);\n        if (browserResult) {\n          const out = [];\n          for (let i = 0; i < browserResult.snapshotLength; i++) {\n            out.push(wrap(browserResult.snapshotItem(i)));\n          }\n          return out;\n        }\n        const xpath = xpathEngine();\n        const result = xpath.select(text, node);\n        return Array.isArray(result) ? nodeArray(result) : [];\n      }\n      function findValue(node, expr) {\n        const text = String(expr || "").trim();\n        if (text === "") {\n          return "";\n        }\n        const anyType = typeof XPathResult !== "undefined" ? XPathResult.ANY_TYPE : 0;\n        const browserResult = evaluateBrowserXPath(node, text, anyType);\n        if (browserResult) {\n          switch (browserResult.resultType) {\n            case XPathResult.NUMBER_TYPE:\n              return String(browserResult.numberValue);\n            case XPathResult.STRING_TYPE:\n              return browserResult.stringValue;\n            case XPathResult.BOOLEAN_TYPE:\n              return browserResult.booleanValue ? "true" : "false";\n            default: {\n              const found = browserResult.iterateNext();\n              return found ? nodeStringValue(found) : "";\n            }\n          }\n        }\n        const xpath = xpathEngine();\n        const result = xpath.select1(text, node);\n        if (result == null) {\n          return "";\n        }\n        if (typeof result === "number" || typeof result === "boolean") {\n          return String(result);\n        }\n        if (typeof result === "string") {\n          return result;\n        }\n        return nodeStringValue(result);\n      }\n      function nodeStringValue(node) {\n        if (node.nodeType === 2) {\n          return node.value || node.nodeValue || "";\n        }\n        return node.textContent || node.nodeValue || "";\n      }\n      function serialize(node) {\n        const { XMLSerializer: XMLSerializer2 } = domClasses();\n        return new XMLSerializer2().serializeToString(node);\n      }\n      function parseXml(text) {\n        const { DOMParser: DOMParser2 } = domClasses();\n        const parser = new DOMParser2();\n        const doc = parser.parseFromString(String(text ?? ""), "application/xml");\n        const parserError = doc.getElementsByTagName ? doc.getElementsByTagName("parsererror")[0] : null;\n        if (parserError) {\n          throw new Error(\n            `Exception: XML.parse failed: ${nodeStringValue(parserError)}`\n          );\n        }\n        return wrap(doc);\n      }\n      var XMLNode = class {\n        constructor(node) {\n          this._node = node;\n        }\n        nodeType() {\n          return String(this._node.nodeType);\n        }\n        nodeName() {\n          return this._node.nodeName || "";\n        }\n        nodeValue() {\n          return this._node.nodeValue;\n        }\n        setNodeValue(value) {\n          this._node.nodeValue = String(value ?? "");\n          return this;\n        }\n        data() {\n          return this._node.data ?? this.nodeValue();\n        }\n        setData(value) {\n          this._node.data = String(value ?? "");\n          return this;\n        }\n        nodeKind() {\n          switch (this._node.nodeType) {\n            case 1:\n              return "element";\n            case 2:\n              return "attr";\n            case 3:\n            case 4:\n              return "text";\n            case 8:\n              return "comment";\n            case 9:\n              return "document";\n            default:\n              return "node";\n          }\n        }\n        localName() {\n          return this._node.localName || null;\n        }\n        namespaceURI() {\n          return this._node.namespaceURI || null;\n        }\n        parentNode() {\n          return wrap(this._node.parentNode || this._node.ownerElement || null);\n        }\n        ownerDocument() {\n          return wrap(this._node.nodeType === 9 ? this._node : this._node.ownerDocument);\n        }\n        childNodes() {\n          return nodeArray(this._node.childNodes);\n        }\n        children() {\n          return elementChildren(this._node).map(wrap);\n        }\n        hasChildNodes() {\n          return this._node.hasChildNodes && this._node.hasChildNodes() ? 1 : 0;\n        }\n        firstChild() {\n          return wrap(this._node.firstChild);\n        }\n        lastChild() {\n          return wrap(this._node.lastChild);\n        }\n        nextSibling() {\n          return wrap(this._node.nextSibling);\n        }\n        previousSibling() {\n          return wrap(this._node.previousSibling);\n        }\n        textContent() {\n          return this._node.textContent || "";\n        }\n        setTextContent(value) {\n          this._node.textContent = String(value ?? "");\n          return this;\n        }\n        appendChild(node) {\n          return wrap(this._node.appendChild(unwrap(node)));\n        }\n        prependChild(node) {\n          const raw = unwrap(node);\n          if (this._node.firstChild) {\n            this._node.insertBefore(raw, this._node.firstChild);\n          } else {\n            this._node.appendChild(raw);\n          }\n          return node;\n        }\n        insertBefore(newNode, refNode) {\n          this._node.insertBefore(unwrap(newNode), unwrap(refNode));\n          return newNode;\n        }\n        replaceChild(newNode, oldNode) {\n          return wrap(this._node.replaceChild(unwrap(newNode), unwrap(oldNode)));\n        }\n        removeChild(childNode) {\n          return wrap(this._node.removeChild(unwrap(childNode)));\n        }\n        remove() {\n          if (this._node.parentNode) {\n            this._node.parentNode.removeChild(this._node);\n          }\n          return this;\n        }\n        cloneNode(deep = false) {\n          return wrap(this._node.cloneNode(Boolean(deep)));\n        }\n        normalize() {\n          this._node.normalize();\n          return this;\n        }\n        isSameNode(other) {\n          return unwrap(other) === this._node ? 1 : 0;\n        }\n        isEqualNode(other) {\n          const raw = unwrap(other);\n          if (this._node.isEqualNode) {\n            return this._node.isEqualNode(raw) ? 1 : 0;\n          }\n          return raw && serialize(this._node) === serialize(raw) ? 1 : 0;\n        }\n        contains(other) {\n          let cur = unwrap(other);\n          while (cur) {\n            if (cur === this._node) {\n              return 1;\n            }\n            cur = cur.parentNode || cur.ownerElement || null;\n          }\n          return 0;\n        }\n        visitEach(fn2) {\n          for (const node of descendants(this._node, true)) {\n            fn2(wrap(node));\n          }\n          return this;\n        }\n        findFirst(fn2) {\n          for (const node of descendants(this._node, false)) {\n            const wrapped = wrap(node);\n            if (fn2(wrapped)) {\n              return wrapped;\n            }\n          }\n          return null;\n        }\n        findnodes(xpath) {\n          return findNodes(this._node, xpath);\n        }\n        findvalue(xpath) {\n          return findValue(this._node, xpath);\n        }\n        querySelectorAll(selector) {\n          return simpleSelectorAll(this._node, selector);\n        }\n        querySelector(selector) {\n          return this.querySelectorAll(selector)[0] || null;\n        }\n        getElementsByTagName(name2) {\n          return this._node.getElementsByTagName ? nodeArray(this._node.getElementsByTagName(String(name2 || ""))) : [];\n        }\n        toXML(_pretty = false) {\n          return serialize(this._node);\n        }\n        to_String() {\n          return this.toXML(false);\n        }\n        uniqueKey() {\n          return nodeKey(this._node);\n        }\n        unique_id() {\n          return this.uniqueKey();\n        }\n      };\n      var XMLElement = class extends XMLNode {\n        tagName() {\n          return this.nodeName();\n        }\n        id() {\n          return this.getAttribute("id");\n        }\n        setId(value) {\n          return this.setAttribute("id", value);\n        }\n        getAttribute(name2) {\n          const value = this._node.getAttribute(String(name2 || ""));\n          return value == null ? null : value;\n        }\n        setAttribute(name2, value) {\n          this._node.setAttribute(String(name2 || ""), String(value ?? ""));\n          return this;\n        }\n        hasAttribute(name2) {\n          return this._node.hasAttribute(String(name2 || "")) ? 1 : 0;\n        }\n        removeAttribute(name2) {\n          this._node.removeAttribute(String(name2 || ""));\n          return this;\n        }\n        attributeNames() {\n          return Array.from(this._node.attributes || []).map((attr) => attr.name);\n        }\n        attributes() {\n          return nodeArray(this._node.attributes);\n        }\n      };\n      var DOMAttr = class extends XMLNode {\n      };\n      var DOMText = class extends XMLNode {\n      };\n      var DOMComment = class extends XMLNode {\n      };\n      var XMLDocument = class extends XMLNode {\n        documentElement() {\n          return wrap(this._node.documentElement);\n        }\n        createElement(name2) {\n          return wrap(this._node.createElement(String(name2 || "")));\n        }\n        createTextNode(text) {\n          return wrap(this._node.createTextNode(String(text ?? "")));\n        }\n        createComment(text) {\n          return wrap(this._node.createComment(String(text ?? "")));\n        }\n        createCDATASection(text) {\n          return wrap(this._node.createCDATASection(String(text ?? "")));\n        }\n        getElementById(id) {\n          if (typeof this._node.getElementById === "function") {\n            return wrap(this._node.getElementById(String(id || "")));\n          }\n          return this.findFirst(\n            (node) => node instanceof XMLElement && node.getAttribute("id") === String(id || "")\n          );\n        }\n      };\n      var XML = {\n        parse(text) {\n          return parseXml(text);\n        },\n        load(pathValue) {\n          if (!isPath(pathValue)) {\n            throw new Error("TypeException: XML.load expects Path as first argument");\n          }\n          return parseXml(pathValue.slurp_utf8());\n        },\n        dump(pathValue, value, pretty = false) {\n          if (!isPath(pathValue)) {\n            throw new Error("TypeException: XML.dump expects Path as first argument");\n          }\n          const xml = value && typeof value.toXML === "function" ? value.toXML(pretty) : String(value ?? "");\n          pathValue.spew_utf8(xml);\n          return pathValue;\n        }\n      };\n      module2.exports = {\n        XML,\n        XMLDocument,\n        XMLNode,\n        DOMNode: XMLNode,\n        DOMElement: XMLElement,\n        DOMAttr,\n        DOMText,\n        DOMComment,\n        DOMDocument: XMLDocument\n      };\n    }\n  });\n\n  // modules/std/digest/md5.js\n  var require_md5 = __commonJS({\n    "modules/std/digest/md5.js"(exports2, module2) {\n      "use strict";\n      var {\n        bytesToBase64,\n        bytesToHex,\n        digestBytes: digestBytes2,\n        toBinary\n      } = require_hash();\n      function md5(value) {\n        return toBinary(digestBytes2("md5", value, "md5"));\n      }\n      function md5_hex(value) {\n        return bytesToHex(digestBytes2("md5", value, "md5_hex"));\n      }\n      function md5_b64(value) {\n        return bytesToBase64(digestBytes2("md5", value, "md5_b64"));\n      }\n      module2.exports = {\n        md5,\n        md5_hex,\n        md5_b64\n      };\n    }\n  });\n\n  // modules/std/digest/sha.js\n  var require_sha = __commonJS({\n    "modules/std/digest/sha.js"(exports2, module2) {\n      "use strict";\n      var {\n        bytesToBase64,\n        bytesToHex,\n        digestBytes: digestBytes2,\n        hmacBytes: hmacBytes2,\n        toBinary\n      } = require_hash();\n      function digestFn(algorithm, fnName) {\n        return (value) => {\n          return toBinary(digestBytes2(algorithm, value, fnName));\n        };\n      }\n      function digestHexFn(algorithm, fnName) {\n        return (value) => {\n          return bytesToHex(digestBytes2(algorithm, value, fnName));\n        };\n      }\n      function digestB64Fn(algorithm, fnName) {\n        return (value) => {\n          return bytesToBase64(digestBytes2(algorithm, value, fnName));\n        };\n      }\n      function hmacFn(algorithm, fnName) {\n        return (value, key) => {\n          return toBinary(hmacBytes2(algorithm, value, key, fnName));\n        };\n      }\n      function hmacHexFn(algorithm, fnName) {\n        return (value, key) => {\n          return bytesToHex(hmacBytes2(algorithm, value, key, fnName));\n        };\n      }\n      function hmacB64Fn(algorithm, fnName) {\n        return (value, key) => {\n          return bytesToBase64(hmacBytes2(algorithm, value, key, fnName));\n        };\n      }\n      module2.exports = {\n        sha1: digestFn("sha1", "sha1"),\n        sha224: digestFn("sha224", "sha224"),\n        sha256: digestFn("sha256", "sha256"),\n        sha384: digestFn("sha384", "sha384"),\n        sha512: digestFn("sha512", "sha512"),\n        sha1_hex: digestHexFn("sha1", "sha1_hex"),\n        sha224_hex: digestHexFn("sha224", "sha224_hex"),\n        sha256_hex: digestHexFn("sha256", "sha256_hex"),\n        sha384_hex: digestHexFn("sha384", "sha384_hex"),\n        sha512_hex: digestHexFn("sha512", "sha512_hex"),\n        sha1_b64: digestB64Fn("sha1", "sha1_b64"),\n        sha256_b64: digestB64Fn("sha256", "sha256_b64"),\n        sha512_b64: digestB64Fn("sha512", "sha512_b64"),\n        hmac_sha1: hmacFn("sha1", "hmac_sha1"),\n        hmac_sha224: hmacFn("sha224", "hmac_sha224"),\n        hmac_sha256: hmacFn("sha256", "hmac_sha256"),\n        hmac_sha384: hmacFn("sha384", "hmac_sha384"),\n        hmac_sha512: hmacFn("sha512", "hmac_sha512"),\n        hmac_sha1_hex: hmacHexFn("sha1", "hmac_sha1_hex"),\n        hmac_sha224_hex: hmacHexFn("sha224", "hmac_sha224_hex"),\n        hmac_sha256_hex: hmacHexFn("sha256", "hmac_sha256_hex"),\n        hmac_sha384_hex: hmacHexFn("sha384", "hmac_sha384_hex"),\n        hmac_sha512_hex: hmacHexFn("sha512", "hmac_sha512_hex"),\n        hmac_sha256_b64: hmacB64Fn("sha256", "hmac_sha256_b64")\n      };\n    }\n  });\n\n  // modules/std/net/http.js\n  var require_http = __commonJS({\n    "modules/std/net/http.js"(exports2, module2) {\n      "use strict";\n      var nodeSpawnSync;\n      var nodeSpawnLoaded = false;\n      var nodeFs;\n      var nodeHttps;\n      var nodeOs;\n      var nodePath;\n      var hostName2 = null;\n      var { Task, traceBlockingOperation } = require_task();\n      function _nodeSpawnSync() {\n        if (nodeSpawnLoaded) {\n          return nodeSpawnSync;\n        }\n        nodeSpawnLoaded = true;\n        if (typeof __require !== "function") {\n          nodeSpawnSync = null;\n          return nodeSpawnSync;\n        }\n        try {\n          nodeSpawnSync = __require("node:child_process").spawnSync;\n        } catch (_err) {\n          nodeSpawnSync = null;\n        }\n        return nodeSpawnSync;\n      }\n      function _nodeModule(name2) {\n        if (typeof __require !== "function") {\n          return null;\n        }\n        try {\n          return __require(name2);\n        } catch (_err) {\n          return null;\n        }\n      }\n      function _nodeFs() {\n        nodeFs = nodeFs || _nodeModule("node:fs");\n        return nodeFs;\n      }\n      function _nodeHttps() {\n        nodeHttps = nodeHttps || _nodeModule("node:https");\n        return nodeHttps;\n      }\n      function _nodeOs() {\n        nodeOs = nodeOs || _nodeModule("node:os");\n        return nodeOs;\n      }\n      function _nodePath() {\n        nodePath = nodePath || _nodeModule("node:path");\n        return nodePath;\n      }\n      function _toDict(value) {\n        if (value == null) {\n          return {};\n        }\n        if (value && Array.isArray(value.list)) {\n          const out = {};\n          for (const pair of value.list) {\n            if (Array.isArray(pair) && pair.length >= 2) {\n              out[String(pair[0])] = pair[1];\n            }\n          }\n          return out;\n        }\n        if (typeof value !== "object" || Array.isArray(value)) {\n          return {};\n        }\n        return { ...value };\n      }\n      function _decorateDict(value) {\n        if (value == null || typeof value !== "object" || Array.isArray(value)) {\n          return value;\n        }\n        if (!Object.prototype.hasOwnProperty.call(value, "get")) {\n          Object.defineProperty(value, "get", {\n            value(key, fallback = null) {\n              return Object.prototype.hasOwnProperty.call(this, String(key)) ? this[String(key)] : fallback;\n            },\n            enumerable: false,\n            configurable: true,\n            writable: true\n          });\n        }\n        return value;\n      }\n      function _syncUnsupportedResponse(spec) {\n        return new Response({\n          status: 599,\n          reason: "Synchronous HTTP is unsupported on JS/Browser",\n          url: _urlWithQuery(spec.url, spec.query),\n          content: "",\n          headers: {},\n          success: false\n        });\n      }\n      function _urlWithQuery(url, query) {\n        const queryMap = _toDict(query);\n        const keys = Object.keys(queryMap);\n        if (keys.length === 0) {\n          return String(url);\n        }\n        const usp = new URLSearchParams();\n        for (const key of keys.sort()) {\n          usp.set(key, queryMap[key] == null ? "" : String(queryMap[key]));\n        }\n        const base = String(url);\n        return `${base}${base.includes("?") ? "&" : "?"}${usp.toString()}`;\n      }\n      function _maxRedirect(spec, uaConfig) {\n        const value = spec.max_redirect ?? uaConfig.max_redirect ?? 10;\n        const number = Number(value);\n        return Number.isFinite(number) && number >= 0 ? Math.floor(number) : 10;\n      }\n      function _writeDownload(spec, content) {\n        if (spec.download_to === void 0) {\n          return;\n        }\n        const fs = _nodeFs();\n        if (!fs) {\n          throw new Error("Exception: download_to filesystem support is unavailable");\n        }\n        fs.writeFileSync(String(spec.download_to), content, "utf8");\n      }\n      var CookieJar = class {\n        constructor() {\n          this._cookies = /* @__PURE__ */ new Map();\n        }\n        add(url, setCookie) {\n          this._cookies.set(String(url ?? ""), String(setCookie ?? ""));\n          return this;\n        }\n        cookie_header(url) {\n          return this._cookies.get(String(url ?? "")) ?? null;\n        }\n        clear() {\n          this._cookies.clear();\n          return this;\n        }\n      };\n      var Response = class {\n        constructor(payload) {\n          this._payload = payload;\n        }\n        status() {\n          return this._payload.status;\n        }\n        reason() {\n          return this._payload.reason;\n        }\n        url() {\n          return this._payload.url;\n        }\n        content() {\n          return this._payload.content;\n        }\n        headers() {\n          return { ...this._payload.headers };\n        }\n        header(name2) {\n          return this._payload.headers[String(name2).toLowerCase()] ?? null;\n        }\n        success() {\n          return this._payload.success ? 1 : 0;\n        }\n        json() {\n          return JSON.parse(this._payload.content || "");\n        }\n        expect_success() {\n          if (this.success()) {\n            return this;\n          }\n          throw new Error(`HTTP request failed with status ${this.status()}`);\n        }\n        to_Dict() {\n          return _decorateDict({\n            status: this.status(),\n            reason: this.reason(),\n            url: this.url(),\n            content: this.content(),\n            headers: _decorateDict(this.headers()),\n            success: this.success()\n          });\n        }\n      };\n      var Request = class {\n        constructor(method, url) {\n          this._spec = {\n            method: String(method || "GET").toUpperCase(),\n            url: String(url || ""),\n            headers: {}\n          };\n        }\n        method(value) {\n          this._spec.method = String(value).toUpperCase();\n          return this;\n        }\n        url(value) {\n          this._spec.url = String(value);\n          return this;\n        }\n        header(name2, value) {\n          this._spec.headers[String(name2).toLowerCase()] = String(value);\n          return this;\n        }\n        headers(value) {\n          for (const [key, item] of Object.entries(_toDict(value))) {\n            this.header(key, item);\n          }\n          return this;\n        }\n        query(value) {\n          this._spec.query = _toDict(value);\n          return this;\n        }\n        body(value) {\n          this._spec.body = value == null ? "" : String(value);\n          return this;\n        }\n        json(value) {\n          this._spec.json = value;\n          this._spec.headers["content-type"] = this._spec.headers["content-type"] || "application/json";\n          return this;\n        }\n        auth_bearer(token) {\n          return this.header("authorization", `Bearer ${token}`);\n        }\n        timeout(value) {\n          this._spec.timeout = Number(value);\n          return this;\n        }\n        retries(value) {\n          this._spec.retries = Number(value);\n          return this;\n        }\n        max_redirect(value) {\n          this._spec.max_redirect = Number(value);\n          return this;\n        }\n        download_to(value) {\n          this._spec.download_to = String(value);\n          return this;\n        }\n        upload_from(value) {\n          this._spec.upload_from = String(value);\n          return this;\n        }\n        tls_identity(value) {\n          this._spec.tls_identity = value ?? null;\n          return this;\n        }\n        multipart(value) {\n          this._spec.multipart = _toDict(value);\n          return this;\n        }\n        send(ua) {\n          if (!(ua instanceof UserAgent)) {\n            throw new Error("Request.send expects a UserAgent");\n          }\n          return ua.send(this);\n        }\n        send_async(ua) {\n          if (!(ua instanceof UserAgent)) {\n            throw new Error("Request.send_async expects a UserAgent");\n          }\n          return ua.send_async(this);\n        }\n      };\n      function _derToPem(label, der) {\n        const bytes = der instanceof Uint8Array ? der : der && der.bytes instanceof Uint8Array ? der.bytes : Uint8Array.from(der || []);\n        const base642 = Buffer.from(bytes).toString("base64");\n        const lines = base642.match(/.{1,64}/gu) || [];\n        return `-----BEGIN ${label}-----\n${lines.join("\\n")}\n-----END ${label}-----\n`;\n      }\n      function _certificatePem(value, label) {\n        if (value == null) {\n          return "";\n        }\n        if (typeof value === "string") {\n          if (!value.includes("-----BEGIN CERTIFICATE-----")) {\n            throw new Error(`${label} expects PEM certificate text`);\n          }\n          return value;\n        }\n        if (value && value.__secureCertificate) {\n          return _derToPem("CERTIFICATE", value.__secureCertificate.der);\n        }\n        throw new Error(`TypeException: ${label} expects Certificate, String PEM, or Array`);\n      }\n      function _caPem(value, label) {\n        if (value == null) {\n          return null;\n        }\n        if (Array.isArray(value)) {\n          return value.map((item) => _certificatePem(item, label)).join("");\n        }\n        return _certificatePem(value, label);\n      }\n      function _tlsPolicy(spec, uaConfig) {\n        const config = _toDict(uaConfig);\n        const policy = {\n          tls_identity: Object.prototype.hasOwnProperty.call(spec, "tls_identity") ? spec.tls_identity : config.tls_identity ?? null,\n          tls_ca: config.tls_ca ?? null,\n          tls_verify: Object.prototype.hasOwnProperty.call(config, "tls_verify") ? Boolean(config.tls_verify) : true,\n          tls_server_name: config.tls_server_name ?? null,\n          tls_min_version: config.tls_min_version ?? null,\n          tls_ciphers: config.tls_ciphers ?? null\n        };\n        policy.active = Boolean(\n          policy.tls_identity || policy.tls_ca || policy.tls_verify === false || policy.tls_server_name || policy.tls_min_version || policy.tls_ciphers\n        );\n        return policy;\n      }\n      function _assertBrowserTlsSupported(policy) {\n        if (hostName2 === "browser" && policy.active) {\n          throw new Error(\n            "std/net/http TLS client configuration is not supported on JS/Browser"\n          );\n        }\n      }\n      function _identityState(identity, label) {\n        if (!identity || !identity.__secureTlsIdentity) {\n          throw new Error(`TypeException: ${label} expects TlsIdentity`);\n        }\n        return identity.__secureTlsIdentity;\n      }\n      function _tlsMinVersion(value) {\n        if (value == null) {\n          return void 0;\n        }\n        const text = String(value).toLowerCase();\n        if (text === "tls1.2") {\n          return "TLSv1.2";\n        }\n        if (text === "tls1.3") {\n          return "TLSv1.3";\n        }\n        throw new Error("std/net/http tls_min_version must be \'tls1.2\' or \'tls1.3\'");\n      }\n      function _writeTempFile(content, files) {\n        const fs = _nodeFs();\n        const os = _nodeOs();\n        const path = _nodePath();\n        if (!fs || !os || !path) {\n          throw new Error("Exception: temporary TLS file support is unavailable");\n        }\n        const dir = fs.mkdtempSync(path.join(os.tmpdir(), "zuzu-http-tls-"));\n        const file = path.join(dir, "material.pem");\n        fs.writeFileSync(file, content);\n        files.push(file, dir);\n        return file;\n      }\n      function _cleanupTempFiles(files) {\n        const fs = _nodeFs();\n        if (!fs) {\n          return;\n        }\n        for (const file of files) {\n          try {\n            if (fs.statSync(file).isDirectory()) {\n              fs.rmdirSync(file);\n            } else {\n              fs.unlinkSync(file);\n            }\n          } catch (_err) {\n          }\n        }\n      }\n      function _curlRequest(spec, uaConfig) {\n        const spawnSync = _nodeSpawnSync();\n        if (!spawnSync) {\n          throw new Error("Exception: curl transport is unavailable");\n        }\n        const policy = _tlsPolicy(spec, uaConfig);\n        if (policy.tls_server_name) {\n          throw new Error(\n            "std/net/http tls_server_name is not supported by the synchronous JS/Node HTTP backend"\n          );\n        }\n        const method = String(spec.method || "GET").toUpperCase();\n        const target = _urlWithQuery(spec.url, spec.query);\n        const args = [\n          "-sS",\n          "-i",\n          "-L",\n          "--max-redirs",\n          String(_maxRedirect(spec, uaConfig)),\n          "-w",\n          "\\n\\n__ZUZU_EFFECTIVE_URL:%{url_effective}",\n          "-X",\n          method,\n          target\n        ];\n        const tempFiles = [];\n        const headers = { ..._toDict(uaConfig.default_headers), ..._toDict(spec.headers) };\n        if (uaConfig.agent) {\n          headers["user-agent"] = String(uaConfig.agent);\n        }\n        if (uaConfig.cookie_jar && typeof uaConfig.cookie_jar.cookie_header === "function") {\n          const cookie = uaConfig.cookie_jar.cookie_header(target);\n          if (cookie) {\n            headers.cookie = cookie;\n          }\n        }\n        for (const [name2, value] of Object.entries(headers)) {\n          args.push("-H", `${name2}: ${String(value)}`);\n        }\n        if (spec.json !== void 0) {\n          args.push("--data", JSON.stringify(spec.json));\n        } else if (spec.upload_from !== void 0) {\n          args.push("--data-binary", `@${String(spec.upload_from)}`);\n        } else if (spec.body !== void 0) {\n          args.push("--data", String(spec.body));\n        }\n        if (policy.tls_identity) {\n          const identity = _identityState(\n            policy.tls_identity,\n            "std/net/http tls_identity"\n          );\n          args.push("--cert", _writeTempFile(\n            identity.certPem,\n            tempFiles\n          ));\n          args.push("--key", _writeTempFile(identity.keyPem, tempFiles));\n        }\n        if (policy.tls_ca) {\n          args.push("--cacert", _writeTempFile(\n            _caPem(policy.tls_ca, "std/net/http tls_ca"),\n            tempFiles\n          ));\n        }\n        if (policy.tls_verify === false) {\n          args.push("--insecure");\n        }\n        if (policy.tls_min_version) {\n          args.push(\n            String(policy.tls_min_version).toLowerCase() === "tls1.3" ? "--tlsv1.3" : "--tlsv1.2"\n          );\n        }\n        if (policy.tls_ciphers) {\n          args.push("--ciphers", String(policy.tls_ciphers));\n        }\n        let spawned;\n        try {\n          spawned = spawnSync("curl", args, { encoding: "utf8" });\n        } finally {\n          _cleanupTempFiles(tempFiles);\n        }\n        if (spawned.error) {\n          throw spawned.error;\n        }\n        let raw = String(spawned.stdout || "");\n        let effectiveUrl = target;\n        const effectiveMatch = raw.match(/\\n\\n__ZUZU_EFFECTIVE_URL:([^\\n\\r]*)\\s*$/u);\n        if (effectiveMatch) {\n          effectiveUrl = effectiveMatch[1] || target;\n          raw = raw.slice(0, effectiveMatch.index);\n        }\n        const split = raw.split(/\\r?\\n\\r?\\n/u);\n        let headerIndex = 0;\n        for (let i = 0; i < split.length; i++) {\n          if (/^HTTP\\/\\d(?:\\.\\d)?\\s+\\d+/u.test(split[i] || "")) {\n            headerIndex = i;\n          }\n        }\n        const headerText = split[headerIndex] || "";\n        const body = split.slice(headerIndex + 1).join("\\n\\n");\n        const headerLines = headerText.split(/\\r?\\n/u);\n        const statusLine = headerLines.shift() || "HTTP/1.1 599 Request Failed";\n        const statusMatch = statusLine.match(/^HTTP\\/\\d(?:\\.\\d)?\\s+(\\d+)(?:\\s+(.*))?$/u);\n        const status = statusMatch ? Number(statusMatch[1]) : 599;\n        const reason = statusMatch ? statusMatch[2] || "" : "Request Failed";\n        const outHeaders = {};\n        for (const line of headerLines) {\n          const idx = line.indexOf(":");\n          if (idx < 0) {\n            continue;\n          }\n          outHeaders[line.slice(0, idx).trim().toLowerCase()] = line.slice(idx + 1).trim();\n        }\n        if (outHeaders["set-cookie"] && uaConfig.cookie_jar && typeof uaConfig.cookie_jar.add === "function") {\n          uaConfig.cookie_jar.add(effectiveUrl, outHeaders["set-cookie"]);\n        }\n        _writeDownload(spec, body);\n        return new Response({\n          status,\n          reason,\n          url: effectiveUrl,\n          content: body,\n          headers: outHeaders,\n          success: status >= 200 && status < 300\n        });\n      }\n      function _nodeHttpsRequest(spec, uaConfig, signal = null) {\n        const https = _nodeHttps();\n        if (!https) {\n          throw new Error("Exception: https transport is unavailable");\n        }\n        const policy = _tlsPolicy(spec, uaConfig);\n        const method = String(spec.method || "GET").toUpperCase();\n        const target = _urlWithQuery(spec.url, spec.query);\n        const url = new URL(target);\n        if (url.protocol !== "https:") {\n          throw new Error("std/net/http TLS configuration requires an https URL");\n        }\n        const headers = { ..._toDict(uaConfig.default_headers), ..._toDict(spec.headers) };\n        if (uaConfig.agent) {\n          headers["user-agent"] = String(uaConfig.agent);\n        }\n        if (uaConfig.cookie_jar && typeof uaConfig.cookie_jar.cookie_header === "function") {\n          const cookie = uaConfig.cookie_jar.cookie_header(target);\n          if (cookie) {\n            headers.cookie = cookie;\n          }\n        }\n        const body = spec.json !== void 0 ? JSON.stringify(spec.json) : spec.body !== void 0 ? String(spec.body) : null;\n        if (spec.json !== void 0) {\n          headers["content-type"] = headers["content-type"] || "application/json";\n        }\n        const options = {\n          method,\n          headers,\n          rejectUnauthorized: policy.tls_verify !== false\n        };\n        if (policy.tls_identity) {\n          const identity = _identityState(\n            policy.tls_identity,\n            "std/net/http tls_identity"\n          );\n          options.cert = identity.chainPem || identity.certPem;\n          options.key = identity.keyPem;\n          if (identity.password) {\n            options.passphrase = identity.password;\n          }\n        }\n        if (policy.tls_ca) {\n          options.ca = _caPem(policy.tls_ca, "std/net/http tls_ca");\n        }\n        if (policy.tls_server_name) {\n          options.servername = String(policy.tls_server_name);\n        }\n        if (policy.tls_min_version) {\n          options.minVersion = _tlsMinVersion(policy.tls_min_version);\n        }\n        if (policy.tls_ciphers) {\n          options.ciphers = String(policy.tls_ciphers);\n        }\n        return new Promise((resolve, reject) => {\n          const req = https.request(url, options, (response) => {\n            const chunks = [];\n            response.on("data", (chunk) => chunks.push(chunk));\n            response.on("end", () => {\n              const outHeaders = {};\n              for (const [name2, value] of Object.entries(response.headers)) {\n                outHeaders[String(name2).toLowerCase()] = Array.isArray(value) ? value.join(", ") : String(value ?? "");\n              }\n              if (outHeaders["set-cookie"] && uaConfig.cookie_jar && typeof uaConfig.cookie_jar.add === "function") {\n                uaConfig.cookie_jar.add(target, outHeaders["set-cookie"]);\n              }\n              const content = Buffer.concat(chunks).toString("utf8");\n              _writeDownload(spec, content);\n              resolve(new Response({\n                status: response.statusCode || 599,\n                reason: response.statusMessage || "",\n                url: target,\n                content,\n                headers: outHeaders,\n                success: (response.statusCode || 0) >= 200 && (response.statusCode || 0) < 300\n              }));\n            });\n          });\n          req.on("error", reject);\n          if (signal) {\n            signal.addEventListener("abort", () => req.destroy(\n              new Error("HTTP request cancelled")\n            ));\n          }\n          if (body != null) {\n            req.write(body);\n          }\n          req.end();\n        });\n      }\n      async function _fetchRequest(spec, uaConfig, signal = null) {\n        if (typeof fetch !== "function") {\n          throw new Error("Exception: fetch transport is unavailable");\n        }\n        const method = String(spec.method || "GET").toUpperCase();\n        const target = _urlWithQuery(spec.url, spec.query);\n        const headers = { ..._toDict(uaConfig.default_headers), ..._toDict(spec.headers) };\n        if (uaConfig.agent) {\n          headers["user-agent"] = String(uaConfig.agent);\n        }\n        if (uaConfig.cookie_jar && typeof uaConfig.cookie_jar.cookie_header === "function") {\n          const cookie = uaConfig.cookie_jar.cookie_header(target);\n          if (cookie) {\n            headers.cookie = cookie;\n          }\n        }\n        const fetchOptions = {\n          method,\n          headers\n        };\n        if (signal) {\n          fetchOptions.signal = signal;\n        }\n        if (spec.json !== void 0) {\n          headers["content-type"] = headers["content-type"] || "application/json";\n          fetchOptions.body = JSON.stringify(spec.json);\n        } else if (spec.body !== void 0) {\n          fetchOptions.body = String(spec.body);\n        }\n        const response = await fetch(target, {\n          ...fetchOptions,\n          redirect: _maxRedirect(spec, uaConfig) === 0 ? "manual" : "follow"\n        });\n        const outHeaders = {};\n        if (response.headers && typeof response.headers.forEach === "function") {\n          response.headers.forEach((value, key) => {\n            outHeaders[String(key).toLowerCase()] = String(value);\n          });\n        }\n        if (outHeaders["set-cookie"] && uaConfig.cookie_jar && typeof uaConfig.cookie_jar.add === "function") {\n          uaConfig.cookie_jar.add(target, outHeaders["set-cookie"]);\n        }\n        const content = await response.text();\n        _writeDownload(spec, content);\n        return new Response({\n          status: response.status,\n          reason: response.statusText || "",\n          url: response.url || target,\n          content,\n          headers: outHeaders,\n          success: response.ok\n        });\n      }\n      async function _asyncRequest(spec, uaConfig, signal = null) {\n        try {\n          const policy = _tlsPolicy(spec, uaConfig);\n          _assertBrowserTlsSupported(policy);\n          if (hostName2 !== "browser" && policy.active) {\n            return await _nodeHttpsRequest(spec, uaConfig, signal);\n          }\n          if (typeof fetch === "function") {\n            return await _fetchRequest(spec, uaConfig, signal);\n          }\n          if (hostName2 !== "browser" && String(_urlWithQuery(spec.url, spec.query)).startsWith("https:") && _nodeHttps()) {\n            return await _nodeHttpsRequest(spec, uaConfig, signal);\n          }\n          return _curlRequest(spec, uaConfig);\n        } catch (err) {\n          return new Response({\n            status: 599,\n            reason: err && err.message ? err.message : String(err || "Request Failed"),\n            url: _urlWithQuery(spec.url, spec.query),\n            content: "",\n            headers: {},\n            success: false\n          });\n        }\n      }\n      var UserAgent = class {\n        constructor(options = {}, named = {}) {\n          this._config = { ..._toDict(options), ..._toDict(named) };\n        }\n        build_request(method, url) {\n          return new Request(method, url);\n        }\n        send(request) {\n          if (!(request instanceof Request)) {\n            throw new Error("UserAgent.send expects a Request");\n          }\n          traceBlockingOperation("std/net/http UserAgent.send");\n          const policy = _tlsPolicy(request._spec, this._config);\n          _assertBrowserTlsSupported(policy);\n          if (hostName2 === "browser") {\n            return _syncUnsupportedResponse(request._spec);\n          }\n          if (!_nodeSpawnSync() && typeof fetch === "function") {\n            return _fetchRequest(request._spec, this._config);\n          }\n          return _curlRequest(request._spec, this._config);\n        }\n        send_async(request) {\n          if (!(request instanceof Request)) {\n            throw new Error("UserAgent.send_async expects a Request");\n          }\n          const timeoutSeconds = Number(\n            request._spec.timeout || this._config.timeout || 0\n          );\n          const controller = typeof AbortController === "function" ? new AbortController() : null;\n          let timer = null;\n          const task = new Task(\n            () => _asyncRequest(\n              request._spec,\n              this._config,\n              controller ? controller.signal : null\n            ),\n            {\n              name: "http.request",\n              cancel() {\n                if (timer != null) {\n                  clearTimeout(timer);\n                  timer = null;\n                }\n                if (controller) {\n                  controller.abort();\n                }\n              }\n            }\n          );\n          if (timeoutSeconds > 0 && controller) {\n            timer = setTimeout(() => {\n              controller.abort();\n            }, Math.floor(timeoutSeconds * 1e3));\n            task.finally(() => {\n              if (timer != null) {\n                clearTimeout(timer);\n                timer = null;\n              }\n            });\n          }\n          return task;\n        }\n        request(method, url, data, headers) {\n          const req = this.build_request(method, url);\n          if (method === "POST" || method === "PUT" || method === "PATCH") {\n            if (data !== void 0) {\n              req.body(data);\n            }\n            if (headers !== void 0) {\n              req.headers(headers);\n            }\n          } else {\n            if (data !== void 0) {\n              req.headers(data);\n            }\n          }\n          return this.send(req);\n        }\n        request_async(method, url, data, headers) {\n          const req = this.build_request(method, url);\n          if (method === "POST" || method === "PUT" || method === "PATCH") {\n            if (data !== void 0) {\n              req.body(data);\n            }\n            if (headers !== void 0) {\n              req.headers(headers);\n            }\n          } else if (data !== void 0) {\n            req.headers(data);\n          }\n          return this.send_async(req);\n        }\n        get(url, headers) {\n          return this.request("GET", url, headers);\n        }\n        get_async(url, headers) {\n          return this.request_async("GET", url, headers);\n        }\n        head(url, headers) {\n          return this.request("HEAD", url, headers);\n        }\n        head_async(url, headers) {\n          return this.request_async("HEAD", url, headers);\n        }\n        delete(url, headers) {\n          return this.request("DELETE", url, headers);\n        }\n        delete_async(url, headers) {\n          return this.request_async("DELETE", url, headers);\n        }\n        options(url, headers) {\n          return this.request("OPTIONS", url, headers);\n        }\n        options_async(url, headers) {\n          return this.request_async("OPTIONS", url, headers);\n        }\n        post(url, data, headers) {\n          return this.request("POST", url, data, headers);\n        }\n        post_async(url, data, headers) {\n          return this.request_async("POST", url, data, headers);\n        }\n        put(url, data, headers) {\n          return this.request("PUT", url, data, headers);\n        }\n        put_async(url, data, headers) {\n          return this.request_async("PUT", url, data, headers);\n        }\n        patch(url, data, headers) {\n          return this.request("PATCH", url, data, headers);\n        }\n        patch_async(url, data, headers) {\n          return this.request_async("PATCH", url, data, headers);\n        }\n      };\n      var api = {\n        CookieJar,\n        Request,\n        Response,\n        UserAgent\n      };\n      Object.defineProperty(api, "__zuzu_set_runtime_policy", {\n        value(policy = {}) {\n          hostName2 = policy.host_name || null;\n        },\n        enumerable: false\n      });\n      module2.exports = api;\n    }\n  });\n\n  // modules/std/math.js\n  var require_math = __commonJS({\n    "modules/std/math.js"(exports2, module2) {\n      "use strict";\n      var PI = Math.PI;\n      function normalizeNumberArgs(values) {\n        if (values.length === 1 && Array.isArray(values[0])) {\n          return values[0];\n        }\n        return values;\n      }\n      var ZMath = {\n        pi() {\n          return PI;\n        },\n        sin(value) {\n          return Math.sin(Number(value ?? 0));\n        },\n        cos(value) {\n          return Math.cos(Number(value ?? 0));\n        },\n        tan(value) {\n          return Math.tan(Number(value ?? 0));\n        },\n        asin(value) {\n          return Math.asin(Number(value ?? 0));\n        },\n        acos(value) {\n          return Math.acos(Number(value ?? 0));\n        },\n        atan(value) {\n          return Math.atan(Number(value ?? 0));\n        },\n        atan2(y, x) {\n          return Math.atan2(Number(y ?? 0), Number(x ?? 0));\n        },\n        pow(base, exp) {\n          return Math.pow(Number(base ?? 0), Number(exp ?? 0));\n        },\n        exp(value) {\n          return Math.exp(Number(value ?? 0));\n        },\n        log(value) {\n          return Math.log(Number(value ?? 0));\n        },\n        log10(value) {\n          return Math.log10(Number(value ?? 0));\n        },\n        min(...values) {\n          return Math.min(...normalizeNumberArgs(values).map(Number));\n        },\n        max(...values) {\n          return Math.max(...normalizeNumberArgs(values).map(Number));\n        },\n        sum(...values) {\n          return normalizeNumberArgs(values).map(Number).reduce((acc, v) => acc + v, 0);\n        },\n        clamp(value, low, high) {\n          return Math.min(Number(high ?? 0), Math.max(Number(low ?? 0), Number(value ?? 0)));\n        },\n        hypot(...values) {\n          return Math.hypot(...values.map(Number));\n        },\n        deg2rad(degrees) {\n          return Number(degrees ?? 0) * (PI / 180);\n        },\n        rad2deg(radians) {\n          return Number(radians ?? 0) * (180 / PI);\n        },\n        rand() {\n          return Math.random();\n        },\n        hex2dec(value) {\n          return convertBase(value, 16, 10);\n        },\n        hex2oct(value) {\n          return convertBase(value, 16, 8);\n        },\n        hex2bin(value) {\n          return convertBase(value, 16, 2);\n        },\n        dec2hex(value) {\n          return convertBase(value, 10, 16);\n        },\n        dec2oct(value) {\n          return convertBase(value, 10, 8);\n        },\n        dec2bin(value) {\n          return convertBase(value, 10, 2);\n        },\n        oct2hex(value) {\n          return convertBase(value, 8, 16);\n        },\n        oct2dec(value) {\n          return convertBase(value, 8, 10);\n        },\n        oct2bin(value) {\n          return convertBase(value, 8, 2);\n        },\n        bin2hex(value) {\n          return convertBase(value, 2, 16);\n        },\n        bin2dec(value) {\n          return convertBase(value, 2, 10);\n        },\n        bin2oct(value) {\n          return convertBase(value, 2, 8);\n        }\n      };\n      function normalizeDigits(value, base) {\n        let text = String(value ?? "").trim().toLowerCase();\n        if (base === 16) {\n          text = text.replace(/^0x/u, "");\n        } else if (base === 8) {\n          text = text.replace(/^0o/u, "");\n        } else if (base === 2) {\n          text = text.replace(/^0b/u, "");\n        }\n        return text;\n      }\n      function convertBase(value, fromBase, toBase) {\n        const text = normalizeDigits(value, fromBase);\n        if (text === "") {\n          return "0";\n        }\n        const num = Number.parseInt(text, fromBase);\n        if (Number.isNaN(num)) {\n          return "0";\n        }\n        return num.toString(toBase);\n      }\n      module2.exports = {\n        Math: ZMath,\n        pi: PI,\n        \\u03C0: PI\n      };\n    }\n  });\n\n  // modules/std/math/bignum.js\n  var require_bignum = __commonJS({\n    "modules/std/math/bignum.js"(exports2, module2) {\n      "use strict";\n      var BigNum = class _BigNum {\n        constructor(value, text = null, isInt = null) {\n          if (typeof value === "bigint") {\n            this._value = value;\n            this._text = text == null ? String(value) : String(text);\n            this._isInt = isInt == null ? true : Boolean(isInt);\n            return;\n          }\n          this._value = Number(value ?? 0);\n          this._text = text == null ? String(this._value) : String(text);\n          this._isInt = isInt == null ? Number.isInteger(this._value) : Boolean(isInt);\n        }\n        static _coerce(value) {\n          if (value instanceof _BigNum) {\n            return value;\n          }\n          if (typeof value === "string") {\n            return _BigNum.from_dec(value);\n          }\n          return new _BigNum(Number(value ?? 0));\n        }\n        static from_dec(value) {\n          const text = String(value ?? "0").trim();\n          const safeText = text || "0";\n          if (_BigNum._isIntegerText(safeText)) {\n            return new _BigNum(BigInt(safeText), safeText, true);\n          }\n          return new _BigNum(Number(safeText), safeText, !/[.eE]/.test(safeText));\n        }\n        static from_hex(value) {\n          const text = String(value ?? "0").trim().replace(/^0x/u, "").toLowerCase() || "0";\n          const negative = text.startsWith("-");\n          const digits = text.replace(/^[+-]/u, "");\n          const parsed = BigInt(`0x${digits}`) * (negative ? -1n : 1n);\n          return new _BigNum(parsed, String(parsed), true);\n        }\n        is_int() {\n          return this._isInt;\n        }\n        _toBigInt() {\n          if (!this._isInt) {\n            return null;\n          }\n          if (typeof this._value === "bigint") {\n            return this._value;\n          }\n          try {\n            return BigInt(this._text);\n          } catch {\n            return null;\n          }\n        }\n        _toNumber() {\n          return typeof this._value === "bigint" ? Number(this._value) : this._value;\n        }\n        bcmp(other) {\n          const rhs = _BigNum._coerce(other);\n          const lhsBigInt = this._toBigInt();\n          const rhsBigInt = rhs._toBigInt();\n          if (lhsBigInt !== null && rhsBigInt !== null) {\n            return lhsBigInt < rhsBigInt ? -1 : lhsBigInt > rhsBigInt ? 1 : 0;\n          }\n          return this._toNumber() < rhs._toNumber() ? -1 : this._toNumber() > rhs._toNumber() ? 1 : 0;\n        }\n        beq(other) {\n          return this.bcmp(other) === 0;\n        }\n        bne(other) {\n          return this.bcmp(other) !== 0;\n        }\n        blt(other) {\n          return this.bcmp(other) < 0;\n        }\n        ble(other) {\n          return this.bcmp(other) <= 0;\n        }\n        bgt(other) {\n          return this.bcmp(other) > 0;\n        }\n        bge(other) {\n          return this.bcmp(other) >= 0;\n        }\n        babs() {\n          const value = this._toBigInt();\n          if (value !== null) {\n            return new _BigNum(value < 0n ? -value : value, String(value < 0n ? -value : value), this._isInt);\n          }\n          return new _BigNum(Math.abs(this._toNumber()), String(Math.abs(this._toNumber())), this._isInt);\n        }\n        bneg() {\n          const value = this._toBigInt();\n          if (value !== null) {\n            return new _BigNum(-value, String(-value), this._isInt);\n          }\n          return new _BigNum(-this._toNumber(), String(-this._toNumber()), this._isInt);\n        }\n        binv() {\n          return new _BigNum(1 / this._toNumber());\n        }\n        bsin() {\n          return new _BigNum(Math.sin(this._toNumber()), String(Math.sin(this._toNumber())), false);\n        }\n        bcos() {\n          return new _BigNum(Math.cos(this._toNumber()));\n        }\n        btan() {\n          return new _BigNum(Math.tan(this._toNumber()), String(Math.tan(this._toNumber())), false);\n        }\n        bsqrt() {\n          return new _BigNum(Math.sqrt(this._toNumber()));\n        }\n        bround() {\n          return new _BigNum(Math.round(this._toNumber()));\n        }\n        bfloor() {\n          return new _BigNum(Math.floor(this._toNumber()));\n        }\n        bceil() {\n          return new _BigNum(Math.ceil(this._toNumber()));\n        }\n        badd(other) {\n          const rhs = _BigNum._coerce(other);\n          const lhsInt = this._toBigInt();\n          const rhsInt = rhs._toBigInt();\n          if (lhsInt !== null && rhsInt !== null) {\n            return new _BigNum(lhsInt + rhsInt, String(lhsInt + rhsInt), false);\n          }\n          return new _BigNum(this._toNumber() + rhs._toNumber(), String(this._toNumber() + rhs._toNumber()), false);\n        }\n        bsub(other) {\n          const rhs = _BigNum._coerce(other);\n          const lhsInt = this._toBigInt();\n          const rhsInt = rhs._toBigInt();\n          if (lhsInt !== null && rhsInt !== null) {\n            return new _BigNum(lhsInt - rhsInt, String(lhsInt - rhsInt), false);\n          }\n          return new _BigNum(this._toNumber() - rhs._toNumber(), String(this._toNumber() - rhs._toNumber()), false);\n        }\n        bmul(other) {\n          const rhs = _BigNum._coerce(other);\n          const lhsInt = this._toBigInt();\n          const rhsInt = rhs._toBigInt();\n          if (lhsInt !== null && rhsInt !== null) {\n            return new _BigNum(lhsInt * rhsInt, String(lhsInt * rhsInt), false);\n          }\n          return new _BigNum(this._toNumber() * rhs._toNumber(), String(this._toNumber() * rhs._toNumber()), false);\n        }\n        bdiv(other) {\n          const rhs = _BigNum._coerce(other);\n          return new _BigNum(this._toNumber() / rhs._toNumber());\n        }\n        bmod(other) {\n          const rhs = _BigNum._coerce(other);\n          const lhsInt = this._toBigInt();\n          const rhsInt = rhs._toBigInt();\n          if (lhsInt !== null && rhsInt !== null && rhsInt !== 0n) {\n            return new _BigNum(lhsInt % rhsInt, String(lhsInt % rhsInt), true);\n          }\n          return new _BigNum(this._toNumber() % rhs._toNumber());\n        }\n        bpow(other) {\n          const rhs = _BigNum._coerce(other);\n          const lhsInt = this._toBigInt();\n          const rhsInt = rhs._toBigInt();\n          if (lhsInt !== null && rhsInt !== null && rhsInt >= 0n) {\n            let base = lhsInt;\n            let power = rhsInt;\n            let result = 1n;\n            while (power > 0n) {\n              if (power & 1n) {\n                result *= base;\n              }\n              power >>= 1n;\n              if (power > 0n) {\n                base *= base;\n              }\n            }\n            return new _BigNum(result, String(result), true);\n          }\n          return new _BigNum(this._toNumber() ** rhs._toNumber());\n        }\n        to_hex() {\n          const value = this._toBigInt();\n          if (value === null) {\n            return `0x${Math.trunc(this._toNumber()).toString(16)}`;\n          }\n          if (value === 0n) {\n            return "0x0";\n          }\n          const absolute = value < 0n ? -value : value;\n          return value < 0n ? `-0x${absolute.toString(16)}` : `0x${absolute.toString(16)}`;\n        }\n        to_dec() {\n          return this._textify();\n        }\n        to_String() {\n          return this.to_dec();\n        }\n        toString() {\n          return String(this.to_String());\n        }\n        to_Number() {\n          return this._toNumber();\n        }\n        static _isIntegerText(text) {\n          return /^[+-]?(?:\\d+)$/u.test(text);\n        }\n        _textify() {\n          if (this._text != null && /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)$/u.test(this._text)) {\n            return this._text.replace(/\\.0+$/u, "").replace(/(\\.\\d*?)0+$/u, "$1").replace(/\\.$/u, "");\n          }\n          return this._toBigInt() !== null ? this._toBigInt().toString() : String(this._value);\n        }\n      };\n      module2.exports = {\n        BigNum\n      };\n    }\n  });\n\n  // modules/std/eval.js\n  var require_eval = __commonJS({\n    "modules/std/eval.js"(exports2, module2) {\n      "use strict";\n      function evalZuzu(code) {\n        const src = String(code ?? "");\n        return (0, eval)(src);\n      }\n      module2.exports = {\n        eval: evalZuzu\n      };\n    }\n  });\n\n  // modules/std/gui/objects.js\n  var require_objects = __commonJS({\n    "modules/std/gui/objects.js"(exports2, module2) {\n      "use strict";\n      var {\n        makeWeakValue,\n        retainValue,\n        releaseValue,\n        resolveWeakValue\n      } = require_runtime_helpers();\n      var runtimePolicy2 = {\n        deny_gui: true,\n        gui: null,\n        host_name: "node"\n      };\n      var meta = {\n        backend: "electron-dom",\n        font_size_pixels: 16,\n        font_name: "system-ui",\n        font_point_size: 12\n      };\n      var nextWidgetId = 1;\n      function _getProp(props, key, fallback = null) {\n        if (props && typeof props.get === "function") {\n          return props.get(key, fallback);\n        }\n        if (props && Object.prototype.hasOwnProperty.call(props, key)) {\n          return props[key];\n        }\n        return fallback;\n      }\n      function _setProp(props, key, value) {\n        if (props && typeof props.set === "function") {\n          if (typeof props.remove === "function") {\n            props.remove(key);\n          }\n          props.set(key, value);\n          return;\n        }\n        props[key] = value;\n      }\n      function _getChildren(props) {\n        const children = _getProp(props, "children", []);\n        return Array.isArray(children) ? children : [];\n      }\n      function _asBool(value) {\n        return value ? true : false;\n      }\n      function _asArray(value) {\n        return Array.isArray(value) ? value : [];\n      }\n      function _itemChildren(item) {\n        if (item && typeof item === "object") {\n          if (typeof item.get === "function") {\n            return _asArray(item.get("children", []));\n          }\n          if (Array.isArray(item.children)) {\n            return item.children;\n          }\n        }\n        return [];\n      }\n      function _isMenuKind(value) {\n        return value instanceof Menu || value instanceof MenuItem;\n      }\n      function _weak(value) {\n        return makeWeakValue(value);\n      }\n      function _resolve(value) {\n        return resolveWeakValue(value);\n      }\n      function _retainDispatchPath(path) {\n        for (const widget of path) {\n          retainValue(widget);\n        }\n      }\n      function _releaseDispatchPath(path) {\n        for (const widget of path) {\n          releaseValue(widget);\n        }\n      }\n      var ListenerToken = class {\n        constructor(widget, type, id) {\n          this.widget = _weak(widget);\n          this.type = String(type);\n          this.id = id;\n        }\n      };\n      var Event = class {\n        constructor(props = {}) {\n          this.__zuzu_name = String(props.name || props.type || "");\n          this.__zuzu_target = _weak(props.target || null);\n          this.__zuzu_current_target = _weak(props.current_target || null);\n          this.__zuzu_timestamp = Date.now() / 1e3;\n          this.__zuzu_data = Object.prototype.hasOwnProperty.call(props, "data") ? props.data : null;\n          this.__zuzu_value = Object.prototype.hasOwnProperty.call(props, "value") ? props.value : null;\n          this.__zuzu_cancelled = false;\n          this.__zuzu_propagation_stopped = false;\n          this.__zuzu_default_prevented = false;\n          this.__zuzu_phase = "";\n        }\n        name() {\n          return this.__zuzu_name;\n        }\n        type() {\n          return this.__zuzu_name;\n        }\n        target() {\n          return _resolve(this.__zuzu_target);\n        }\n        current_target() {\n          return _resolve(this.__zuzu_current_target);\n        }\n        currentTarget() {\n          return _resolve(this.__zuzu_current_target);\n        }\n        phase() {\n          return this.__zuzu_phase;\n        }\n        timestamp() {\n          return this.__zuzu_timestamp;\n        }\n        data() {\n          return this.__zuzu_data;\n        }\n        value() {\n          return this.__zuzu_value;\n        }\n        cancelled() {\n          return this.__zuzu_cancelled;\n        }\n        propagation_stopped() {\n          return this.__zuzu_propagation_stopped;\n        }\n        default_prevented() {\n          return this.__zuzu_default_prevented;\n        }\n        window() {\n          const target = _resolve(this.__zuzu_target);\n          return target instanceof Widget ? target.__zuzu_owner_window_live() : null;\n        }\n        stop_propagation() {\n          this.__zuzu_propagation_stopped = true;\n          this.__zuzu_cancelled = true;\n          return this;\n        }\n        prevent_default() {\n          this.__zuzu_default_prevented = true;\n          this.__zuzu_cancelled = true;\n          return this;\n        }\n      };\n      var Widget = class _Widget {\n        constructor(props = {}) {\n          this.__zuzu_gui_id = `w${nextWidgetId++}`;\n          this.__zuzu_gui_type = this.__zuzu_gui_type_name || this.constructor.name;\n          this.__zuzu_props = props || {};\n          this.__zuzu_parent = _weak(null);\n          this.__zuzu_event_parent = null;\n          this.__zuzu_children = [];\n          this.__zuzu_listeners = /* @__PURE__ */ new Map();\n          this.__zuzu_listener_seq = 0;\n          this.__zuzu_meta = /* @__PURE__ */ Object.create(null);\n          this.__zuzu_style = /* @__PURE__ */ Object.create(null);\n          this.__zuzu_classes = [];\n          for (const child of _getChildren(this.__zuzu_props)) {\n            this.add_child(child);\n          }\n        }\n        id(value) {\n          if (arguments.length === 0) {\n            return _getProp(this.__zuzu_props, "id", null);\n          }\n          _setProp(this.__zuzu_props, "id", value == null ? null : String(value));\n          this.__zuzu_update_native();\n          return this;\n        }\n        set_id(value) {\n          return this.id(value);\n        }\n        parent() {\n          return _resolve(this.__zuzu_parent);\n        }\n        children() {\n          return this.__zuzu_children.slice();\n        }\n        add_child(child) {\n          if (child == null) {\n            return this;\n          }\n          if (!(child instanceof _Widget)) {\n            throw new Error("GUI_PROP_TYPE: add_child expects a Widget");\n          }\n          if (this instanceof MenuItem) {\n            throw new Error("GUI_PROP_TYPE: MenuItem widgets cannot have children");\n          }\n          if (child instanceof Menu && !(this instanceof Window)) {\n            throw new Error("GUI_PROP_TYPE: Menu widgets can only be Window children");\n          }\n          if (child instanceof MenuItem && !(this instanceof Menu)) {\n            throw new Error("GUI_PROP_TYPE: MenuItem widgets can only be Menu children");\n          }\n          if (this instanceof Menu && !(child instanceof MenuItem)) {\n            throw new Error("GUI_PROP_TYPE: Menu widgets can only contain MenuItem children");\n          }\n          const oldParent = child.parent();\n          if (oldParent && oldParent !== this) {\n            oldParent.remove_child(child);\n          }\n          if (this.__zuzu_children.includes(child)) {\n            return this;\n          }\n          child.__zuzu_parent = _weak(this);\n          child.__zuzu_event_parent = this;\n          this.__zuzu_children.push(child);\n          this.__zuzu_child_added(child);\n          if (this instanceof Window && !_isMenuKind(child) && this.__zuzu_content == null) {\n            this.__zuzu_content = child;\n          }\n          this.__zuzu_create_native_child(child);\n          return this;\n        }\n        __zuzu_child_added(_child) {\n        }\n        remove_child(child) {\n          if (!(child instanceof _Widget)) {\n            return this;\n          }\n          const before = this.__zuzu_children.length;\n          this.__zuzu_children = this.__zuzu_children.filter((item) => item !== child);\n          if (this.__zuzu_children.length === before) {\n            return this;\n          }\n          this.__zuzu_destroy_native_child(child);\n          this.__zuzu_child_removed(child);\n          if (child.parent() === this) {\n            child.__zuzu_parent = _weak(null);\n          }\n          if (child.__zuzu_event_parent === this) {\n            child.__zuzu_event_parent = null;\n          }\n          if (this instanceof Window && this.__zuzu_content === child) {\n            this.__zuzu_content = this.__zuzu_children.find(\n              (item) => !_isMenuKind(item)\n            ) || null;\n          }\n          return this;\n        }\n        __zuzu_child_removed(_child) {\n        }\n        find_by_id(id) {\n          if (this.id() != null && this.id() === String(id)) {\n            return this;\n          }\n          for (const child of this.__zuzu_children) {\n            const found = child.find_by_id(id);\n            if (found) {\n              return found;\n            }\n          }\n          return null;\n        }\n        enabled(value) {\n          if (arguments.length === 0) {\n            return _getProp(this.__zuzu_props, "disabled", false) ? false : Boolean(_getProp(this.__zuzu_props, "enabled", true));\n          }\n          _setProp(this.__zuzu_props, "enabled", value ? true : false);\n          _setProp(this.__zuzu_props, "disabled", value ? false : true);\n          this.__zuzu_update_native();\n          return this;\n        }\n        set_enabled(value) {\n          return this.enabled(value);\n        }\n        disabled(value) {\n          if (arguments.length === 0) {\n            return this.enabled() ? false : true;\n          }\n          return this.enabled(value ? false : true);\n        }\n        visible(value) {\n          if (arguments.length === 0) {\n            return Boolean(_getProp(this.__zuzu_props, "visible", true));\n          }\n          _setProp(this.__zuzu_props, "visible", value ? true : false);\n          this.__zuzu_update_native();\n          return this;\n        }\n        set_visible(value) {\n          return this.visible(value);\n        }\n        classes() {\n          return this.__zuzu_classes.slice();\n        }\n        add_class(name2) {\n          const key = String(name2);\n          if (!this.__zuzu_classes.includes(key)) {\n            this.__zuzu_classes.push(key);\n            this.__zuzu_update_native();\n          }\n          return this;\n        }\n        remove_class(name2) {\n          const key = String(name2);\n          const before = this.__zuzu_classes.length;\n          this.__zuzu_classes = this.__zuzu_classes.filter((item) => item !== key);\n          if (before !== this.__zuzu_classes.length) {\n            this.__zuzu_update_native();\n          }\n          return this;\n        }\n        style(key, value) {\n          if (arguments.length === 0) {\n            return { ...this.__zuzu_style };\n          }\n          const name2 = String(key);\n          if (arguments.length === 1) {\n            return this.__zuzu_style[name2] ?? null;\n          }\n          this.__zuzu_style[name2] = value;\n          this.__zuzu_update_native();\n          return this;\n        }\n        meta(key, value) {\n          if (arguments.length === 0) {\n            return { ...this.__zuzu_meta };\n          }\n          const name2 = String(key);\n          if (arguments.length === 1) {\n            return this.__zuzu_meta[name2] ?? null;\n          }\n          this.__zuzu_meta[name2] = value;\n          return this;\n        }\n        on(type, handler) {\n          if (typeof handler !== "function") {\n            throw new Error("GUI_EVENT_HANDLER: on expects a Function handler");\n          }\n          const name2 = String(type);\n          const id = ++this.__zuzu_listener_seq;\n          if (!this.__zuzu_listeners.has(name2)) {\n            this.__zuzu_listeners.set(name2, []);\n          }\n          this.__zuzu_listeners.get(name2).push({\n            id,\n            handler,\n            once: false\n          });\n          return new ListenerToken(this, name2, id);\n        }\n        once(type, handler) {\n          if (typeof handler !== "function") {\n            throw new Error("GUI_EVENT_HANDLER: once expects a Function handler");\n          }\n          const name2 = String(type);\n          const id = ++this.__zuzu_listener_seq;\n          if (!this.__zuzu_listeners.has(name2)) {\n            this.__zuzu_listeners.set(name2, []);\n          }\n          this.__zuzu_listeners.get(name2).push({\n            id,\n            handler,\n            once: true\n          });\n          return new ListenerToken(this, name2, id);\n        }\n        off(token) {\n          if (!(token instanceof ListenerToken) || _resolve(token.widget) !== this) {\n            return false;\n          }\n          const listeners = this.__zuzu_listeners.get(token.type);\n          if (!listeners) {\n            return false;\n          }\n          const before = listeners.length;\n          const kept = listeners.filter((listener) => listener.id !== token.id);\n          this.__zuzu_listeners.set(token.type, kept);\n          return kept.length !== before;\n        }\n        emit(type, payload = null) {\n          const name2 = String(type);\n          const event = payload instanceof Event ? payload : new Event({\n            name: name2,\n            target: this,\n            data: payload,\n            value: payload\n          });\n          event.__zuzu_name = name2;\n          if (_resolve(event.__zuzu_target) == null) {\n            event.__zuzu_target = _weak(this);\n          }\n          this.__zuzu_dispatch_event(event);\n          return event;\n        }\n        __zuzu_dispatch_event(event) {\n          const path = [];\n          let current = this;\n          while (current) {\n            path.push(current);\n            current = current.__zuzu_event_parent;\n          }\n          _retainDispatchPath(path);\n          try {\n            this.__zuzu_dispatch_at(event, "target");\n            for (let i = 1; i < path.length; i++) {\n              if (event.__zuzu_propagation_stopped) {\n                break;\n              }\n              path[i].__zuzu_dispatch_at(event, "bubble");\n            }\n          } finally {\n            _releaseDispatchPath(path);\n          }\n        }\n        __zuzu_dispatch_at(event, phase) {\n          const listeners = (this.__zuzu_listeners.get(event.__zuzu_name) || []).slice();\n          if (listeners.length === 0) {\n            return;\n          }\n          event.__zuzu_current_target = _weak(this);\n          event.__zuzu_phase = phase;\n          for (const listener of listeners) {\n            listener.handler(event);\n            if (listener.once) {\n              this.off(new ListenerToken(this, event.__zuzu_name, listener.id));\n            }\n            if (event.__zuzu_propagation_stopped) {\n              break;\n            }\n          }\n        }\n        __zuzu_owner_window() {\n          let current = this;\n          while (current) {\n            if (current instanceof Window) {\n              return current;\n            }\n            current = current.parent();\n          }\n          return null;\n        }\n        __zuzu_owner_window_live() {\n          let current = this;\n          while (current) {\n            if (current instanceof Window) {\n              return current;\n            }\n            current = current.__zuzu_event_parent;\n          }\n          return null;\n        }\n        __zuzu_create_native_child(child) {\n          const window2 = this.__zuzu_owner_window_live();\n          if (!window2 || window2.__zuzu_electron_window_id == null || !runtimePolicy2.gui || typeof runtimePolicy2.gui.createWidget !== "function") {\n            return;\n          }\n          runtimePolicy2.gui.createWidget(\n            window2.__zuzu_electron_window_id,\n            this.__zuzu_gui_id,\n            child.__zuzu_gui_snapshot(),\n            this.__zuzu_children.indexOf(child)\n          );\n        }\n        __zuzu_destroy_native_child(child) {\n          const window2 = this.__zuzu_owner_window_live();\n          if (!window2 || window2.__zuzu_electron_window_id == null || !runtimePolicy2.gui || typeof runtimePolicy2.gui.destroyWidget !== "function") {\n            return;\n          }\n          runtimePolicy2.gui.destroyWidget(\n            window2.__zuzu_electron_window_id,\n            child.__zuzu_gui_id\n          );\n        }\n        __zuzu_update_native() {\n          const window2 = this.__zuzu_owner_window_live();\n          if (!window2 || window2.__zuzu_electron_window_id == null || !runtimePolicy2.gui || typeof runtimePolicy2.gui.updateWidget !== "function") {\n            return;\n          }\n          runtimePolicy2.gui.updateWidget(\n            window2.__zuzu_electron_window_id,\n            this.__zuzu_gui_snapshot()\n          );\n        }\n        __zuzu_set_prop_silent(key, value) {\n          _setProp(this.__zuzu_props, key, value);\n        }\n        __zuzu_find_by_guid(guid) {\n          if (this.__zuzu_gui_id === guid) {\n            return this;\n          }\n          for (const child of this.__zuzu_children) {\n            const found = child.__zuzu_find_by_guid(guid);\n            if (found) {\n              return found;\n            }\n          }\n          return null;\n        }\n        __zuzu_gui_snapshot() {\n          return {\n            guid: this.__zuzu_gui_id,\n            type: this.__zuzu_gui_type,\n            id: this.id(),\n            classes: this.classes(),\n            props: {\n              disabled: this.disabled(),\n              enabled: this.enabled(),\n              visible: this.visible(),\n              align: _getProp(this.__zuzu_props, "align", null),\n              alt: _getProp(this.__zuzu_props, "alt", null),\n              checked: _getProp(this.__zuzu_props, "checked", null),\n              closable: _getProp(this.__zuzu_props, "closable", null),\n              collapsible: _getProp(this.__zuzu_props, "collapsible", null),\n              collapsed: _getProp(this.__zuzu_props, "collapsed", null),\n              first_day_of_week: _getProp(this.__zuzu_props, "first_day_of_week", null),\n              fit: _getProp(this.__zuzu_props, "fit", null),\n              for_id: this.for_id ? this.for_id() : null,\n              group: _getProp(this.__zuzu_props, "group", null),\n              icon: _getProp(this.__zuzu_props, "icon", null),\n              indeterminate: _getProp(this.__zuzu_props, "indeterminate", null),\n              items: _getProp(this.__zuzu_props, "items", null),\n              label: _getProp(this.__zuzu_props, "label", null),\n              max: _getProp(this.__zuzu_props, "max", null),\n              min: _getProp(this.__zuzu_props, "min", null),\n              modal: _getProp(this.__zuzu_props, "modal", null),\n              multiline: _getProp(this.__zuzu_props, "multiline", null),\n              multiple: _getProp(this.__zuzu_props, "multiple", null),\n              name: _getProp(this.__zuzu_props, "name", null),\n              options: _getProp(this.__zuzu_props, "options", null),\n              orientation: _getProp(this.__zuzu_props, "orientation", null),\n              password: _getProp(this.__zuzu_props, "password", null),\n              title: _getProp(this.__zuzu_props, "title", null),\n              placement: _getProp(this.__zuzu_props, "placement", null),\n              text: _getProp(this.__zuzu_props, "text", null),\n              readonly: _getProp(this.__zuzu_props, "readonly", null),\n              required: _getProp(this.__zuzu_props, "required", null),\n              resizable: _getProp(this.__zuzu_props, "resizable", null),\n              selected: _getProp(this.__zuzu_props, "selected", null),\n              selected_index: _getProp(this.__zuzu_props, "selected_index", null),\n              selected_path: _getProp(this.__zuzu_props, "selected_path", null),\n              show_text: _getProp(this.__zuzu_props, "show_text", null),\n              src: _getProp(this.__zuzu_props, "src", null),\n              step: _getProp(this.__zuzu_props, "step", null),\n              value: _getProp(this.__zuzu_props, "value", null),\n              placeholder: _getProp(this.__zuzu_props, "placeholder", null),\n              variant: _getProp(this.__zuzu_props, "variant", null),\n              wrap: _getProp(this.__zuzu_props, "wrap", null),\n              width: _getProp(this.__zuzu_props, "width", null),\n              height: _getProp(this.__zuzu_props, "height", null),\n              minwidth: _getProp(this.__zuzu_props, "minwidth", null),\n              minheight: _getProp(this.__zuzu_props, "minheight", null),\n              maxwidth: _getProp(this.__zuzu_props, "maxwidth", null),\n              maxheight: _getProp(this.__zuzu_props, "maxheight", null),\n              gap: _getProp(this.__zuzu_props, "gap", null),\n              padding: _getProp(this.__zuzu_props, "padding", null)\n            },\n            children: this.__zuzu_children.map(\n              (child) => child.__zuzu_gui_snapshot()\n            )\n          };\n        }\n      };\n      for (const name2 of [\n        "width",\n        "height",\n        "minwidth",\n        "minheight",\n        "maxwidth",\n        "maxheight",\n        "align",\n        "alt",\n        "closable",\n        "collapsible",\n        "collapsed",\n        "first_day_of_week",\n        "fit",\n        "gap",\n        "group",\n        "icon",\n        "indeterminate",\n        "label",\n        "max",\n        "min",\n        "modal",\n        "multiline",\n        "multiple",\n        "name",\n        "orientation",\n        "padding",\n        "password",\n        "placement",\n        "readonly",\n        "required",\n        "resizable",\n        "selected",\n        "show_text",\n        "src",\n        "step",\n        "title",\n        "text",\n        "value",\n        "placeholder",\n        "variant",\n        "wrap"\n      ]) {\n        Widget.prototype[name2] = function propAccessor(value) {\n          if (arguments.length === 0) {\n            return _getProp(this.__zuzu_props, name2, null);\n          }\n          _setProp(this.__zuzu_props, name2, value == null ? "" : value);\n          this.__zuzu_update_native();\n          return this;\n        };\n      }\n      Widget.prototype.for_id = function forId(value) {\n        if (arguments.length === 0) {\n          return _getProp(this.__zuzu_props, "for", null);\n        }\n        _setProp(this.__zuzu_props, "for", value == null ? null : String(value));\n        this.__zuzu_update_native();\n        return this;\n      };\n      Widget.prototype.set_for_id = function setForId(value) {\n        return this.for_id(value);\n      };\n      Widget.prototype.set_value = function setValue(value) {\n        return this.value(value);\n      };\n      Widget.prototype.set_text = function setText(value) {\n        return this.text(value);\n      };\n      Widget.prototype.set_title = function setTitle(value) {\n        return this.title(value);\n      };\n      for (const eventName of [\n        "activate",\n        "blur",\n        "change",\n        "click",\n        "close_request",\n        "closed",\n        "collapse",\n        "enter",\n        "expand",\n        "focus",\n        "input",\n        "open",\n        "resize",\n        "select",\n        "submit"\n      ]) {\n        Widget.prototype[eventName] = function eventShortcut(handler = null) {\n          if (handler == null) {\n            return this.emit(eventName);\n          }\n          return this.on(eventName, handler);\n        };\n      }\n      var Window = class extends Widget {\n        constructor(props = {}) {\n          super(props);\n          this.__zuzu_close_result = null;\n          this.__zuzu_electron_window_id = null;\n          this.__zuzu_closed = false;\n          this.__zuzu_shown = false;\n          this.__zuzu_native_close_allowed = false;\n          this.__zuzu_close_waiters = [];\n          this.__zuzu_content = _getProp(props, "content", null);\n          if (this.__zuzu_content != null && (!(this.__zuzu_content instanceof Widget) || _isMenuKind(this.__zuzu_content))) {\n            throw new Error("GUI_PROP_TYPE: Window content expects a non-menu Widget or null");\n          }\n          if (this.__zuzu_content != null && !this.__zuzu_children.includes(this.__zuzu_content)) {\n            this.add_child(this.__zuzu_content);\n          }\n          if (this.__zuzu_content == null) {\n            this.__zuzu_content = this.__zuzu_children.find(\n              (child) => !_isMenuKind(child)\n            ) || null;\n          }\n        }\n        content() {\n          return this.__zuzu_content;\n        }\n        menus() {\n          return this.__zuzu_children.filter((child) => child instanceof Menu);\n        }\n        set_content(child = null) {\n          if (child != null && (!(child instanceof Widget) || _isMenuKind(child))) {\n            throw new Error("GUI_PROP_TYPE: set_content expects a non-menu Widget or null");\n          }\n          for (const old of this.__zuzu_children.slice()) {\n            if (!_isMenuKind(old)) {\n              this.remove_child(old);\n            }\n          }\n          this.__zuzu_content = child;\n          if (child != null) {\n            this.add_child(child);\n          }\n          return this;\n        }\n        show() {\n          if (runtimePolicy2.deny_gui || !runtimePolicy2.gui) {\n            throw new Error(\n              `GUI is not available on host \'${runtimePolicy2.host_name}\'`\n            );\n          }\n          if (this.__zuzu_electron_window_id != null) {\n            return this;\n          }\n          const result = runtimePolicy2.gui.openWindow(\n            this.__zuzu_gui_snapshot(),\n            {\n              onEvent: (event) => this.__zuzu_receive_gui_event(event),\n              onCloseRequest: () => this.__zuzu_native_close_request(),\n              onClosed: () => this.__zuzu_native_closed()\n            }\n          );\n          const markShown = (windowId) => {\n            this.__zuzu_electron_window_id = windowId;\n            this.__zuzu_shown = true;\n            this.emit("open");\n            return this;\n          };\n          if (result && typeof result.then === "function") {\n            return result.then(markShown);\n          }\n          return markShown(result);\n        }\n        call(options = null) {\n          const asyncCall = _getProp(options, "async", false) ? true : false;\n          if (this.__zuzu_closed) {\n            if (asyncCall) {\n              return Promise.resolve(this.__zuzu_close_result);\n            }\n            return this.__zuzu_close_result;\n          }\n          if (runtimePolicy2.host_name === "browser" && !asyncCall) {\n            throw new Error(\n              "GUI_CALL_SYNC_UNSUPPORTED: Window.call requires async: true on host \'browser\'"\n            );\n          }\n          const shown = this.show();\n          if (shown && typeof shown.then === "function") {\n            return shown.then(() => this.__zuzu_wait_for_close());\n          }\n          return this.__zuzu_wait_for_close();\n        }\n        close(result = null) {\n          return this.__zuzu_close(result, false);\n        }\n        __zuzu_close(result = null, nativeClose = false) {\n          if (this.__zuzu_closed) {\n            return this;\n          }\n          const request = this.emit("close_request", result);\n          if (request.cancelled() || request.default_prevented()) {\n            return this;\n          }\n          this.__zuzu_closed = true;\n          this.__zuzu_close_result = result;\n          if (!nativeClose && runtimePolicy2.gui && typeof runtimePolicy2.gui.closeWindow === "function" && this.__zuzu_electron_window_id != null) {\n            runtimePolicy2.gui.closeWindow(this.__zuzu_electron_window_id);\n          }\n          this.emit("closed", result);\n          this.__zuzu_resolve_close_waiters();\n          return this;\n        }\n        __zuzu_wait_for_close() {\n          if (this.__zuzu_closed) {\n            return this.__zuzu_close_result;\n          }\n          return new Promise((resolve) => {\n            this.__zuzu_close_waiters.push(resolve);\n          });\n        }\n        __zuzu_resolve_close_waiters() {\n          const waiters = this.__zuzu_close_waiters.splice(0);\n          for (const resolve of waiters) {\n            resolve(this.__zuzu_close_result);\n          }\n        }\n        __zuzu_native_close_request() {\n          if (this.__zuzu_closed) {\n            return false;\n          }\n          const request = this.emit("close_request", null);\n          if (request.cancelled() || request.default_prevented()) {\n            return true;\n          }\n          this.__zuzu_native_close_allowed = true;\n          return false;\n        }\n        __zuzu_native_closed() {\n          if (this.__zuzu_closed) {\n            return;\n          }\n          this.__zuzu_closed = true;\n          this.__zuzu_close_result = null;\n          this.emit("closed", null);\n          this.__zuzu_resolve_close_waiters();\n        }\n        __zuzu_receive_gui_event(raw = {}) {\n          const target = raw.widgetGuid ? this.__zuzu_find_by_guid(raw.widgetGuid) : this;\n          if (!target) {\n            return;\n          }\n          if (Object.prototype.hasOwnProperty.call(raw, "value")) {\n            target.__zuzu_set_prop_silent("value", raw.value);\n          }\n          if (Object.prototype.hasOwnProperty.call(raw, "checked") && typeof target.checked === "function") {\n            target.__zuzu_set_prop_silent("checked", raw.checked ? true : false);\n          }\n          if (Object.prototype.hasOwnProperty.call(raw, "selected_index") && typeof target.selected_index === "function") {\n            target.__zuzu_set_prop_silent(\n              "selected_index",\n              raw.selected_index == null ? null : Number(raw.selected_index)\n            );\n          }\n          if (Object.prototype.hasOwnProperty.call(raw, "selected") && typeof target.selected === "function") {\n            target.__zuzu_set_prop_silent(\n              "selected",\n              raw.selected == null ? null : String(raw.selected)\n            );\n            if (target instanceof Tabs) {\n              target.__zuzu_sync_tabs();\n            }\n          }\n          if (Object.prototype.hasOwnProperty.call(raw, "selected_path") && typeof target.selected_path === "function") {\n            target.__zuzu_set_prop_silent(\n              "selected_path",\n              _asArray(raw.selected_path).map(Number)\n            );\n          }\n          if (target instanceof TreeView && Object.prototype.hasOwnProperty.call(raw, "selected_path") && raw.type === "expand") {\n            target.__zuzu_set_expanded_silent(raw.selected_path, true);\n            target.emit(raw.type, new Event({\n              name: raw.type,\n              target,\n              data: raw,\n              value: raw.selected_path\n            }));\n            return;\n          }\n          if (target instanceof TreeView && Object.prototype.hasOwnProperty.call(raw, "selected_path") && raw.type === "collapse") {\n            target.__zuzu_set_expanded_silent(raw.selected_path, false);\n            target.emit(raw.type, new Event({\n              name: raw.type,\n              target,\n              data: raw,\n              value: raw.selected_path\n            }));\n            return;\n          }\n          target.emit(raw.type, new Event({\n            name: raw.type,\n            target,\n            data: raw,\n            value: Object.prototype.hasOwnProperty.call(raw, "value") ? raw.value : null\n          }));\n        }\n      };\n      var VBox = class extends Widget {\n      };\n      var HBox = class extends Widget {\n      };\n      var Frame = class extends Widget {\n      };\n      var Label = class extends Widget {\n      };\n      var Text = class extends Widget {\n      };\n      var RichText = class extends Widget {\n      };\n      var Image = class extends Widget {\n      };\n      var Input = class extends Widget {\n        constructor(props = {}) {\n          if (props && typeof props.get === "function") {\n            if (typeof props.has === "function" && props.has("value")) {\n              const value = props.get("value");\n              props.set("value", value == null ? "" : String(value));\n            }\n            super(props);\n            return;\n          }\n          const cooked = { ...props };\n          if (Object.prototype.hasOwnProperty.call(cooked, "value")) {\n            cooked.value = cooked.value == null ? "" : String(cooked.value);\n          }\n          super(cooked);\n        }\n        value(value) {\n          if (arguments.length === 0) {\n            return _getProp(this.__zuzu_props, "value", null);\n          }\n          _setProp(this.__zuzu_props, "value", value == null ? "" : String(value));\n          this.__zuzu_update_native();\n          return this;\n        }\n        select_all() {\n          this.emit("select_all");\n          return this;\n        }\n      };\n      var DatePicker = class extends Widget {\n      };\n      var Checkbox = class extends Widget {\n        checked(value) {\n          if (arguments.length === 0) {\n            return _asBool(_getProp(this.__zuzu_props, "checked", false));\n          }\n          _setProp(this.__zuzu_props, "checked", _asBool(value));\n          this.__zuzu_update_native();\n          return this;\n        }\n      };\n      var Radio = class extends Checkbox {\n        checked(value) {\n          if (arguments.length === 0) {\n            return super.checked();\n          }\n          super.checked(value);\n          const parent = this.parent();\n          if (value && parent instanceof RadioGroup) {\n            parent.value(this.value());\n          }\n          return this;\n        }\n      };\n      var RadioGroup = class extends Widget {\n        constructor(props = {}) {\n          super(props);\n          this.__zuzu_sync_radios();\n        }\n        options() {\n          return this.children().filter((child) => child instanceof Radio);\n        }\n        value(value) {\n          if (arguments.length === 0) {\n            return _getProp(this.__zuzu_props, "value", null);\n          }\n          _setProp(this.__zuzu_props, "value", value == null ? null : String(value));\n          this.__zuzu_sync_radios();\n          this.__zuzu_update_native();\n          return this;\n        }\n        __zuzu_child_added(child) {\n          if (child instanceof Radio) {\n            this.__zuzu_sync_radios();\n          }\n        }\n        __zuzu_sync_radios() {\n          const selected = this.value();\n          for (const radio of this.options()) {\n            _setProp(\n              radio.__zuzu_props,\n              "checked",\n              selected != null && String(radio.value()) === String(selected)\n            );\n          }\n        }\n        __zuzu_set_prop_silent(key, value) {\n          super.__zuzu_set_prop_silent(key, value);\n          if (key === "value") {\n            this.__zuzu_sync_radios();\n          }\n        }\n      };\n      var Select = class extends Widget {\n        options() {\n          return _asArray(_getProp(this.__zuzu_props, "options", [])).slice();\n        }\n        add_option(option) {\n          const options = this.options();\n          options.push(option);\n          _setProp(this.__zuzu_props, "options", options);\n          this.__zuzu_update_native();\n          return this;\n        }\n        clear_options() {\n          _setProp(this.__zuzu_props, "options", []);\n          this.__zuzu_update_native();\n          return this;\n        }\n      };\n      var Menu = class extends Widget {\n        items() {\n          return this.children();\n        }\n      };\n      var MenuItem = class extends Widget {\n      };\n      var Button = class extends Widget {\n      };\n      var Separator = class extends Widget {\n      };\n      var Slider = class extends Widget {\n      };\n      var Progress = class extends Widget {\n      };\n      var Tabs = class extends Widget {\n        constructor(props = {}) {\n          super(props);\n          this.__zuzu_sync_tabs();\n        }\n        tabs() {\n          return this.children().filter((child) => child instanceof Tab);\n        }\n        selected(value) {\n          if (arguments.length === 0) {\n            return _getProp(this.__zuzu_props, "selected", null);\n          }\n          _setProp(this.__zuzu_props, "selected", value == null ? null : String(value));\n          this.__zuzu_sync_tabs();\n          this.__zuzu_update_native();\n          return this;\n        }\n        selected_tab() {\n          const selected = this.selected();\n          return this.tabs().find((tab) => String(tab.value()) === String(selected)) || null;\n        }\n        __zuzu_child_added(child) {\n          if (child instanceof Tab) {\n            this.__zuzu_sync_tabs();\n          }\n        }\n        __zuzu_sync_tabs() {\n          const selected = this.selected();\n          for (const tab of this.tabs()) {\n            _setProp(\n              tab.__zuzu_props,\n              "selected",\n              selected != null && String(tab.value()) === String(selected)\n            );\n          }\n        }\n      };\n      var Tab = class extends Widget {\n        selected(value) {\n          if (arguments.length === 0) {\n            return _asBool(_getProp(this.__zuzu_props, "selected", false));\n          }\n          _setProp(this.__zuzu_props, "selected", _asBool(value));\n          const parent = this.parent();\n          if (value && parent instanceof Tabs) {\n            parent.selected(this.value());\n          } else {\n            this.__zuzu_update_native();\n          }\n          return this;\n        }\n      };\n      var ListView = class extends Widget {\n        items() {\n          return _asArray(_getProp(this.__zuzu_props, "items", [])).slice();\n        }\n        selected_index(value) {\n          if (arguments.length === 0) {\n            return _getProp(this.__zuzu_props, "selected_index", null);\n          }\n          _setProp(\n            this.__zuzu_props,\n            "selected_index",\n            value == null ? null : Number(value)\n          );\n          this.__zuzu_update_native();\n          return this;\n        }\n        selected_item() {\n          const index = this.selected_index();\n          const items = this.items();\n          return index == null ? null : items[Number(index)] ?? null;\n        }\n        add_item(item) {\n          const items = this.items();\n          items.push(item);\n          _setProp(this.__zuzu_props, "items", items);\n          this.__zuzu_update_native();\n          return this;\n        }\n        clear_items() {\n          _setProp(this.__zuzu_props, "items", []);\n          _setProp(this.__zuzu_props, "selected_index", null);\n          this.__zuzu_update_native();\n          return this;\n        }\n        activate_index(index) {\n          this.selected_index(index);\n          this.emit("activate", index);\n          return this;\n        }\n      };\n      var TreeView = class extends Widget {\n        constructor(props = {}) {\n          super(props);\n          this.__zuzu_expanded = /* @__PURE__ */ new Set();\n          this.__zuzu_mark_initial_expanded(this.items(), []);\n        }\n        items() {\n          return _asArray(_getProp(this.__zuzu_props, "items", [])).slice();\n        }\n        selected_path(value) {\n          if (arguments.length === 0) {\n            return _asArray(_getProp(this.__zuzu_props, "selected_path", [])).slice();\n          }\n          _setProp(this.__zuzu_props, "selected_path", _asArray(value).map(Number));\n          this.__zuzu_update_native();\n          return this;\n        }\n        selected_item() {\n          return this.__zuzu_item_at_path(this.selected_path());\n        }\n        add_item(item) {\n          const items = this.items();\n          items.push(item);\n          _setProp(this.__zuzu_props, "items", items);\n          this.__zuzu_update_native();\n          return this;\n        }\n        clear_items() {\n          _setProp(this.__zuzu_props, "items", []);\n          _setProp(this.__zuzu_props, "selected_path", []);\n          this.__zuzu_expanded.clear();\n          this.__zuzu_update_native();\n          return this;\n        }\n        activate_path(path) {\n          this.selected_path(path);\n          this.emit("activate", path);\n          return this;\n        }\n        expand_path(path) {\n          this.__zuzu_expanded.add(this.__zuzu_path_key(path));\n          this.__zuzu_update_native();\n          this.emit("expand", path);\n          return this;\n        }\n        collapse_path(path) {\n          this.__zuzu_expanded.delete(this.__zuzu_path_key(path));\n          this.__zuzu_update_native();\n          this.emit("collapse", path);\n          return this;\n        }\n        is_expanded(path) {\n          return this.__zuzu_expanded.has(this.__zuzu_path_key(path));\n        }\n        __zuzu_gui_snapshot() {\n          const snapshot = super.__zuzu_gui_snapshot();\n          snapshot.props.expanded_paths = [...this.__zuzu_expanded].map(\n            (key) => key.split(",").filter(Boolean).map(Number)\n          );\n          return snapshot;\n        }\n        __zuzu_item_at_path(path) {\n          let items = this.items();\n          let current = null;\n          for (const rawIndex of _asArray(path)) {\n            const index = Number(rawIndex);\n            current = items[index] ?? null;\n            if (current == null) {\n              return null;\n            }\n            items = _itemChildren(current);\n          }\n          return current;\n        }\n        __zuzu_path_key(path) {\n          return _asArray(path).map((part) => Number(part)).join(",");\n        }\n        __zuzu_mark_initial_expanded(items, prefix) {\n          for (let i = 0; i < items.length; i++) {\n            const path = [...prefix, i];\n            const children = _itemChildren(items[i]);\n            if (children.length > 0) {\n              this.__zuzu_expanded.add(this.__zuzu_path_key(path));\n              this.__zuzu_mark_initial_expanded(children, path);\n            }\n          }\n        }\n        __zuzu_set_expanded_silent(path, expanded) {\n          const key = this.__zuzu_path_key(path);\n          if (expanded) {\n            this.__zuzu_expanded.add(key);\n          } else {\n            this.__zuzu_expanded.delete(key);\n          }\n        }\n      };\n      function _nativeDialogue(name2) {\n        return function nativeDialogue(first, ...rest) {\n          if (runtimePolicy2.gui && typeof runtimePolicy2.gui[name2] === "function") {\n            return runtimePolicy2.gui[name2](first, ...rest);\n          }\n          return null;\n        };\n      }\n      function _tagGuiType(klass, names) {\n        Object.defineProperty(klass.prototype, "__zuzu_gui_type_name", {\n          value: names[0],\n          enumerable: false,\n          configurable: false\n        });\n        Object.defineProperty(klass.prototype, "__zuzu_type_names", {\n          value: names,\n          enumerable: false,\n          configurable: false\n        });\n      }\n      for (const [klass, names] of [\n        [Widget, ["Widget"]],\n        [Window, ["Window", "Widget"]],\n        [VBox, ["VBox", "Widget"]],\n        [HBox, ["HBox", "Widget"]],\n        [Frame, ["Frame", "Widget"]],\n        [Label, ["Label", "Widget"]],\n        [Text, ["Text", "Widget"]],\n        [RichText, ["RichText", "Widget"]],\n        [Image, ["Image", "Widget"]],\n        [Input, ["Input", "Widget"]],\n        [DatePicker, ["DatePicker", "Widget"]],\n        [Checkbox, ["Checkbox", "Widget"]],\n        [Radio, ["Radio", "Checkbox", "Widget"]],\n        [RadioGroup, ["RadioGroup", "Widget"]],\n        [Select, ["Select", "Widget"]],\n        [Menu, ["Menu", "Widget"]],\n        [MenuItem, ["MenuItem", "Widget"]],\n        [Button, ["Button", "Widget"]],\n        [Separator, ["Separator", "Widget"]],\n        [Slider, ["Slider", "Widget"]],\n        [Progress, ["Progress", "Widget"]],\n        [Tabs, ["Tabs", "Widget"]],\n        [Tab, ["Tab", "Widget"]],\n        [ListView, ["ListView", "Widget"]],\n        [TreeView, ["TreeView", "Widget"]]\n      ]) {\n        _tagGuiType(klass, names);\n      }\n      module2.exports = {\n        Widget,\n        Window,\n        VBox,\n        HBox,\n        Frame,\n        Label,\n        Text,\n        RichText,\n        Image,\n        Input,\n        DatePicker,\n        Checkbox,\n        Radio,\n        RadioGroup,\n        Select,\n        Menu,\n        MenuItem,\n        Button,\n        Separator,\n        Slider,\n        Progress,\n        Tabs,\n        Tab,\n        ListView,\n        TreeView,\n        Event,\n        ListenerToken,\n        meta,\n        native_file_open: _nativeDialogue("fileOpen"),\n        native_file_save: _nativeDialogue("fileSave"),\n        native_directory_open: _nativeDialogue("directoryOpen"),\n        native_directory_save: _nativeDialogue("directorySave"),\n        native_alert: _nativeDialogue("alert"),\n        native_confirm: _nativeDialogue("confirm"),\n        native_prompt: _nativeDialogue("prompt"),\n        native_colour_picker: _nativeDialogue("colourPicker"),\n        __zuzu_set_runtime_policy(policy = {}) {\n          runtimePolicy2 = {\n            ...runtimePolicy2,\n            ...policy\n          };\n          meta.backend = runtimePolicy2.host_name === "browser" ? "browser-dom" : "electron-dom";\n        }\n      };\n    }\n  });\n\n  // modules/std/tui.js\n  var require_tui = __commonJS({\n    "modules/std/tui.js"(exports2, module2) {\n      "use strict";\n      var stdinBuffer = null;\n      var denyFs = false;\n      function hasProcess() {\n        return typeof process !== "undefined" && process;\n      }\n      function nodeRequire2(name2) {\n        if (typeof __require !== "function") {\n          return null;\n        }\n        try {\n          return __require(name2);\n        } catch (_err) {\n          return null;\n        }\n      }\n      function ansi_esc() {\n        return "\\x1B";\n      }\n      function supports_ansi() {\n        if (!hasProcess() || process.env.NO_COLOR) {\n          return 0;\n        }\n        if (!process.stdout || !process.stdout.isTTY) {\n          return 0;\n        }\n        if (process.platform === "win32") {\n          return process.env.ANSICON || process.env.WT_SESSION || process.env.ConEmuANSI || process.env.TERM_PROGRAM ? 1 : 0;\n        }\n        const term = process.env.TERM || "";\n        return term && term !== "dumb" ? 1 : 0;\n      }\n      function ansiCode(colour) {\n        switch (String(colour || "").toLowerCase()) {\n          case "black":\n            return 30;\n          case "red":\n            return 31;\n          case "green":\n            return 32;\n          case "yellow":\n            return 33;\n          case "blue":\n            return 34;\n          case "magenta":\n            return 35;\n          case "cyan":\n            return 36;\n          case "white":\n            return 37;\n          default:\n            return null;\n        }\n      }\n      function colour_text(text, colour) {\n        const value = text == null ? "" : String(text);\n        const code = ansiCode(colour);\n        if (!code || !supports_ansi()) {\n          return value;\n        }\n        return `${ansi_esc()}[${code}m${value}${ansi_esc()}[0m`;\n      }\n      function output(text) {\n        if (hasProcess() && process.stdout && typeof process.stdout.write === "function") {\n          process.stdout.write(String(text));\n          return;\n        }\n        if (typeof console !== "undefined" && typeof console.log === "function") {\n          console.log(String(text));\n        }\n      }\n      function write(text, colour) {\n        output(colour_text(text, colour));\n        return null;\n      }\n      function write_line(text, colour) {\n        output(`${colour_text(text, colour)}\n`);\n        return null;\n      }\n      function readStdinLine() {\n        const fs = nodeRequire2("node:fs") || nodeRequire2("fs");\n        if (!fs) {\n          return null;\n        }\n        if (stdinBuffer == null) {\n          try {\n            stdinBuffer = fs.readFileSync(0, "utf8");\n          } catch (_err) {\n            stdinBuffer = "";\n          }\n        }\n        if (stdinBuffer.length === 0) {\n          return null;\n        }\n        const match = /^([^\\n\\r]*)(?:\\r?\\n|\\r)?/.exec(stdinBuffer);\n        const line = match ? match[1] : stdinBuffer;\n        stdinBuffer = stdinBuffer.slice(match ? match[0].length : stdinBuffer.length);\n        return line;\n      }\n      function readline(prompt = "", defaultValue = "", _completionCallback = null) {\n        if (_completionCallback != null && typeof _completionCallback !== "function") {\n          throw new Error("readline completion must be Function or null");\n        }\n        output(prompt == null ? "" : String(prompt));\n        const line = readStdinLine();\n        if (line == null || line === "") {\n          return defaultValue == null ? "" : String(defaultValue);\n        }\n        return line;\n      }\n      function readline_supports_completion() {\n        return 0;\n      }\n      function pathCompletions(text, directoryOnly) {\n        if (denyFs) {\n          return [];\n        }\n        const fs = nodeRequire2("node:fs") || nodeRequire2("fs");\n        const path = nodeRequire2("node:path") || nodeRequire2("path");\n        if (!fs || !path) {\n          return [];\n        }\n        const raw = text == null ? "" : String(text);\n        const sepMatch = /[/\\\\]$/u.test(raw);\n        const dir = sepMatch ? raw : path.dirname(raw || ".");\n        const base = sepMatch ? "" : path.basename(raw);\n        const searchDir = dir && dir !== "." ? dir : ".";\n        const visibleDir = dir && dir !== "." ? dir : "";\n        let entries;\n        try {\n          entries = fs.readdirSync(searchDir, { withFileTypes: true });\n        } catch (_err) {\n          return [];\n        }\n        return entries.filter((entry) => entry.name.startsWith(base)).filter((entry) => !directoryOnly || entry.isDirectory()).map((entry) => {\n          const prefix = visibleDir ? `${visibleDir}${path.sep}` : "";\n          return `${prefix}${entry.name}${entry.isDirectory() ? path.sep : ""}`;\n        }).sort();\n      }\n      function filename_completions(text) {\n        return pathCompletions(text, false);\n      }\n      function directory_completions(text) {\n        return pathCompletions(text, true);\n      }\n      var api = {\n        ansi_esc,\n        colour_text,\n        directory_completions,\n        filename_completions,\n        readline,\n        readline_supports_completion,\n        supports_ansi,\n        write,\n        write_line\n      };\n      Object.defineProperty(api, "__zuzu_set_runtime_policy", {\n        value(policy = {}) {\n          denyFs = !!policy.deny_fs;\n        },\n        enumerable: false\n      });\n      module2.exports = api;\n    }\n  });\n\n  // modules/std/internals.js\n  var require_internals = __commonJS({\n    "modules/std/internals.js"(exports2, module2) {\n      "use strict";\n      var { getCompiledSource } = require_execution_metadata();\n      var taskRuntime2 = require_task();\n      var frameProps = /* @__PURE__ */ new Map();\n      var refIds = /* @__PURE__ */ new WeakMap();\n      var scopeTrees = /* @__PURE__ */ new Map();\n      var ZUZU_SKIP_BUILD = /* @__PURE__ */ Symbol.for("zuzu.skip_build");\n      var refSeq = 1;\n      var nodeFs;\n      var nodeFsLoaded = false;\n      var runtimePolicy2 = {\n        load_module: null,\n        builtin_class: null,\n        to_String: null,\n        to_Number: null,\n        to_Boolean: null,\n        to_Regexp: null,\n        to_Regexp_with_flags: null\n      };\n      function setRuntimePolicy2(policy = {}) {\n        runtimePolicy2 = {\n          ...runtimePolicy2,\n          ...policy\n        };\n      }\n      function _thisModuleFilename() {\n        return typeof __filename === "string" ? __filename : null;\n      }\n      function _nodeFs() {\n        if (nodeFsLoaded) {\n          return nodeFs;\n        }\n        nodeFsLoaded = true;\n        if (typeof __require !== "function") {\n          nodeFs = null;\n          return nodeFs;\n        }\n        try {\n          nodeFs = __require("node:fs");\n        } catch (_err) {\n          nodeFs = null;\n        }\n        return nodeFs;\n      }\n      function parseUserFrames() {\n        const lines = String(new Error().stack || "").split("\\n").slice(1);\n        const frames = [];\n        for (const line of lines) {\n          const trimmed = line.trim();\n          let match = trimmed.match(/^at\\s+(.*?)\\s+\\((.+):(\\d+):(\\d+)\\)$/);\n          if (!match) {\n            match = trimmed.match(/^at\\s+(.+):(\\d+):(\\d+)$/);\n            if (match) {\n              match = [match[0], "", match[1], match[2], match[3]];\n            }\n          }\n          if (!match) {\n            continue;\n          }\n          const file = match[2];\n          if (file.includes("<anonymous>") || file.startsWith("eval at ")) {\n            continue;\n          }\n          const thisFile = _thisModuleFilename();\n          if (thisFile != null && file === thisFile || /[\\\\/]extras[\\\\/]zuzu-js[\\\\/]lib[\\\\/]runtime\\.js$/.test(file) || /[\\\\/]zuzu-js[\\\\/]lib[\\\\/]runtime\\.js$/.test(file) || /[\\\\/]zuzu-browser\\.js$/.test(file) || file.startsWith("node:") || file === "[stdin]") {\n            continue;\n          }\n          frames.push({\n            func: match[1] || "",\n            file,\n            line: Number(match[3]),\n            col: Number(match[4])\n          });\n        }\n        return frames;\n      }\n      function loadScopeTree(file) {\n        if (scopeTrees.has(file)) {\n          return scopeTrees.get(file);\n        }\n        let source = "";\n        const compiled = getCompiledSource(file);\n        if (compiled != null) {\n          source = compiled;\n        } else try {\n          const fs = _nodeFs();\n          if (!fs) {\n            throw new Error("fs unavailable");\n          }\n          source = fs.readFileSync(file, "utf8");\n        } catch (_err) {\n          const fallback = {\n            nodes: [{ id: 0, parent: null, startLine: 1, endLine: Number.MAX_SAFE_INTEGER }]\n          };\n          scopeTrees.set(file, fallback);\n          return fallback;\n        }\n        const nodes = [\n          { id: 0, parent: null, startLine: 1, endLine: Number.MAX_SAFE_INTEGER }\n        ];\n        const stack = [0];\n        let line = 1;\n        let mode = "code";\n        let quote = "";\n        let escaped = false;\n        let atLineStart = true;\n        let inPod = false;\n        for (let i = 0; i < source.length; i++) {\n          const ch = source[i];\n          const next = source[i + 1] || "";\n          if (ch === "\\n") {\n            line++;\n            atLineStart = true;\n            if (mode === "line-comment") {\n              mode = "code";\n            }\n            continue;\n          }\n          if (inPod) {\n            if (atLineStart && ch === "=") {\n              const end = source.indexOf("\\n", i);\n              const rest = source.slice(i, end === -1 ? source.length : end);\n              if (/^=cut\\b/.test(rest)) {\n                inPod = false;\n              }\n            }\n            atLineStart = false;\n            continue;\n          }\n          if (atLineStart && ch === "=") {\n            const end = source.indexOf("\\n", i);\n            const rest = source.slice(i, end === -1 ? source.length : end);\n            if (/^=\\w+/.test(rest) && !/^=cut\\b/.test(rest)) {\n              inPod = true;\n              atLineStart = false;\n              continue;\n            }\n          }\n          atLineStart = false;\n          if (mode === "line-comment") {\n            continue;\n          }\n          if (mode === "block-comment") {\n            if (ch === "*" && next === "/") {\n              mode = "code";\n              i++;\n            }\n            continue;\n          }\n          if (mode === "string") {\n            if (escaped) {\n              escaped = false;\n              continue;\n            }\n            if (ch === "\\\\") {\n              escaped = true;\n              continue;\n            }\n            if (ch === quote) {\n              mode = "code";\n            }\n            continue;\n          }\n          if (ch === "/" && next === "/") {\n            mode = "line-comment";\n            i++;\n            continue;\n          }\n          if (ch === "/" && next === "*") {\n            mode = "block-comment";\n            i++;\n            continue;\n          }\n          if (ch === \'"\' || ch === "\'" || ch === "`") {\n            mode = "string";\n            quote = ch;\n            escaped = false;\n            continue;\n          }\n          if (ch === "{") {\n            const id = nodes.length;\n            nodes.push({\n              id,\n              parent: stack[stack.length - 1],\n              startLine: line,\n              endLine: Number.MAX_SAFE_INTEGER\n            });\n            stack.push(id);\n            continue;\n          }\n          if (ch === "}" && stack.length > 1) {\n            const id = stack.pop();\n            nodes[id].endLine = line;\n          }\n        }\n        const tree = { nodes };\n        scopeTrees.set(file, tree);\n        return tree;\n      }\n      function scopePathForLocation(file, line) {\n        const tree = loadScopeTree(file);\n        let current = 0;\n        let found = true;\n        while (found) {\n          found = false;\n          for (let i = tree.nodes.length - 1; i >= 1; i--) {\n            const node = tree.nodes[i];\n            if (node.parent !== current) {\n              continue;\n            }\n            if (node.startLine <= line && line <= node.endLine) {\n              current = node.id;\n              found = true;\n              break;\n            }\n          }\n        }\n        const path = [];\n        let nodeId = current;\n        while (nodeId != null) {\n          path.push(nodeId);\n          nodeId = tree.nodes[nodeId].parent;\n        }\n        return path;\n      }\n      function contextAtDepth(depth = 0) {\n        const frames = parseUserFrames();\n        const frame = frames[depth];\n        if (!frame) {\n          return null;\n        }\n        const isVirtualBrowserPath = runtimePolicy2.host_name === "browser";\n        const line = isVirtualBrowserPath ? frame.line - 2 : frame.line;\n        return {\n          activationKey: `file:${frame.file}`,\n          scopePath: scopePathForLocation(frame.file, Math.max(1, line))\n        };\n      }\n      function ensureFrame(activationKey, scopeId) {\n        const key = `${activationKey}#${scopeId}`;\n        if (!frameProps.has(key)) {\n          frameProps.set(key, /* @__PURE__ */ new Map());\n        }\n        return frameProps.get(key);\n      }\n      function getFrame(activationKey, scopeId) {\n        return frameProps.get(`${activationKey}#${scopeId}`);\n      }\n      function class_name(value) {\n        if (value == null || typeof value !== "object") {\n          return null;\n        }\n        return value.constructor && value.constructor.name ? value.constructor.name : null;\n      }\n      function classof(value) {\n        if (value == null) {\n          return null;\n        }\n        if (typeof value === "boolean" || typeof value === "number" || typeof value === "string") {\n          return null;\n        }\n        const builtinClass = typeof runtimePolicy2.builtin_class === "function" ? runtimePolicy2.builtin_class : () => null;\n        if (Array.isArray(value)) {\n          return builtinClass("Array") || value.constructor || null;\n        }\n        if (Object.prototype.toString.call(value) === "[object Set]") {\n          return builtinClass("Set") || value.constructor || null;\n        }\n        if (value && value.constructor) {\n          const ctor = value.constructor;\n          const name2 = ctor.__zuzu_class_name || ctor.name || "";\n          if (name2 === "Object") {\n            return builtinClass("Dict") || ctor;\n          }\n          if (name2 === "ZuzuBag") {\n            return builtinClass("Bag") || ctor;\n          }\n          return ctor;\n        }\n        if (typeof value === "function") {\n          const source = Function.prototype.toString.call(value);\n          if (/^\\s*class\\b/.test(source)) {\n            return builtinClass("Class") || Function;\n          }\n          return builtinClass("Function") || Function;\n        }\n        return null;\n      }\n      function object_slots(value) {\n        if (value == null || typeof value !== "object") {\n          return null;\n        }\n        const out = {};\n        for (const key of Object.keys(value)) {\n          if (!key.startsWith("_")) {\n            out[key] = value[key];\n          }\n        }\n        Object.defineProperty(\n          out,\n          "get",\n          {\n            value(key) {\n              const id = String(key);\n              return Object.prototype.hasOwnProperty.call(out, id) ? out[id] : null;\n            },\n            enumerable: false\n          }\n        );\n        Object.defineProperty(\n          out,\n          "keys",\n          {\n            value() {\n              return Object.keys(out);\n            },\n            enumerable: false\n          }\n        );\n        Object.defineProperty(\n          out,\n          "sorted_keys",\n          {\n            value() {\n              return Object.keys(out).sort();\n            },\n            enumerable: false\n          }\n        );\n        return out;\n      }\n      function ansi_esc() {\n        return "\\x1B";\n      }\n      function ref_id(value) {\n        if (value == null || typeof value !== "object" && typeof value !== "function") {\n          return null;\n        }\n        if (!refIds.has(value)) {\n          refIds.set(value, `ref:${refSeq++}`);\n        }\n        return refIds.get(value);\n      }\n      function make_instance(klass, slots = null) {\n        if (typeof klass !== "function" || typeof klass.__zuzu_class_name !== "string") {\n          throw new Error("make_instance expects a user class");\n        }\n        if (slots == null) {\n          return new klass(ZUZU_SKIP_BUILD);\n        }\n        if (typeof slots !== "object" || Array.isArray(slots)) {\n          throw new Error("make_instance slot values must be Dict");\n        }\n        return new klass(ZUZU_SKIP_BUILD, slots);\n      }\n      function currentUserFile() {\n        const frame = parseUserFrames()[0];\n        return frame && frame.file ? frame.file : null;\n      }\n      function moduleExportKeys(loaded) {\n        return Reflect.ownKeys(Object(loaded)).filter((key) => typeof key === "string").filter((key) => !key.startsWith("__zuzu_"));\n      }\n      function load_module(moduleName, symbolName = null) {\n        if (arguments.length < 1 || arguments.length > 2) {\n          throw new Error("load_module expects 1 to 2 arguments");\n        }\n        if (typeof moduleName !== "string") {\n          throw new Error("load_module module must be String");\n        }\n        if (symbolName != null && typeof symbolName !== "string") {\n          throw new Error("load_module symbol must be String");\n        }\n        if (typeof runtimePolicy2.load_module !== "function") {\n          throw new Error("load_module is unavailable in this runtime");\n        }\n        const loaded = runtimePolicy2.load_module(moduleName, currentUserFile());\n        if (symbolName != null) {\n          if (!Object.prototype.hasOwnProperty.call(Object(loaded), symbolName)) {\n            throw new Error(`Module \'${moduleName}\' has no export \'${symbolName}\'`);\n          }\n          return loaded[symbolName];\n        }\n        const out = {};\n        for (const key of moduleExportKeys(loaded)) {\n          out[key] = loaded[key];\n        }\n        return out;\n      }\n      function requirePolicyFunction(name2) {\n        const fn2 = runtimePolicy2[name2];\n        if (typeof fn2 !== "function") {\n          throw new Error(`${name2} is unavailable in this runtime`);\n        }\n        return fn2;\n      }\n      function to_String(value) {\n        return requirePolicyFunction("to_String")(value);\n      }\n      function to_Number(value) {\n        return requirePolicyFunction("to_Number")(value);\n      }\n      function to_Boolean(value) {\n        return requirePolicyFunction("to_Boolean")(value);\n      }\n      function to_Regexp(value) {\n        return requirePolicyFunction("to_Regexp")(value);\n      }\n      function to_Regexp_with_flags(value, flags) {\n        return requirePolicyFunction("to_Regexp_with_flags")(value, flags);\n      }\n      function validateKey(key) {\n        if (typeof key !== "string") {\n          throw new Error("getprop|setprop key must be String");\n        }\n      }\n      function setprop(key, value) {\n        validateKey(key);\n        const ctx = contextAtDepth(0);\n        if (!ctx) {\n          return value;\n        }\n        ensureFrame(ctx.activationKey, ctx.scopePath[0]).set(key, value);\n        return value;\n      }\n      function getprop(key) {\n        validateKey(key);\n        const ctx = contextAtDepth(0);\n        if (!ctx) {\n          return null;\n        }\n        for (const scopeId of ctx.scopePath) {\n          const frame = getFrame(ctx.activationKey, scopeId);\n          if (frame && frame.has(key)) {\n            return frame.get(key);\n          }\n        }\n        return null;\n      }\n      function setupperprop(level, key, value) {\n        validateKey(key);\n        const ctx = contextAtDepth(Number(level ?? 0));\n        if (!ctx) {\n          return value;\n        }\n        ensureFrame(ctx.activationKey, ctx.scopePath[0]).set(key, value);\n        return value;\n      }\n      function getupperprop(level, key) {\n        validateKey(key);\n        const ctx = contextAtDepth(Number(level ?? 0));\n        if (!ctx) {\n          return null;\n        }\n        for (const scopeId of ctx.scopePath) {\n          const frame = getFrame(ctx.activationKey, scopeId);\n          if (frame && frame.has(key)) {\n            return frame.get(key);\n          }\n        }\n        return null;\n      }\n      var api = {\n        active_task_count: taskRuntime2.activeCount,\n        ansi_esc,\n        class_name,\n        classof,\n        clear_task_trace: taskRuntime2.clearTrace,\n        getprop,\n        getupperprop,\n        load_module,\n        make_instance,\n        object_slots,\n        ref_id,\n        setprop,\n        setupperprop,\n        shutdown_tasks: taskRuntime2.shutdown,\n        task_trace: taskRuntime2.taskTrace,\n        to_Boolean,\n        to_Number,\n        to_Regexp,\n        to_Regexp_with_flags,\n        to_String\n      };\n      Object.defineProperty(api, "__zuzu_set_runtime_policy", {\n        value: setRuntimePolicy2,\n        enumerable: false,\n        configurable: true,\n        writable: true\n      });\n      module2.exports = api;\n    }\n  });\n\n  // node_modules/@std-uritemplate/std-uritemplate/dist/index.cjs\n  var require_dist = __commonJS({\n    "node_modules/@std-uritemplate/std-uritemplate/dist/index.cjs"(exports2) {\n      "use strict";\n      var StdUriTemplate = class _StdUriTemplate {\n        static expand(template, substitutions) {\n          return _StdUriTemplate.expandImpl(template, substitutions);\n        }\n        static validateLiteral(c, col) {\n          switch (c) {\n            case "+":\n            case "#":\n            case "/":\n            case ";":\n            case "?":\n            case "&":\n            case " ":\n            case "!":\n            case "=":\n            case "$":\n            case "|":\n            case "*":\n            case ":":\n            case "~":\n            case "-":\n              throw new Error(`Illegal character identified in the token at col: ${col}`);\n          }\n        }\n        static getMaxChar(buffer, col) {\n          if (!buffer) {\n            return -1;\n          } else {\n            const value = buffer.join("");\n            if (value.length === 0) {\n              return -1;\n            } else {\n              try {\n                return parseInt(value, 10);\n              } catch (e) {\n                throw new Error(`Cannot parse max chars at col: ${col}`);\n              }\n            }\n          }\n        }\n        static getOperator(c, token, col) {\n          switch (c) {\n            case "+":\n              return 1;\n            case "#":\n              return 2;\n            case ".":\n              return 3;\n            case "/":\n              return 4;\n            case ";":\n              return 5;\n            case "?":\n              return 6;\n            case "&":\n              return 7;\n            default:\n              _StdUriTemplate.validateLiteral(c, col);\n              token.push(c);\n              return 0;\n          }\n        }\n        static expandImpl(str, substitutions) {\n          const result = [];\n          let token = null;\n          let operator = null;\n          let composite = false;\n          let maxCharBuffer = null;\n          let firstToken = true;\n          for (let i = 0; i < str.length; i++) {\n            const character = str.charAt(i);\n            switch (character) {\n              case "{":\n                token = [];\n                firstToken = true;\n                break;\n              case "}":\n                if (token !== null) {\n                  const expanded = _StdUriTemplate.expandToken(\n                    operator,\n                    token.join(""),\n                    composite,\n                    _StdUriTemplate.getMaxChar(maxCharBuffer, i),\n                    firstToken,\n                    substitutions,\n                    result,\n                    i\n                  );\n                  if (expanded && firstToken) {\n                    firstToken = false;\n                  }\n                  token = null;\n                  operator = null;\n                  composite = false;\n                  maxCharBuffer = null;\n                } else {\n                  throw new Error(`Failed to expand token, invalid at col: ${i}`);\n                }\n                break;\n              case ",":\n                if (token !== null) {\n                  const expanded = _StdUriTemplate.expandToken(\n                    operator,\n                    token.join(""),\n                    composite,\n                    _StdUriTemplate.getMaxChar(maxCharBuffer, i),\n                    firstToken,\n                    substitutions,\n                    result,\n                    i\n                  );\n                  if (expanded && firstToken) {\n                    firstToken = false;\n                  }\n                  token = [];\n                  composite = false;\n                  maxCharBuffer = null;\n                  break;\n                }\n              // Intentional fall-through for commas outside the {}\n              default:\n                if (token !== null) {\n                  if (operator === null) {\n                    operator = _StdUriTemplate.getOperator(character, token, i);\n                  } else if (maxCharBuffer !== null) {\n                    if (character.match(/^\\d$/)) {\n                      maxCharBuffer.push(character);\n                    } else {\n                      throw new Error(`Illegal character identified in the token at col: ${i}`);\n                    }\n                  } else {\n                    if (character === ":") {\n                      maxCharBuffer = [];\n                    } else if (character === "*") {\n                      composite = true;\n                    } else {\n                      _StdUriTemplate.validateLiteral(character, i);\n                      token.push(character);\n                    }\n                  }\n                } else {\n                  result.push(character);\n                }\n                break;\n            }\n          }\n          if (token === null) {\n            return result.join("");\n          } else {\n            throw new Error("Unterminated token");\n          }\n        }\n        static addPrefix(op, result) {\n          switch (op) {\n            case 2:\n              result.push("#");\n              break;\n            case 3:\n              result.push(".");\n              break;\n            case 4:\n              result.push("/");\n              break;\n            case 5:\n              result.push(";");\n              break;\n            case 6:\n              result.push("?");\n              break;\n            case 7:\n              result.push("&");\n              break;\n            default:\n              return;\n          }\n        }\n        static addSeparator(op, result) {\n          switch (op) {\n            case 3:\n              result.push(".");\n              break;\n            case 4:\n              result.push("/");\n              break;\n            case 5:\n              result.push(";");\n              break;\n            case 6:\n            case 7:\n              result.push("&");\n              break;\n            default:\n              result.push(",");\n              return;\n          }\n        }\n        static addValue(op, token, value, result, maxChar) {\n          switch (op) {\n            case 1:\n            case 2:\n              _StdUriTemplate.addExpandedValue(null, value, result, maxChar, false);\n              break;\n            case 6:\n            case 7:\n              result.push(`${token}=`);\n              _StdUriTemplate.addExpandedValue(null, value, result, maxChar, true);\n              break;\n            case 5:\n              result.push(token);\n              _StdUriTemplate.addExpandedValue("=", value, result, maxChar, true);\n              break;\n            case 3:\n            case 4:\n            case 0:\n              _StdUriTemplate.addExpandedValue(null, value, result, maxChar, true);\n              break;\n          }\n        }\n        static addValueElement(op, token, value, result, maxChar) {\n          switch (op) {\n            case 1:\n            case 2:\n              _StdUriTemplate.addExpandedValue(null, value, result, maxChar, false);\n              break;\n            case 6:\n            case 7:\n            case 5:\n            case 3:\n            case 4:\n            case 0:\n              _StdUriTemplate.addExpandedValue(null, value, result, maxChar, true);\n              break;\n          }\n        }\n        static isSurrogate(cp) {\n          const codeUnit = cp.charCodeAt(0);\n          return codeUnit >= 55296 && codeUnit <= 56319;\n        }\n        static isIprivate(cp) {\n          return 57344 <= cp.charCodeAt(0) && cp.charCodeAt(0) <= 63743;\n        }\n        static isUcschar(cp) {\n          const codePoint = cp.codePointAt(0) || 0;\n          return 160 <= codePoint && codePoint <= 55295 || 63744 <= codePoint && codePoint <= 64975 || 65008 <= codePoint && codePoint <= 65519;\n        }\n        static addExpandedValue(prefix, value, result, maxChar, replaceReserved) {\n          const stringValue = _StdUriTemplate.convertNativeTypes(value);\n          const max = maxChar !== -1 ? Math.min(maxChar, stringValue.length) : stringValue.length;\n          let reservedBuffer = void 0;\n          if (max > 0 && prefix != null) {\n            result.push(prefix);\n          }\n          for (let i = 0; i < max; i++) {\n            const character = stringValue.charAt(i);\n            if (character === "%" && !replaceReserved) {\n              reservedBuffer = [];\n            }\n            let toAppend = character;\n            if (_StdUriTemplate.isSurrogate(character)) {\n              toAppend = encodeURIComponent(stringValue.charAt(i) + stringValue.charAt(i + 1));\n              i++;\n            } else if (replaceReserved || _StdUriTemplate.isUcschar(character) || _StdUriTemplate.isIprivate(character)) {\n              if (character === "!") {\n                toAppend = "%21";\n              } else {\n                toAppend = encodeURIComponent(toAppend);\n              }\n            }\n            if (reservedBuffer) {\n              reservedBuffer.push(toAppend);\n              if (reservedBuffer.length === 3) {\n                let isEncoded = false;\n                try {\n                  const reserved = reservedBuffer.join("");\n                  const decoded = decodeURIComponent(reservedBuffer.join(""));\n                  isEncoded = reserved !== decoded;\n                } catch (e) {\n                }\n                if (isEncoded) {\n                  result.push(reservedBuffer.join(""));\n                } else {\n                  result.push("%25");\n                  result.push(reservedBuffer.slice(1).join(""));\n                }\n                reservedBuffer = void 0;\n              }\n            } else {\n              if (character === " ") {\n                result.push("%20");\n              } else if (character === "%") {\n                result.push("%25");\n              } else {\n                result.push(toAppend);\n              }\n            }\n          }\n          if (reservedBuffer) {\n            result.push("%25");\n            result.push(reservedBuffer.slice(1).join(""));\n          }\n        }\n        static isList(value) {\n          return Array.isArray(value) || value instanceof Set;\n        }\n        static isMap(value) {\n          return value instanceof Map || typeof value === "object";\n        }\n        static getSubstitutionType(value, col) {\n          if (value === void 0 || value === null) {\n            return 0;\n          } else if (_StdUriTemplate.isNativeType(value)) {\n            return 1;\n          } else if (_StdUriTemplate.isList(value)) {\n            return 2;\n          } else if (_StdUriTemplate.isMap(value)) {\n            return 3;\n          } else {\n            throw new Error(`Illegal class passed as substitution, found ${typeof value} at col: ${col}`);\n          }\n        }\n        static isEmpty(substType, value) {\n          if (value === void 0 || value === null) {\n            return true;\n          } else {\n            switch (substType) {\n              case 1:\n                return false;\n              case 2:\n                return value.length === 0;\n              case 3:\n                return Object.keys(value).length === 0;\n              default:\n                return true;\n            }\n          }\n        }\n        static isNativeType(value) {\n          return typeof value === "string" || typeof value === "number" || typeof value === "boolean";\n        }\n        static convertNativeTypes(value) {\n          if (typeof value === "string") {\n            return value;\n          } else if (typeof value === "number" || typeof value === "boolean") {\n            return value.toString();\n          } else {\n            throw new Error(`Illegal class passed as substitution, found ${typeof value}`);\n          }\n        }\n        static expandToken(operator, token, composite, maxChar, firstToken, substitutions, result, col) {\n          if (token.length === 0) {\n            throw new Error(`Found an empty token at col: ${col}`);\n          }\n          const value = substitutions[token];\n          const substType = _StdUriTemplate.getSubstitutionType(value, col);\n          if (substType === 0 || _StdUriTemplate.isEmpty(substType, value)) {\n            return false;\n          }\n          if (firstToken) {\n            _StdUriTemplate.addPrefix(operator, result);\n          } else {\n            _StdUriTemplate.addSeparator(operator, result);\n          }\n          switch (substType) {\n            case 1:\n              _StdUriTemplate.addStringValue(operator, token, value, result, maxChar);\n              break;\n            case 2:\n              _StdUriTemplate.addListValue(operator, token, value, result, maxChar, composite);\n              break;\n            case 3:\n              _StdUriTemplate.addMapValue(operator, token, value, result, maxChar, composite);\n              break;\n          }\n          return true;\n        }\n        static addStringValue(operator, token, value, result, maxChar) {\n          _StdUriTemplate.addValue(operator, token, value, result, maxChar);\n        }\n        static addListValue(operator, token, value, result, maxChar, composite) {\n          let first = true;\n          for (const v of value) {\n            if (first) {\n              _StdUriTemplate.addValue(operator, token, v, result, maxChar);\n              first = false;\n            } else {\n              if (composite) {\n                _StdUriTemplate.addSeparator(operator, result);\n                _StdUriTemplate.addValue(operator, token, v, result, maxChar);\n              } else {\n                result.push(",");\n                _StdUriTemplate.addValueElement(operator, token, v, result, maxChar);\n              }\n            }\n          }\n        }\n        static addMapValue(operator, token, value, result, maxChar, composite) {\n          let first = true;\n          if (maxChar !== -1) {\n            throw new Error("Value trimming is not allowed on Maps");\n          }\n          for (const key in value) {\n            const v = value[key];\n            if (composite) {\n              if (!first) {\n                _StdUriTemplate.addSeparator(operator, result);\n              }\n              _StdUriTemplate.addValueElement(operator, token, key, result, maxChar);\n              result.push("=");\n            } else {\n              if (first) {\n                _StdUriTemplate.addValue(operator, token, key, result, maxChar);\n              } else {\n                result.push(",");\n                _StdUriTemplate.addValueElement(operator, token, key, result, maxChar);\n              }\n              result.push(",");\n            }\n            _StdUriTemplate.addValueElement(operator, token, v, result, maxChar);\n            first = false;\n          }\n        }\n      };\n      exports2.StdUriTemplate = StdUriTemplate;\n    }\n  });\n\n  // modules/std/net/url.js\n  var require_url = __commonJS({\n    "modules/std/net/url.js"(exports2, module2) {\n      "use strict";\n      function _str(value, fallback = "") {\n        if (value == null) {\n          return fallback;\n        }\n        return String(value);\n      }\n      function _dict(source = {}) {\n        const out = { ...source };\n        Object.defineProperties(out, {\n          has: {\n            value(key) {\n              return Object.prototype.hasOwnProperty.call(out, String(key)) ? 1 : 0;\n            },\n            enumerable: false\n          },\n          exists: {\n            value(key) {\n              return out.has(key);\n            },\n            enumerable: false\n          },\n          get: {\n            value(key, fallback = null) {\n              return out.has(key) ? out[String(key)] : fallback;\n            },\n            enumerable: false\n          }\n        });\n        return out;\n      }\n      function escape(value) {\n        return encodeURIComponent(_str(value));\n      }\n      function unescape(value) {\n        return decodeURIComponent(_str(value));\n      }\n      function parse(value) {\n        const urlText = _str(value);\n        const parsed = new URL(urlText, "http://localhost");\n        const out = _dict({\n          url: parsed.href,\n          scheme: parsed.protocol.replace(/:$/u, "") || null,\n          authority: parsed.host || null,\n          userinfo: null,\n          host: parsed.hostname || null,\n          port: parsed.port || null,\n          path: parsed.pathname || "",\n          query: parsed.search.replace(/^\\?/u, "") || null,\n          fragment: parsed.hash.replace(/^#/u, "") || null,\n          query_params: _dict({})\n        });\n        if (parsed.username || parsed.password) {\n          out.userinfo = parsed.username;\n          if (parsed.password) {\n            out.userinfo += `:${parsed.password}`;\n          }\n        }\n        for (const [key, item] of parsed.searchParams.entries()) {\n          out.query_params[key] = item;\n        }\n        return out;\n      }\n      var { StdUriTemplate } = require_dist();\n      function _templateValue(value) {\n        if (value == null) {\n          return null;\n        }\n        if (Array.isArray(value)) {\n          return value.map((item) => _str(item));\n        }\n        if (typeof value === "boolean") {\n          return value ? "true" : "false";\n        }\n        if (typeof value === "object" && !(value.bytes instanceof Uint8Array)) {\n          const out = {};\n          for (const key of Object.keys(value).sort()) {\n            out[key] = _str(value[key]);\n          }\n          return out;\n        }\n        return _str(value);\n      }\n      function fill_template(template, values) {\n        const source = _str(template);\n        const data = {};\n        if (values && typeof values === "object" && !Array.isArray(values)) {\n          for (const key of Object.keys(values)) {\n            const converted = _templateValue(values[key]);\n            if (converted != null) {\n              data[key] = converted;\n            }\n          }\n        }\n        try {\n          return StdUriTemplate.expand(source, data);\n        } catch (err) {\n          throw new Error(`Exception: invalid URL template: ${source}`);\n        }\n      }\n      module2.exports = {\n        escape,\n        unescape,\n        parse,\n        fill_template\n      };\n    }\n  });\n\n  // ../../../../../tmp/zuzu-browser-build.UGYrnC/browser-stdlib.generated.js\n  var require_browser_stdlib_generated = __commonJS({\n    "../../../../../tmp/zuzu-browser-build.UGYrnC/browser-stdlib.generated.js"(exports2, module2) {\n      "use strict";\n      function createBrowserStdlib2() {\n        const jsModules = /* @__PURE__ */ Object.create(null);\n        jsModules["/modules/javascript.js"] = require_javascript();\n        jsModules["/modules/std/string.js"] = require_string();\n        jsModules["/modules/std/string/base64.js"] = require_base64();\n        jsModules["/modules/std/string/encode.js"] = require_encode();\n        jsModules["/modules/std/time.js"] = require_time();\n        jsModules["/modules/std/marshal.js"] = require_marshal();\n        jsModules["/modules/std/task.js"] = require_task();\n        jsModules["/modules/std/worker.js"] = require_worker();\n        jsModules["/modules/std/secure.js"] = require_secure();\n        jsModules["/modules/std/data/json.js"] = require_json();\n        jsModules["/modules/std/data/yaml.js"] = require_yaml();\n        jsModules["/modules/std/data/csv.js"] = require_csv();\n        jsModules["/modules/std/data/xml.js"] = require_xml();\n        jsModules["/modules/std/digest/md5.js"] = require_md5();\n        jsModules["/modules/std/digest/sha.js"] = require_sha();\n        jsModules["/modules/std/net/http.js"] = require_http();\n        jsModules["/modules/std/math.js"] = require_math();\n        jsModules["/modules/std/math/bignum.js"] = require_bignum();\n        jsModules["/modules/std/eval.js"] = require_eval();\n        jsModules["/modules/std/gui/objects.js"] = require_objects();\n        jsModules["/modules/std/tui.js"] = require_tui();\n        jsModules["/modules/std/internals.js"] = require_internals();\n        jsModules["/modules/std/net/url.js"] = require_url();\n        const virtualFiles = /* @__PURE__ */ Object.create(null);\n        virtualFiles["/modules/std/colour.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/colour - Colour parsing helpers.\\n\\n=head1 SYNOPSIS\\n\\n  from std/colour import parse_colour;\\n\\n  say( parse_colour("red") );  # #ff0000\\n  say( parse_colour("#abc") ); # #aabbcc\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nC<parse_colour> accepts three- and six-digit hexadecimal colours and the\\nCSS3 extended colour keywords. It returns a lowercase six-digit\\nhexadecimal colour string.\\n\\n=head1 EXPORTS\\n\\n=head2 Functions\\n\\n=over\\n\\n=item C<< parse_colour(String x) >>\\n\\nParameters: C<x> is a CSS colour keyword or a three- or six-digit\\nhexadecimal colour string. Returns: C<String>. Returns the normalized\\nlowercase C<#rrggbb> colour string, or throws if C<x> is not recognised.\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/colour >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/string import trim;\\n\\nconst _COLOUR_KEYWORDS := {\\n	aliceblue: "#f0f8ff",\\n	antiquewhite: "#faebd7",\\n	aqua: "#00ffff",\\n	aquamarine: "#7fffd4",\\n	azure: "#f0ffff",\\n	beige: "#f5f5dc",\\n	bisque: "#ffe4c4",\\n	black: "#000000",\\n	blanchedalmond: "#ffebcd",\\n	blue: "#0000ff",\\n	blueviolet: "#8a2be2",\\n	brown: "#a52a2a",\\n	burlywood: "#deb887",\\n	cadetblue: "#5f9ea0",\\n	chartreuse: "#7fff00",\\n	chocolate: "#d2691e",\\n	coral: "#ff7f50",\\n	cornflowerblue: "#6495ed",\\n	cornsilk: "#fff8dc",\\n	crimson: "#dc143c",\\n	cyan: "#00ffff",\\n	darkblue: "#00008b",\\n	darkcyan: "#008b8b",\\n	darkgoldenrod: "#b8860b",\\n	darkgray: "#a9a9a9",\\n	darkgreen: "#006400",\\n	darkgrey: "#a9a9a9",\\n	darkkhaki: "#bdb76b",\\n	darkmagenta: "#8b008b",\\n	darkolivegreen: "#556b2f",\\n	darkorange: "#ff8c00",\\n	darkorchid: "#9932cc",\\n	darkred: "#8b0000",\\n	darksalmon: "#e9967a",\\n	darkseagreen: "#8fbc8f",\\n	darkslateblue: "#483d8b",\\n	darkslategray: "#2f4f4f",\\n	darkslategrey: "#2f4f4f",\\n	darkturquoise: "#00ced1",\\n	darkviolet: "#9400d3",\\n	deeppink: "#ff1493",\\n	deepskyblue: "#00bfff",\\n	dimgray: "#696969",\\n	dimgrey: "#696969",\\n	dodgerblue: "#1e90ff",\\n	firebrick: "#b22222",\\n	floralwhite: "#fffaf0",\\n	forestgreen: "#228b22",\\n	fuchsia: "#ff00ff",\\n	gainsboro: "#dcdcdc",\\n	ghostwhite: "#f8f8ff",\\n	gold: "#ffd700",\\n	goldenrod: "#daa520",\\n	gray: "#808080",\\n	green: "#008000",\\n	greenyellow: "#adff2f",\\n	grey: "#808080",\\n	honeydew: "#f0fff0",\\n	hotpink: "#ff69b4",\\n	indianred: "#cd5c5c",\\n	indigo: "#4b0082",\\n	ivory: "#fffff0",\\n	khaki: "#f0e68c",\\n	lavender: "#e6e6fa",\\n	lavenderblush: "#fff0f5",\\n	lawngreen: "#7cfc00",\\n	lemonchiffon: "#fffacd",\\n	lightblue: "#add8e6",\\n	lightcoral: "#f08080",\\n	lightcyan: "#e0ffff",\\n	lightgoldenrodyellow: "#fafad2",\\n	lightgray: "#d3d3d3",\\n	lightgreen: "#90ee90",\\n	lightgrey: "#d3d3d3",\\n	lightpink: "#ffb6c1",\\n	lightsalmon: "#ffa07a",\\n	lightseagreen: "#20b2aa",\\n	lightskyblue: "#87cefa",\\n	lightslategray: "#778899",\\n	lightslategrey: "#778899",\\n	lightsteelblue: "#b0c4de",\\n	lightyellow: "#ffffe0",\\n	lime: "#00ff00",\\n	limegreen: "#32cd32",\\n	linen: "#faf0e6",\\n	magenta: "#ff00ff",\\n	maroon: "#800000",\\n	mediumaquamarine: "#66cdaa",\\n	mediumblue: "#0000cd",\\n	mediumorchid: "#ba55d3",\\n	mediumpurple: "#9370db",\\n	mediumseagreen: "#3cb371",\\n	mediumslateblue: "#7b68ee",\\n	mediumspringgreen: "#00fa9a",\\n	mediumturquoise: "#48d1cc",\\n	mediumvioletred: "#c71585",\\n	midnightblue: "#191970",\\n	mintcream: "#f5fffa",\\n	mistyrose: "#ffe4e1",\\n	moccasin: "#ffe4b5",\\n	navajowhite: "#ffdead",\\n	navy: "#000080",\\n	oldlace: "#fdf5e6",\\n	olive: "#808000",\\n	olivedrab: "#6b8e23",\\n	orange: "#ffa500",\\n	orangered: "#ff4500",\\n	orchid: "#da70d6",\\n	palegoldenrod: "#eee8aa",\\n	palegreen: "#98fb98",\\n	paleturquoise: "#afeeee",\\n	palevioletred: "#db7093",\\n	papayawhip: "#ffefd5",\\n	peachpuff: "#ffdab9",\\n	peru: "#cd853f",\\n	pink: "#ffc0cb",\\n	plum: "#dda0dd",\\n	powderblue: "#b0e0e6",\\n	purple: "#800080",\\n	rebeccapurple: "#663399",\\n	red: "#ff0000",\\n	rosybrown: "#bc8f8f",\\n	royalblue: "#4169e1",\\n	saddlebrown: "#8b4513",\\n	salmon: "#fa8072",\\n	sandybrown: "#f4a460",\\n	seagreen: "#2e8b57",\\n	seashell: "#fff5ee",\\n	sienna: "#a0522d",\\n	silver: "#c0c0c0",\\n	skyblue: "#87ceeb",\\n	slateblue: "#6a5acd",\\n	slategray: "#708090",\\n	slategrey: "#708090",\\n	snow: "#fffafa",\\n	springgreen: "#00ff7f",\\n	steelblue: "#4682b4",\\n	tan: "#d2b48c",\\n	teal: "#008080",\\n	thistle: "#d8bfd8",\\n	tomato: "#ff6347",\\n	turquoise: "#40e0d0",\\n	violet: "#ee82ee",\\n	wheat: "#f5deb3",\\n	white: "#ffffff",\\n	whitesmoke: "#f5f5f5",\\n	yellow: "#ffff00",\\n	yellowgreen: "#9acd32",\\n};\\n\\nfunction parse_colour ( String x ) {\\n	let text := lc( trim(x) );\\n\\n	if ( text ~ /^#[0-9a-f]{6}$/ ) {\\n		return text;\\n	}\\n\\n	let short := text ~ /^#([0-9a-f])([0-9a-f])([0-9a-f])$/;\\n	if ( short ) {\\n		return "#"\\n			_ short[1] _ short[1]\\n			_ short[2] _ short[2]\\n			_ short[3] _ short[3];\\n	}\\n\\n	if ( _COLOUR_KEYWORDS.exists(text) ) {\\n		return _COLOUR_KEYWORDS.get(text);\\n	}\\n\\n	die `Invalid colour: ${x}`;\\n}\\n\';\n        virtualFiles["/modules/std/result.zzm"] = "=encoding utf8\\n\\n=head1 NAME\\n\\nstd/result - A simple Result object for explicit success and failure values.\\n\\n=head1 SYNOPSIS\\n\\n  from std/result import Result;\\n\\n  let r := Result.ok(42);\\n\\n  if ( r.is_ok() ) {\\n    say r.unwrap();\\n  }\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nC<Result> is a small, subclassable object modelled on a simplified version\\nof Rust\'s C<Result> concept. It is useful when a function, task, or worker\\nwants to return an explicit success or failure value without throwing an\\nexception.\\n\\nIt is a normal ZuzuScript class. Workers do not require C<Result>; any value\\nsupported by C<std/marshal> may be returned.\\n\\n=head1 EXPORTS\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<Result>\\n\\nContainer for either an ok value or an error value.\\n\\n=over\\n\\n=item C<< Result.ok(value) >>\\n\\nParameters: C<value> is any success value. Returns: C<Result>. Creates an\\nok result wrapping C<value>.\\n\\n=item C<< Result.err(error) >>\\n\\nParameters: C<error> is any error value. Returns: C<Result>. Creates an\\nerror result wrapping C<error>.\\n\\n=item C<< result.is_ok() >>\\n\\nParameters: none. Returns: C<Boolean>. Returns true when the result is an\\nok value.\\n\\n=item C<< result.is_err() >>\\n\\nParameters: none. Returns: C<Boolean>. Returns true when the result is an\\nerror value.\\n\\n=item C<< result.value() >>\\n\\nParameters: none. Returns: value. Returns the stored ok value, or\\nC<null> for an error result.\\n\\n=item C<< result.error() >>\\n\\nParameters: none. Returns: value. Returns the stored error value, or\\nC<null> for an ok result.\\n\\n=item C<< result.unwrap() >>\\n\\nParameters: none. Returns: value. Returns the ok value, or throws if the\\nresult is an error.\\n\\n=item C<< result.unwrap_err() >>\\n\\nParameters: none. Returns: value. Returns the error value, or throws if\\nthe result is ok.\\n\\n=back\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/result >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nclass Result {\\n	let Boolean _is_ok := true;\\n	let _value := null;\\n	let _error := null;\\n\\n	static method ok ( value ) {\\n		return new self(\\n			_is_ok: true,\\n			_value: value,\\n			_error: null,\\n		);\\n	}\\n\\n	static method err ( error ) {\\n		return new self(\\n			_is_ok: false,\\n			_value: null,\\n			_error: error,\\n		);\\n	}\\n\\n	method is_ok () {\\n		return _is_ok;\\n	}\\n\\n	method is_err () {\\n		return not _is_ok;\\n	}\\n\\n	method value () {\\n		return _value;\\n	}\\n\\n	method error () {\\n		return _error;\\n	}\\n\\n	method unwrap () {\\n		if ( _is_ok ) {\\n			return _value;\\n		}\\n\\n		die `called Result.unwrap() on an err value: ${_error}`;\\n	}\\n\\n	method unwrap_err () {\\n		if ( not _is_ok ) {\\n			return _error;\\n		}\\n\\n		die `called Result.unwrap_err() on an ok value: ${_value}`;\\n	}\\n}\\n";\n        virtualFiles["/modules/std/string/quoted_printable.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/string/quoted_printable - Quoted-printable encoders and decoders.\\n\\n=head1 SYNOPSIS\\n\\n  from std/string/quoted_printable import encode, decode;\\n\\n  let raw := to_binary( "Hello, world!\\\\r\\\\n" );\\n\\n  let text := encode(raw);\\n  let bytes := decode(text);\\n\\n  let binary_text := encode(raw, binary: true);\\n  let short_lines := encode(raw, line_length: 40, newline: "\\\\n");\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nThis module provides quoted-printable encoding and decoding helpers for\\nRFC 2045-style byte transport. Encoding returns ASCII C<String> text.\\nDecoding returns a C<BinaryString>, because quoted-printable is a byte\\ntransfer encoding rather than a Unicode text format.\\n\\nThe C<binary> option controls how input line break bytes are encoded.\\nIn the default non-binary mode, CRLF, CR, and LF bytes are normalized to\\nthe configured C<newline> string. In binary mode, CR and LF bytes are\\nencoded as C<=0D> and C<=0A>.\\n\\n=head1 EXPORTS\\n\\n=head2 Functions\\n\\n=over\\n\\n=item * C<encode(BinaryString bytes, ... PairList options)>\\n\\nParameters: C<bytes> is binary input data and C<options> controls\\nencoding. Returns: C<String>. Encodes C<bytes> as quoted-printable ASCII\\ntext.\\n\\n=item * C<decode(String text, ... PairList options)>\\n\\nParameters: C<text> is quoted-printable text and C<options> controls\\nstrictness. Returns: C<BinaryString>. Decodes quoted-printable text into\\nbytes.\\n\\n=back\\n\\n=head1 OPTIONS\\n\\n=over\\n\\n=item * C<line_length>\\n\\nMaximum encoded line length. Defaults to C<76> and must be at least\\nC<4>.\\n\\n=item * C<newline>\\n\\nOutput newline for hard line breaks and encoded soft breaks. Defaults\\nto CRLF.\\n\\n=item * C<binary>\\n\\nWhen true, encode CR and LF bytes as C<=0D> and C<=0A>. Defaults to\\nfalse.\\n\\n=item * C<strict>\\n\\nWhen true, malformed quoted-printable escape sequences throw during\\ndecoding. Non-strict decoding preserves malformed escape text\\nliterally.\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/string/quoted_printable >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\n\\nlet encode := null;\\nlet decode := null;\\n\\n{\\n	from std/string import chr, index, ord, substr;\\n	from std/string/base64 import\\n		encode as _base64_encode,\\n		decode as _base64_decode;\\n\\n	let _B64_ALPHABET := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"\\n		_ "abcdefghijklmnopqrstuvwxyz0123456789+/";\\n	let _HEX := "0123456789ABCDEF";\\n\\n	function _div_floor ( Number n, Number d ) {\\n		return floor( n / d );\\n	}\\n\\n	function _mod ( Number n, Number d ) {\\n		return n - _div_floor( n, d ) * d;\\n	}\\n\\n	function _bytes_to_binary ( Array bytes ) {\\n		let out := "";\\n		let i := 0;\\n		let n := bytes.length();\\n\\n		while ( i < n ) {\\n			let b0 := bytes[i];\\n			let b1 := null;\\n			let b2 := null;\\n			if ( i + 1 < n ) {\\n				b1 := bytes[i + 1];\\n			}\\n			if ( i + 2 < n ) {\\n				b2 := bytes[i + 2];\\n			}\\n\\n			let c0 := _div_floor( b0, 4 );\\n			let c1 := _mod( b0, 4 ) * 16;\\n			let c2 := 64;\\n			let c3 := 64;\\n\\n			if ( not( b1 == null ) ) {\\n				c1 += _div_floor( b1, 16 );\\n				c2 := _mod( b1, 16 ) * 4;\\n				if ( not( b2 == null ) ) {\\n					c2 += _div_floor( b2, 64 );\\n					c3 := _mod( b2, 64 );\\n				}\\n			}\\n\\n			out _= substr( _B64_ALPHABET, c0, 1 );\\n			out _= substr( _B64_ALPHABET, c1, 1 );\\n			out _= c2 == 64 ? "=" : substr( _B64_ALPHABET, c2, 1 );\\n			out _= c3 == 64 ? "=" : substr( _B64_ALPHABET, c3, 1 );\\n			i += 3;\\n		}\\n\\n		return _base64_decode(out);\\n	}\\n\\n	function _binary_to_bytes ( BinaryString raw ) {\\n		let b64 := _base64_encode(raw);\\n		let out := [];\\n		let i := 0;\\n		let n := length b64;\\n\\n		while ( i < n ) {\\n			let c0 := index( _B64_ALPHABET, substr( b64, i, 1 ) );\\n			let c1 := index( _B64_ALPHABET, substr( b64, i + 1, 1 ) );\\n			let ch2 := substr( b64, i + 2, 1 );\\n			let ch3 := substr( b64, i + 3, 1 );\\n			let c2 := -1;\\n			let c3 := -1;\\n			if ( ch2 ne "=" ) {\\n				c2 := index( _B64_ALPHABET, ch2 );\\n			}\\n			if ( ch3 ne "=" ) {\\n				c3 := index( _B64_ALPHABET, ch3 );\\n			}\\n\\n			out.push( c0 * 4 + _div_floor( c1, 16 ) );\\n			if ( c2 >= 0 ) {\\n				out.push( _mod( c1, 16 ) * 16 + _div_floor( c2, 4 ) );\\n			}\\n			if ( c3 >= 0 ) {\\n				out.push( _mod( c2, 4 ) * 64 + c3 );\\n			}\\n\\n			i += 4;\\n		}\\n\\n		return out;\\n	}\\n\\n	function _parse_options ( PairList options ) {\\n		let line_length := 76;\\n		let newline := "\\\\r\\\\n";\\n		let binary := false;\\n		let strict := false;\\n\\n		for ( let option in options.enumerate() ) {\\n			let key := option.key;\\n			let value := option.value;\\n\\n			if ( key eq "line_length" ) {\\n				line_length := value;\\n			}\\n			else if ( key eq "newline" ) {\\n				newline := value;\\n			}\\n			else if ( key eq "binary" ) {\\n				binary := value;\\n			}\\n			else if ( key eq "strict" ) {\\n				strict := value;\\n			}\\n			else {\\n				die `quoted_printable option \\\'${key}\\\' is not supported`;\\n			}\\n		}\\n\\n		if ( not( line_length instanceof Number ) ) {\\n			die "quoted_printable line_length option expects Number";\\n		}\\n		if ( line_length < 4 ) {\\n			die "quoted_printable line_length option must be at least 4";\\n		}\\n		if ( not( newline instanceof String ) ) {\\n			die "quoted_printable newline option expects String";\\n		}\\n		if ( not( binary instanceof Boolean ) ) {\\n			die "quoted_printable binary option expects Boolean";\\n		}\\n		if ( not( strict instanceof Boolean ) ) {\\n			die "quoted_printable strict option expects Boolean";\\n		}\\n\\n		return {\\n			line_length: int(line_length),\\n			newline: newline,\\n			binary: binary,\\n			strict: strict,\\n		};\\n	}\\n\\n	function _is_safe_literal ( Number b ) {\\n		return ( b >= 33 and b <= 60 ) or ( b >= 62 and b <= 126 );\\n	}\\n\\n	function _byte_to_hex_token ( Number b ) {\\n		return "="\\n			_ substr( _HEX, _div_floor( b, 16 ), 1 )\\n			_ substr( _HEX, _mod( b, 16 ), 1 );\\n	}\\n\\n	function _simple_token_length ( Number b, Boolean final_byte ) {\\n		if ( ( b == 9 or b == 32 ) and not final_byte ) {\\n			return 1;\\n		}\\n		if ( _is_safe_literal(b) ) {\\n			return 1;\\n		}\\n		return 3;\\n	}\\n\\n	function _space_tab_needs_escape (\\n		Array bytes,\\n		Number i,\\n		Number column,\\n		Number line_length,\\n	) {\\n		let n := bytes.length();\\n		if ( i + 1 >= n ) {\\n			return true;\\n		}\\n\\n		let j := i + 1;\\n		while ( j < n and ( bytes[j] == 9 or bytes[j] == 32 ) ) {\\n			j++;\\n		}\\n		if ( j >= n ) {\\n			return true;\\n		}\\n\\n		let next_is_final := i + 2 >= n;\\n		let next_len := _simple_token_length( bytes[i + 1], next_is_final );\\n		let max := next_is_final ? line_length : line_length - 1;\\n		return column + 1 + next_len > max;\\n	}\\n\\n	function _token_for_byte (\\n		Array bytes,\\n		Number i,\\n		Number column,\\n		Number line_length,\\n	) {\\n		let b := bytes[i];\\n\\n		if ( b == 9 or b == 32 ) {\\n			if ( _space_tab_needs_escape( bytes, i, column, line_length ) ) {\\n				return _byte_to_hex_token(b);\\n			}\\n			return chr(b);\\n		}\\n\\n		if ( _is_safe_literal(b) ) {\\n			return chr(b);\\n		}\\n\\n		return _byte_to_hex_token(b);\\n	}\\n\\n	function _emit_token (\\n		String out,\\n		Number column,\\n		String token,\\n		Boolean more_after,\\n		Number line_length,\\n		String newline,\\n	) {\\n		let max := more_after ? line_length - 1 : line_length;\\n		let updated_out := out;\\n		let updated_column := column;\\n\\n		if ( updated_column > 0 and updated_column + ( length token ) > max ) {\\n			updated_out _= "=" _ newline;\\n			updated_column := 0;\\n		}\\n\\n		updated_out _= token;\\n		updated_column += length token;\\n\\n		return [ updated_out, updated_column ];\\n	}\\n\\n	function _encode_segment (\\n		Array bytes,\\n		Number line_length,\\n		String newline,\\n	) {\\n		let out := "";\\n		let column := 0;\\n		let i := 0;\\n		let n := bytes.length();\\n\\n		while ( i < n ) {\\n			let token := _token_for_byte( bytes, i, column, line_length );\\n			let emitted := _emit_token(\\n				out,\\n				column,\\n				token,\\n				i + 1 < n,\\n				line_length,\\n				newline,\\n			);\\n			out := emitted[0];\\n			column := emitted[1];\\n			i++;\\n		}\\n\\n		return out;\\n	}\\n\\n	function _encode_text_bytes (\\n		Array bytes,\\n		Number line_length,\\n		String newline,\\n	) {\\n		let out := "";\\n		let line := [];\\n		let i := 0;\\n		let n := bytes.length();\\n\\n		while ( i < n ) {\\n			let b := bytes[i];\\n			if ( b == 13 or b == 10 ) {\\n				out _= _encode_segment( line, line_length, newline );\\n				out _= newline;\\n				line := [];\\n\\n				if ( b == 13 and i + 1 < n and bytes[i + 1] == 10 ) {\\n					i++;\\n				}\\n			}\\n			else {\\n				line.push(b);\\n			}\\n\\n			i++;\\n		}\\n\\n		out _= _encode_segment( line, line_length, newline );\\n		return out;\\n	}\\n\\n	function _hex_value ( String ch ) {\\n		let cp := ord(ch);\\n		if ( cp >= 48 and cp <= 57 ) {\\n			return cp - 48;\\n		}\\n		if ( cp >= 65 and cp <= 70 ) {\\n			return cp - 55;\\n		}\\n		if ( cp >= 97 and cp <= 102 ) {\\n			return cp - 87;\\n		}\\n		return -1;\\n	}\\n\\n	function _decode_text_bytes ( String text, Boolean strict ) {\\n		let out := [];\\n		let i := 0;\\n		let n := length text;\\n\\n		while ( i < n ) {\\n			let ch := substr( text, i, 1 );\\n			let cp := ord( text, i );\\n\\n			if ( cp > 127 ) {\\n				die "quoted_printable.decode rejects non-ASCII input";\\n			}\\n\\n			if ( ch eq "=" ) {\\n				if ( i + 1 >= n ) {\\n					die "malformed quoted-printable escape" if strict;\\n					out.push(61);\\n					i++;\\n					next;\\n				}\\n\\n				let ch1 := substr( text, i + 1, 1 );\\n				if ( ch1 eq "\\\\r" ) {\\n					if ( i + 2 < n and substr( text, i + 2, 1 ) eq "\\\\n" ) {\\n						i += 3;\\n					}\\n					else {\\n						i += 2;\\n					}\\n					next;\\n				}\\n				if ( ch1 eq "\\\\n" ) {\\n					i += 2;\\n					next;\\n				}\\n\\n				if ( i + 2 < n ) {\\n					let hi := _hex_value(ch1);\\n					let lo := _hex_value( substr( text, i + 2, 1 ) );\\n					if ( hi >= 0 and lo >= 0 ) {\\n						out.push( hi * 16 + lo );\\n						i += 3;\\n						next;\\n					}\\n				}\\n\\n				die "malformed quoted-printable escape" if strict;\\n				out.push(61);\\n				i++;\\n				next;\\n			}\\n\\n			out.push(cp);\\n			i++;\\n		}\\n\\n		return out;\\n	}\\n\\n	encode := function ( BinaryString bytes, ... PairList options ) {\\n		let opts := _parse_options(options);\\n		let raw := _binary_to_bytes(bytes);\\n\\n		if ( opts{binary} ) {\\n			return _encode_segment(\\n				raw,\\n				opts{line_length},\\n				opts{newline},\\n			);\\n		}\\n\\n		return _encode_text_bytes(\\n			raw,\\n			opts{line_length},\\n			opts{newline},\\n		);\\n	};\\n\\n	decode := function ( String text, ... PairList options ) {\\n		let opts := _parse_options(options);\\n		return _bytes_to_binary( _decode_text_bytes( text, opts{strict} ) );\\n	};\\n}\\n\';\n        virtualFiles["/modules/std/gui.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/gui - User-facing GUI constructor helpers.\\n\\n=head1 SYNOPSIS\\n\\n  from std/gui import *;\\n\\n  let w := Window(\\n  	title: "Demo",\\n  	VBox(\\n  		Label( text: "Name:" ),\\n  		Input( id: "name" ),\\n  		Button( text: "OK", id: "submit" ),\\n  	),\\n  );\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Electron.\\nIt is not supported by zuzu-js on Node. It is partially supported by\\nzuzu-js in the browser: core GUI and widget lifecycle coverage passes,\\nbut filesystem-backed file and directory dialogue coverage is unsupported.\\n\\n=head1 DESCRIPTION\\n\\nThis module provides thin constructor helpers over C<std/gui/objects>.\\nHost runtimes expose the shared widget, object tree, event, and window\\nlifecycle APIs when GUI support is available. It also re-exports\\nbackend-native file and directory dialogue hooks for C<std/gui/dialogue>.\\n\\nThe module exports C<EM>, the standard UI font height in logical\\npixels, derived from C<std/gui/objects> metadata.\\n\\n=head1 EXPORTS\\n\\n=head2 Constants\\n\\n=over\\n\\n=item C<EM>\\n\\nType: C<Number>. Standard UI font height in logical pixels.\\n\\n=item C<GUI_XML_NS>\\n\\nType: C<String>. XML namespace URI used by GUI XML serialization and\\nparsing.\\n\\n=back\\n\\n=head2 Functions\\n\\n=over\\n\\n=item C<< Window(... PairList p, Array c) >>, C<< VBox(... PairList p, Array c) >>, C<< HBox(... PairList p, Array c) >>, C<< Frame(... PairList p, Array c) >>\\n\\nParameters: C<p> are widget properties and C<c> contains child widgets.\\nReturns: widget object. Constructs window and layout widgets.\\n\\n=item C<< Label(... PairList p, Array c) >>, C<< Text(... PairList p, Array c) >>, C<< RichText(... PairList p, Array c) >>, C<< Image(... PairList p, Array c) >>\\n\\nParameters: C<p> are widget properties and C<c> contains child widgets.\\nReturns: widget object. Constructs content widgets.\\n\\n=item C<< Input(... PairList p, Array c) >>, C<< DatePicker(... PairList p, Array c) >>, C<< Checkbox(... PairList p, Array c) >>, C<< Radio(... PairList p, Array c) >>, C<< RadioGroup(... PairList p, Array c) >>, C<< Select(... PairList p, Array c) >>\\n\\nParameters: C<p> are widget properties and C<c> contains child widgets.\\nReturns: widget object. Constructs input widgets.\\n\\n=item C<< Menu(... PairList p, Array c) >>, C<< MenuItem(... PairList p, Array c) >>, C<< Button(... PairList p, Array c) >>, C<< Separator(... PairList p, Array c) >>, C<< Slider(... PairList p, Array c) >>, C<< Progress(... PairList p, Array c) >>\\n\\nParameters: C<p> are widget properties and C<c> contains child widgets.\\nReturns: widget object. Constructs command and control widgets.\\n\\n=item C<< Tabs(... PairList p, Array c) >>, C<< Tab(... PairList p, Array c) >>, C<< ListView(... PairList p, Array c) >>, C<< TreeView(... PairList p, Array c) >>\\n\\nParameters: C<p> are widget properties and C<c> contains child widgets.\\nReturns: widget object. Constructs tabular and collection widgets.\\n\\n=item C<< unbind(BindingToken token) >>\\n\\nParameters: C<token> is a binding token. Returns: C<null>. Removes a GUI\\nbinding.\\n\\n=item C<< gui_from_xml(String xml) >>, C<< gui_from_xml_file(path) >>\\n\\nParameters: C<xml> is GUI XML text and C<path> is a file path. Returns:\\nwidget object. Builds a GUI object tree from XML.\\n\\n=item C<< gui_to_xml(Widget root) >>\\n\\nParameters: C<root> is a GUI widget. Returns: C<String>. Serializes a\\nGUI object tree to XML.\\n\\n=back\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<BindingToken>\\n\\nRepresents a model/widget binding.\\n\\n=over\\n\\n=item C<< token.is_active() >>\\n\\nParameters: none. Returns: C<Boolean>. Returns true while the binding is\\nactive.\\n\\n=item C<< token.set_listener(token) >>\\n\\nParameters: C<token> is a listener token. Returns: C<BindingToken>.\\nStores the listener token associated with the binding.\\n\\n=item C<< token.sync_model_to_widget() >>, C<< token.sync_widget_to_model() >>\\n\\nParameters: none. Returns: C<null>. Synchronizes the bound values.\\n\\n=item C<< token.unbind() >>\\n\\nParameters: none. Returns: C<null>. Removes the binding.\\n\\n=back\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/gui >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/gui/objects import\\n	Window as _WindowClass,\\n	VBox as _VBoxClass,\\n	HBox as _HBoxClass,\\n	Frame as _FrameClass,\\n	Label as _LabelClass,\\n	Text as _TextClass,\\n	RichText as _RichTextClass,\\n	Image as _ImageClass,\\n	Input as _InputClass,\\n	DatePicker as _DatePickerClass,\\n	Checkbox as _CheckboxClass,\\n	Radio as _RadioClass,\\n	RadioGroup as _RadioGroupClass,\\n	Select as _SelectClass,\\n	Menu as _MenuClass,\\n	MenuItem as _MenuItemClass,\\n	Button as _ButtonClass,\\n	Separator as _SeparatorClass,\\n	Slider as _SliderClass,\\n	Progress as _ProgressClass,\\n	Tabs as _TabsClass,\\n	Tab as _TabClass,\\n	ListView as _ListViewClass,\\n	TreeView as _TreeViewClass,\\n	Widget,\\n	Event,\\n	ListenerToken,\\n	native_file_open,\\n	native_file_save,\\n	native_directory_open,\\n	native_directory_save,\\n	native_colour_picker,\\n	meta as _gui_meta;\\n\\nfrom std/gui/objects try import\\n	native_alert,\\n	native_confirm,\\n	native_prompt;\\n\\nfrom std/data/xml import XML;\\nfrom std/data/xml/escape import escape_xml;\\nfrom std/internals import getupperprop;\\nfrom std/path/zz import ZZPath;\\nfrom std/string import join, split, substr, trim;\\n\\n\\nconst Number EM := _gui_meta{font_size_pixels};\\n\\nfunction _assert_known_props ( String ctor, PairList props, Array allowed ) {\\n	let geometry := [\\n		"width",\\n		"height",\\n		"minwidth",\\n		"minheight",\\n		"maxwidth",\\n		"maxheight",\\n	];\\n	for ( let key in props.keys() ) {\\n		if ( key \\u2209 allowed and key \\u2209 geometry ) {\\n			die `GUI_PROP_UNKNOWN: ${ctor} does not accept property \\\'${key}\\\'`;\\n		}\\n	}\\n}\\n\\nfunction _assert_prop_value ( String ctor, String prop, value, Array allowed ) {\\n	if ( value \\u2209 allowed ) {\\n		die `GUI_PROP_TYPE: ${ctor} property \\\'${prop}\\\' has invalid value`;\\n	}\\n}\\n\\nfunction _assert_prop_array ( String ctor, String prop, value ) {\\n	if ( not( value instanceof Array ) ) {\\n		die `GUI_PROP_TYPE: ${ctor} property \\\'${prop}\\\' expects Array`;\\n	}\\n}\\n\\nfunction _with_geometry_props ( Array allowed ) {\\n	for ( let key in [\\n		"width",\\n		"height",\\n		"minwidth",\\n		"minheight",\\n		"maxwidth",\\n		"maxheight",\\n	] ) {\\n		allowed.push(key) unless key \\u2208 allowed;\\n	}\\n	return allowed;\\n}\\n\\nfunction _apply_geometry ( Widget widget, PairList p ) {\\n	for ( let key in [\\n		"width",\\n		"height",\\n		"minwidth",\\n		"minheight",\\n		"maxwidth",\\n		"maxheight",\\n	] ) {\\n		if ( p.has(key) ) {\\n			widget.(key)( p.get(key) );\\n		}\\n	}\\n	return widget;\\n}\\n\\nfunction Window ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"Window",\\n		p,\\n		_with_geometry_props( [\\n			"id",\\n			"title",\\n			"width",\\n			"height",\\n			"resizable",\\n			"modal",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		] ),\\n	);\\n\\n	return new _WindowClass(\\n		id: p.get( "id", null ),\\n		title: p.get( "title", "" ),\\n		width: p.get( "width", 800 ),\\n		height: p.get( "height", 600 ),\\n		minwidth: p.get( "minwidth", null ),\\n		minheight: p.get( "minheight", null ),\\n		maxwidth: p.get( "maxwidth", null ),\\n		maxheight: p.get( "maxheight", null ),\\n		resizable: p.get( "resizable", true ),\\n		modal: p.get( "modal", false ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	);\\n}\\n\\nfunction VBox ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"VBox",\\n		p,\\n		[\\n			"id",\\n			"align",\\n			"gap",\\n			"padding",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		],\\n	);\\n\\n	_assert_prop_value(\\n		"VBox",\\n		"align",\\n		p.get( "align", "top" ),\\n		[ "top", "centre", "bottom", "stretch" ],\\n	);\\n\\n	return _apply_geometry( new _VBoxClass(\\n		id: p.get( "id", null ),\\n		align: p.get( "align", "top" ),\\n		gap: p.get( "gap", 0 ),\\n		padding: p.get( "padding", 0 ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction HBox ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"HBox",\\n		p,\\n		_with_geometry_props( [\\n			"id",\\n			"align",\\n			"gap",\\n			"padding",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		] ),\\n	);\\n\\n	_assert_prop_value(\\n		"HBox",\\n		"align",\\n		p.get( "align", "left" ),\\n		[ "left", "centre", "right", "stretch" ],\\n	);\\n\\n	return new _HBoxClass(\\n		id: p.get( "id", null ),\\n		align: p.get( "align", "left" ),\\n		gap: p.get( "gap", 0 ),\\n		padding: p.get( "padding", 0 ),\\n		width: p.get( "width", null ),\\n		height: p.get( "height", null ),\\n		minwidth: p.get( "minwidth", null ),\\n		minheight: p.get( "minheight", null ),\\n		maxwidth: p.get( "maxwidth", null ),\\n		maxheight: p.get( "maxheight", null ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	);\\n}\\n\\nfunction Frame ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"Frame",\\n		p,\\n		[\\n			"id",\\n			"label",\\n			"collapsible",\\n			"collapsed",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		],\\n	);\\n\\n	return _apply_geometry( new _FrameClass(\\n		id: p.get( "id", null ),\\n		label: p.get( "label", "" ),\\n		collapsible: p.get( "collapsible", false ),\\n		collapsed: p.get( "collapsed", false ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction Label ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"Label",\\n		p,\\n		[ "id", "text", "for", "visible", "enabled", "disabled" ],\\n	);\\n\\n	let label := new _LabelClass(\\n		id: p.get( "id", null ),\\n		text: p.get( "text", "" ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	);\\n	if ( p.has("for") ) {\\n		label.set_for_id( p.get( "for", null ) );\\n	}\\n\\n	return _apply_geometry( label, p );\\n}\\n\\nfunction Text ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"Text",\\n		p,\\n		[\\n			"id",\\n			"value",\\n			"multiline",\\n			"readonly",\\n			"wrap",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		],\\n	);\\n\\n	return _apply_geometry( new _TextClass(\\n		id: p.get( "id", null ),\\n		value: p.get( "value", "" ),\\n		multiline: p.get( "multiline", false ),\\n		readonly: p.get( "readonly", false ),\\n		wrap: p.get( "wrap", true ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction RichText ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"RichText",\\n		p,\\n		[\\n			"id",\\n			"value",\\n			"multiline",\\n			"readonly",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		],\\n	);\\n\\n	return _apply_geometry( new _RichTextClass(\\n		id: p.get( "id", null ),\\n		value: p.get( "value", "" ),\\n		multiline: p.get( "multiline", true ),\\n		readonly: p.get( "readonly", true ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction Image ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"Image",\\n		p,\\n		[ "id", "src", "alt", "fit", "visible", "enabled", "disabled" ],\\n	);\\n\\n	_assert_prop_value(\\n		"Image",\\n		"fit",\\n		p.get( "fit", "none" ),\\n		[ "none", "contain", "cover", "stretch" ],\\n	);\\n\\n	return _apply_geometry( new _ImageClass(\\n		id: p.get( "id", null ),\\n		src: p.get( "src", "" ),\\n		alt: p.get( "alt", "" ),\\n		fit: p.get( "fit", "none" ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction Input ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"Input",\\n		p,\\n		[\\n			"id",\\n			"value",\\n			"placeholder",\\n			"multiline",\\n			"readonly",\\n			"password",\\n			"required",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		],\\n	);\\n\\n	return _apply_geometry( new _InputClass(\\n		id: p.get( "id", null ),\\n		value: p.get( "value", "" ),\\n		placeholder: p.get( "placeholder", "" ),\\n		multiline: p.get( "multiline", false ),\\n		readonly: p.get( "readonly", false ),\\n		password: p.get( "password", false ),\\n		required: p.get( "required", false ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction DatePicker ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"DatePicker",\\n		p,\\n		[\\n			"id",\\n			"value",\\n			"min",\\n			"max",\\n			"first_day_of_week",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		],\\n	);\\n\\n	return _apply_geometry( new _DatePickerClass(\\n		id: p.get( "id", null ),\\n		value: p.get( "value", null ),\\n		min: p.get( "min", null ),\\n		max: p.get( "max", null ),\\n		first_day_of_week: p.get( "first_day_of_week", 0 ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction Checkbox ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"Checkbox",\\n		p,\\n		[\\n			"id",\\n			"label",\\n			"checked",\\n			"indeterminate",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		],\\n	);\\n\\n	return _apply_geometry( new _CheckboxClass(\\n		id: p.get( "id", null ),\\n		label: p.get( "label", "" ),\\n		checked: p.get( "checked", false ),\\n		indeterminate: p.get( "indeterminate", false ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction Radio ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"Radio",\\n		p,\\n		[\\n			"id",\\n			"label",\\n			"value",\\n			"group",\\n			"checked",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		],\\n	);\\n\\n	return _apply_geometry( new _RadioClass(\\n		id: p.get( "id", null ),\\n		label: p.get( "label", "" ),\\n		value: p.get( "value", "" ),\\n		group: p.get( "group", null ),\\n		checked: p.get( "checked", false ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction RadioGroup ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"RadioGroup",\\n		p,\\n		[\\n			"id",\\n			"name",\\n			"value",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		],\\n	);\\n\\n	return _apply_geometry( new _RadioGroupClass(\\n		id: p.get( "id", null ),\\n		name: p.get( "name", "" ),\\n		value: p.get( "value", null ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction Select ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"Select",\\n		p,\\n		[\\n			"id",\\n			"value",\\n			"options",\\n			"multiple",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		],\\n	);\\n\\n	if ( p.has("options") ) {\\n		_assert_prop_array( "Select", "options", p.get("options") );\\n	}\\n\\n	return _apply_geometry( new _SelectClass(\\n		id: p.get( "id", null ),\\n		value: p.get( "value", null ),\\n		options: p.get( "options", [] ),\\n		multiple: p.get( "multiple", false ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction Menu ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"Menu",\\n		p,\\n		[ "id", "text", "visible", "enabled", "disabled" ],\\n	);\\n\\n	return _apply_geometry( new _MenuClass(\\n		id: p.get( "id", null ),\\n		text: p.get( "text", "" ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction MenuItem ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"MenuItem",\\n		p,\\n		[ "id", "text", "disabled", "visible", "enabled" ],\\n	);\\n\\n	return _apply_geometry( new _MenuItemClass(\\n		id: p.get( "id", null ),\\n		text: p.get( "text", "" ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction Button ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"Button",\\n		p,\\n		_with_geometry_props( [\\n			"id",\\n			"text",\\n			"variant",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		] ),\\n	);\\n\\n	_assert_prop_value(\\n		"Button",\\n		"variant",\\n		p.get( "variant", "default" ),\\n		[ "default", "primary", "danger" ],\\n	);\\n\\n	return new _ButtonClass(\\n		id: p.get( "id", null ),\\n		text: p.get( "text", "" ),\\n		variant: p.get( "variant", "default" ),\\n		width: p.get( "width", null ),\\n		height: p.get( "height", null ),\\n		minwidth: p.get( "minwidth", null ),\\n		minheight: p.get( "minheight", null ),\\n		maxwidth: p.get( "maxwidth", null ),\\n		maxheight: p.get( "maxheight", null ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	);\\n}\\n\\nfunction Separator ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"Separator",\\n		p,\\n		[ "id", "orientation", "visible", "enabled", "disabled" ],\\n	);\\n\\n	_assert_prop_value(\\n		"Separator",\\n		"orientation",\\n		p.get( "orientation", "horizontal" ),\\n		[ "horizontal", "vertical" ],\\n	);\\n\\n	return _apply_geometry( new _SeparatorClass(\\n		id: p.get( "id", null ),\\n		orientation: p.get( "orientation", "horizontal" ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction Slider ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"Slider",\\n		p,\\n		[\\n			"id",\\n			"value",\\n			"min",\\n			"max",\\n			"step",\\n			"orientation",\\n			"readonly",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		],\\n	);\\n\\n	_assert_prop_value(\\n		"Slider",\\n		"orientation",\\n		p.get( "orientation", "horizontal" ),\\n		[ "horizontal", "vertical" ],\\n	);\\n\\n	return _apply_geometry( new _SliderClass(\\n		id: p.get( "id", null ),\\n		value: p.get( "value", 0 ),\\n		min: p.get( "min", 0 ),\\n		max: p.get( "max", 100 ),\\n		step: p.get( "step", 1 ),\\n		orientation: p.get( "orientation", "horizontal" ),\\n		readonly: p.get( "readonly", false ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction Progress ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"Progress",\\n		p,\\n		[\\n			"id",\\n			"value",\\n			"min",\\n			"max",\\n			"indeterminate",\\n			"show_text",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		],\\n	);\\n\\n	return _apply_geometry( new _ProgressClass(\\n		id: p.get( "id", null ),\\n		value: p.get( "value", 0 ),\\n		min: p.get( "min", 0 ),\\n		max: p.get( "max", 100 ),\\n		indeterminate: p.get( "indeterminate", false ),\\n		show_text: p.get( "show_text", false ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction Tabs ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"Tabs",\\n		p,\\n		[\\n			"id",\\n			"selected",\\n			"placement",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		],\\n	);\\n\\n	_assert_prop_value(\\n		"Tabs",\\n		"placement",\\n		p.get( "placement", "top" ),\\n		[ "top", "bottom", "left", "right" ],\\n	);\\n\\n	return _apply_geometry( new _TabsClass(\\n		id: p.get( "id", null ),\\n		selected: p.get( "selected", null ),\\n		placement: p.get( "placement", "top" ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction Tab ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"Tab",\\n		p,\\n		[\\n			"id",\\n			"title",\\n			"value",\\n			"selected",\\n			"closable",\\n			"icon",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		],\\n	);\\n\\n	return _apply_geometry( new _TabClass(\\n		id: p.get( "id", null ),\\n		title: p.get( "title", "" ),\\n		value: p.get( "value", "" ),\\n		selected: p.get( "selected", false ),\\n		closable: p.get( "closable", false ),\\n		icon: p.get( "icon", null ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction ListView ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"ListView",\\n		p,\\n		[\\n			"id",\\n			"items",\\n			"selected_index",\\n			"multiple",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		],\\n	);\\n\\n	if ( p.has("items") ) {\\n		_assert_prop_array( "ListView", "items", p.get("items") );\\n	}\\n\\n	return _apply_geometry( new _ListViewClass(\\n		id: p.get( "id", null ),\\n		items: p.get( "items", [] ),\\n		selected_index: p.get( "selected_index", null ),\\n		multiple: p.get( "multiple", false ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction TreeView ( ... PairList p, Array c ) {\\n	_assert_known_props(\\n		"TreeView",\\n		p,\\n		[\\n			"id",\\n			"items",\\n			"selected_path",\\n			"multiple",\\n			"visible",\\n			"enabled",\\n			"disabled",\\n		],\\n	);\\n\\n	if ( p.has("items") ) {\\n		_assert_prop_array( "TreeView", "items", p.get("items") );\\n	}\\n	if ( p.has("selected_path") ) {\\n		_assert_prop_array( "TreeView", "selected_path", p.get("selected_path") );\\n	}\\n\\n	return _apply_geometry( new _TreeViewClass(\\n		id: p.get( "id", null ),\\n		items: p.get( "items", [] ),\\n		selected_path: p.get( "selected_path", [] ),\\n		multiple: p.get( "multiple", false ),\\n		visible: p.get( "visible", true ),\\n		enabled: p.get( "enabled", true ),\\n		disabled: p.get( "disabled", false ),\\n		children: c,\\n	), p );\\n}\\n\\nfunction _binding_path_class ( path_class ) {\\n	if ( path_class \\u2261 null ) {\\n		return ZZPath;\\n	}\\n	if ( not( path_class instanceof Class ) ) {\\n		die "GUI_BIND_PATH: paths special property must be Class or null";\\n	}\\n	return path_class;\\n}\\n\\nfunction _binding_compile_path ( String path_text, path_class ) {\\n	if ( path_class \\u2261 null ) {\\n		try {\\n			return new ZZPath( path: path_text );\\n		}\\n		catch ( Exception e ) {\\n			die `GUI_BIND_PATH: ${e{message}}`;\\n		}\\n	}\\n\\n	let path_type := _binding_path_class(path_class);\\n	try {\\n		return new path_type( path: path_text );\\n	}\\n	catch ( Exception e ) {\\n		die `GUI_BIND_PATH: ${e{message}}`;\\n	}\\n}\\n\\nfunction _binding_path ( pathish, path_class ) {\\n	if ( pathish instanceof String ) {\\n		return _binding_compile_path( pathish, path_class );\\n	}\\n	if (\\n		pathish can first\\n		and ( pathish can assign_first or pathish can ref_first )\\n	) {\\n		return pathish;\\n	}\\n\\n	die "GUI_BIND_PATH: binding path must be String or path-like Object";\\n}\\n\\nfunction _binding_get ( model, path ) {\\n	return path.first( model, null );\\n}\\n\\nfunction _binding_set ( model, path, value ) {\\n	if ( path can assign_first ) {\\n		return path.assign_first( model, value );\\n	}\\n\\n	let ref := path.ref_first(model);\\n	return ref(value);\\n}\\n\\nclass BindingToken {\\n	let Widget widget but weak;\\n	let String widget_prop;\\n	let model;\\n	let model_path;\\n	let String event := "change";\\n	let listener := null;\\n	let Boolean _active := true;\\n\\n	method is_active () {\\n		return _active;\\n	}\\n\\n	method set_listener ( token ) {\\n		listener := token;\\n		return self;\\n	}\\n\\n	method sync_model_to_widget () {\\n		widget.(widget_prop)( _binding_get( model, model_path ) );\\n		return self;\\n	}\\n\\n	method sync_widget_to_model () {\\n		_binding_set( model, model_path, widget.(widget_prop)() );\\n		return self;\\n	}\\n\\n	method unbind () {\\n		if ( _active and listener \\u2262 null ) {\\n			widget.off(listener);\\n		}\\n		_active := false;\\n		return self;\\n	}\\n}\\n\\nfunction bind (\\n	Widget widget,\\n	String widget_prop,\\n	model,\\n	model_path,\\n	... PairList p\\n) {\\n	let path := _binding_path( model_path, getupperprop( 1, "paths" ) );\\n\\n	let token := new BindingToken(\\n		widget: widget,\\n		widget_prop: widget_prop,\\n		model: model,\\n		model_path: path,\\n		event: p.get( "event", "change" ),\\n	);\\n	let event_name := p.get( "event", "change" );\\n\\n	switch ( p.get( "initial", "model" ): eq ) {\\n		case "model":\\n			token.sync_model_to_widget();\\n		case "widget":\\n			token.sync_widget_to_model();\\n		case "none":\\n			// No initial sync.\\n		default:\\n			die "GUI_BIND_INITIAL: initial must be model, widget, or none";\\n	}\\n\\n	token.set_listener(\\n		widget.on( event_name, function () {\\n			if ( token.is_active() ) {\\n				token.sync_widget_to_model();\\n			}\\n		} ),\\n	);\\n	return token;\\n}\\n\\nfunction unbind ( BindingToken token ) {\\n	return token.unbind();\\n}\\n\\nlet GUI_XML_NS := "https://zuzulang.org/ns/std/gui";\\n\\nfunction _xml_error ( String code, String message ) {\\n	die `${code}: ${message}`;\\n}\\n\\nfunction _xml_tag_name ( node ) {\\n	return node.localName() or? node.nodeName();\\n}\\n\\nfunction _xml_assert_namespace ( node ) {\\n	let ns := node.namespaceURI();\\n	if ( ns \\u2262 null and ns \\u2262 "" and ns \\u2262 GUI_XML_NS ) {\\n		_xml_error(\\n			"GUI_XML_STRUCTURE",\\n			`unsupported GUI XML namespace \\\'${ns}\\\'`,\\n		);\\n	}\\n}\\n\\nfunction _xml_common_allowed ( Array extra ) {\\n	let out := [\\n		"id",\\n		"visible",\\n		"enabled",\\n		"disabled",\\n		"width",\\n		"height",\\n		"minwidth",\\n		"minheight",\\n		"maxwidth",\\n		"maxheight",\\n	];\\n	for ( let attr in extra ) {\\n		out.push(attr);\\n	}\\n	return out;\\n}\\n\\nfunction _xml_allowed_attrs ( String tag ) {\\n	switch ( tag: eq ) {\\n		case "Window":\\n			return _xml_common_allowed(\\n				[ "title", "width", "height", "resizable", "modal" ],\\n			);\\n		case "VBox", "HBox":\\n			return _xml_common_allowed( [ "align", "gap", "padding" ] );\\n		case "Frame":\\n			return _xml_common_allowed( [ "label", "collapsible", "collapsed" ] );\\n		case "Label":\\n			return _xml_common_allowed( [ "text", "for" ] );\\n		case "Text":\\n			return _xml_common_allowed(\\n				[ "value", "multiline", "readonly", "wrap" ],\\n			);\\n		case "RichText":\\n			return _xml_common_allowed(\\n				[ "value", "multiline", "readonly" ],\\n			);\\n		case "Image":\\n			return _xml_common_allowed( [ "src", "alt", "fit" ] );\\n		case "Input":\\n			return _xml_common_allowed( [\\n				"value",\\n				"placeholder",\\n				"multiline",\\n				"readonly",\\n				"password",\\n				"required",\\n			] );\\n		case "DatePicker":\\n			return _xml_common_allowed(\\n				[ "value", "min", "max", "first_day_of_week" ],\\n			);\\n		case "Checkbox":\\n			return _xml_common_allowed( [ "label", "checked", "indeterminate" ] );\\n		case "Radio":\\n			return _xml_common_allowed( [ "label", "value", "group", "checked" ] );\\n		case "RadioGroup":\\n			return _xml_common_allowed( [ "name", "value" ] );\\n		case "Select":\\n			return _xml_common_allowed( [ "value", "multiple" ] );\\n		case "Menu":\\n			return _xml_common_allowed( [ "text" ] );\\n		case "MenuItem":\\n			return _xml_common_allowed( [ "text" ] );\\n		case "Button":\\n			return _xml_common_allowed( [ "text", "variant" ] );\\n		case "Separator":\\n			return _xml_common_allowed( [ "orientation" ] );\\n		case "Slider":\\n			return _xml_common_allowed( [\\n				"value",\\n				"min",\\n				"max",\\n				"step",\\n				"orientation",\\n				"readonly",\\n			] );\\n		case "Progress":\\n			return _xml_common_allowed( [\\n				"value",\\n				"min",\\n				"max",\\n				"indeterminate",\\n				"show_text",\\n			] );\\n		case "Tabs":\\n			return _xml_common_allowed( [ "selected", "placement" ] );\\n		case "Tab":\\n			return _xml_common_allowed(\\n				[ "title", "value", "selected", "closable", "icon" ],\\n			);\\n		case "ListView":\\n			return _xml_common_allowed( [ "selected_index", "multiple" ] );\\n		case "TreeView":\\n			return _xml_common_allowed( [ "selected_path", "multiple" ] );\\n	}\\n\\n	_xml_error( "GUI_XML_STRUCTURE", `unsupported GUI XML element \\\'${tag}\\\'` );\\n}\\n\\nfunction _xml_bool_attrs ( String tag ) {\\n	return [\\n		"visible",\\n		"enabled",\\n		"disabled",\\n		"resizable",\\n		"modal",\\n		"collapsible",\\n		"collapsed",\\n		"multiline",\\n		"readonly",\\n		"wrap",\\n		"password",\\n		"required",\\n		"checked",\\n		"indeterminate",\\n		"multiple",\\n		"show_text",\\n		"selected",\\n		"closable",\\n	];\\n}\\n\\nfunction _xml_number_attrs ( String tag ) {\\n	return [\\n		"width",\\n		"height",\\n		"minwidth",\\n		"minheight",\\n		"maxwidth",\\n		"maxheight",\\n		"gap",\\n		"padding",\\n		"first_day_of_week",\\n		"selected_index",\\n		"value",\\n		"min",\\n		"max",\\n		"step",\\n	];\\n}\\n\\nfunction _xml_bool ( String tag, String attr, String raw ) {\\n	switch ( lc(raw): eq ) {\\n		case "true", "1", "yes", "on": return true;\\n		case "false", "0", "no", "off": return false;\\n	}\\n	_xml_error(\\n		"GUI_XML_ATTR_TYPE",\\n		`${tag}.${attr} expects a boolean XML attribute`,\\n	);\\n}\\n\\nfunction _xml_number ( String tag, String attr, String raw ) {\\n	if ( not ( raw ~ /^-?[0-9]+(\\\\.[0-9]+)?$/ ) ) {\\n		_xml_error(\\n			"GUI_XML_ATTR_TYPE",\\n			`${tag}.${attr} expects a numeric XML attribute`,\\n		);\\n	}\\n	return 0 + raw;\\n}\\n\\nfunction _xml_int_list ( String tag, String attr, String raw ) {\\n	let out := [];\\n	return out if raw eq "";\\n	for ( let part in split( raw, "," ) ) {\\n		let item := trim(part);\\n		if ( not ( item ~ /^-?[0-9]+$/ ) ) {\\n			_xml_error(\\n				"GUI_XML_ATTR_TYPE",\\n				`${tag}.${attr} expects comma-separated integers`,\\n			);\\n		}\\n		out.push( 0 + item );\\n	}\\n	return out;\\n}\\n\\nfunction _xml_coerce_attr ( String tag, String attr, String raw ) {\\n	if ( attr eq "selected" and tag eq "Tabs" ) {\\n		return raw;\\n	}\\n	if ( attr eq "value" and tag \\u2209 [ "Slider", "Progress" ] ) {\\n		return raw;\\n	}\\n	if ( attr eq "min" and tag eq "DatePicker" ) {\\n		return raw;\\n	}\\n	if ( attr eq "max" and tag eq "DatePicker" ) {\\n		return raw;\\n	}\\n	if ( attr eq "selected_path" ) {\\n		return _xml_int_list( tag, attr, raw );\\n	}\\n	if ( attr \\u2208 _xml_bool_attrs(tag) ) {\\n		return _xml_bool( tag, attr, raw );\\n	}\\n	if ( attr \\u2208 _xml_number_attrs(tag) ) {\\n		return _xml_number( tag, attr, raw );\\n	}\\n	return raw;\\n}\\n\\nfunction _xml_attrs ( node ) {\\n	let tag := _xml_tag_name(node);\\n	let props := {};\\n	let meta := {};\\n	let meta_keys := [];\\n	let style := {};\\n	let style_keys := [];\\n	let allowed := _xml_allowed_attrs(tag);\\n\\n	for ( let attr in node.attributeNames() ) {\\n		next if attr eq "xmlns";\\n		next if substr( attr, 0, 6 ) eq "xmlns:";\\n		let value := node.getAttribute(attr);\\n		if ( substr( attr, 0, 5 ) eq "meta." ) {\\n			let key := substr( attr, 5 );\\n			_xml_error( "GUI_XML_ATTR_UNKNOWN", "empty meta attribute name" )\\n				if key eq "";\\n			meta{(key)} := value;\\n			meta_keys.push(key);\\n			next;\\n		}\\n		if ( substr( attr, 0, 6 ) eq "style." ) {\\n			let key := substr( attr, 6 );\\n			_xml_error( "GUI_XML_ATTR_UNKNOWN", "empty style attribute name" )\\n				if key eq "";\\n			style{(key)} := value;\\n			style_keys.push(key);\\n			next;\\n		}\\n		if ( attr \\u2209 allowed ) {\\n			_xml_error(\\n				"GUI_XML_ATTR_UNKNOWN",\\n				`${tag} does not accept XML attribute \\\'${attr}\\\'`,\\n			);\\n		}\\n		props{(attr)} := _xml_coerce_attr( tag, attr, value );\\n	}\\n\\n	return {\\n		props: props,\\n		meta: meta,\\n		meta_keys: meta_keys,\\n		style: style,\\n		style_keys: style_keys,\\n	};\\n}\\n\\nfunction _xml_apply_meta ( Widget widget, Dict meta, Array keys ) {\\n	for ( let key in keys ) {\\n		widget.meta( key, meta{(key)} );\\n	}\\n	if ( keys.length() > 0 ) {\\n		widget.meta( "__xml_meta_keys", keys );\\n	}\\n	return widget;\\n}\\n\\nfunction _xml_apply_style ( Widget widget, Dict style, Array keys ) {\\n	for ( let key in keys ) {\\n		widget.style( key, style{(key)} );\\n	}\\n	if ( keys.length() > 0 ) {\\n		widget.meta( "__xml_style_keys", keys );\\n	}\\n	return widget;\\n}\\n\\nfunction _xml_widget_from_node ( node ) {\\n	_xml_assert_namespace(node);\\n\\n	let tag := _xml_tag_name(node);\\n	let child_widgets := [];\\n	for ( let child in node.children() ) {\\n		child_widgets.push( _xml_widget_from_node(child) );\\n	}\\n	let parsed := _xml_attrs(node);\\n	let p := parsed{props};\\n	let widget;\\n\\n	switch ( tag: eq ) {\\n		case "Window":\\n			widget := new _WindowClass(\\n				id: p.get( "id", null ),\\n				title: p.get( "title", "" ),\\n				width: p.get( "width", 800 ),\\n				height: p.get( "height", 600 ),\\n				resizable: p.get( "resizable", true ),\\n				modal: p.get( "modal", false ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n				children: child_widgets,\\n			);\\n		case "VBox":\\n			widget := new _VBoxClass(\\n				id: p.get( "id", null ),\\n				align: p.get( "align", "top" ),\\n				gap: p.get( "gap", 0 ),\\n				padding: p.get( "padding", 0 ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n				children: child_widgets,\\n			);\\n		case "HBox":\\n			widget := new _HBoxClass(\\n				id: p.get( "id", null ),\\n				align: p.get( "align", "left" ),\\n				gap: p.get( "gap", 0 ),\\n				padding: p.get( "padding", 0 ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n				children: child_widgets,\\n			);\\n		case "Frame":\\n			widget := new _FrameClass(\\n				id: p.get( "id", null ),\\n				label: p.get( "label", "" ),\\n				collapsible: p.get( "collapsible", false ),\\n				collapsed: p.get( "collapsed", false ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n				children: child_widgets,\\n			);\\n		case "Label":\\n			widget := Label(\\n				id: p.get( "id", null ),\\n				text: p.get( "text", "" ),\\n				("for"): p.get( "for", null ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n			);\\n		case "Text":\\n			widget := Text(\\n				id: p.get( "id", null ),\\n				value: p.get( "value", "" ),\\n				multiline: p.get( "multiline", false ),\\n				readonly: p.get( "readonly", false ),\\n				wrap: p.get( "wrap", true ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n			);\\n		case "RichText":\\n			widget := RichText(\\n				id: p.get( "id", null ),\\n				value: p.get( "value", "" ),\\n				multiline: p.get( "multiline", true ),\\n				readonly: p.get( "readonly", true ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n			);\\n		case "Image":\\n			widget := Image(\\n				id: p.get( "id", null ),\\n				src: p.get( "src", "" ),\\n				alt: p.get( "alt", "" ),\\n				fit: p.get( "fit", "none" ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n			);\\n		case "Input":\\n			widget := Input(\\n				id: p.get( "id", null ),\\n				value: p.get( "value", "" ),\\n				placeholder: p.get( "placeholder", "" ),\\n				multiline: p.get( "multiline", false ),\\n				readonly: p.get( "readonly", false ),\\n				password: p.get( "password", false ),\\n				required: p.get( "required", false ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n			);\\n		case "DatePicker":\\n			widget := DatePicker(\\n				id: p.get( "id", null ),\\n				value: p.get( "value", null ),\\n				min: p.get( "min", null ),\\n				max: p.get( "max", null ),\\n				first_day_of_week: p.get( "first_day_of_week", 0 ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n			);\\n		case "Checkbox":\\n			widget := Checkbox(\\n				id: p.get( "id", null ),\\n				label: p.get( "label", "" ),\\n				checked: p.get( "checked", false ),\\n				indeterminate: p.get( "indeterminate", false ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n			);\\n		case "Radio":\\n			widget := Radio(\\n				id: p.get( "id", null ),\\n				label: p.get( "label", "" ),\\n				value: p.get( "value", "" ),\\n				group: p.get( "group", null ),\\n				checked: p.get( "checked", false ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n			);\\n		case "RadioGroup":\\n			widget := new _RadioGroupClass(\\n				id: p.get( "id", null ),\\n				name: p.get( "name", "" ),\\n				value: p.get( "value", null ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n				children: child_widgets,\\n			);\\n		case "Select":\\n			widget := Select(\\n				id: p.get( "id", null ),\\n				value: p.get( "value", null ),\\n				multiple: p.get( "multiple", false ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n			);\\n		case "Menu":\\n			widget := new _MenuClass(\\n				id: p.get( "id", null ),\\n				text: p.get( "text", "" ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n				children: child_widgets,\\n			);\\n		case "MenuItem":\\n			widget := MenuItem(\\n				id: p.get( "id", null ),\\n				text: p.get( "text", "" ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n			);\\n		case "Button":\\n			widget := Button(\\n				id: p.get( "id", null ),\\n				text: p.get( "text", "" ),\\n				variant: p.get( "variant", "default" ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n			);\\n		case "Separator":\\n			widget := Separator(\\n				id: p.get( "id", null ),\\n				orientation: p.get( "orientation", "horizontal" ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n			);\\n		case "Slider":\\n			widget := Slider(\\n				id: p.get( "id", null ),\\n				value: p.get( "value", 0 ),\\n				min: p.get( "min", 0 ),\\n				max: p.get( "max", 100 ),\\n				step: p.get( "step", 1 ),\\n				orientation: p.get( "orientation", "horizontal" ),\\n				readonly: p.get( "readonly", false ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n			);\\n		case "Progress":\\n			widget := Progress(\\n				id: p.get( "id", null ),\\n				value: p.get( "value", 0 ),\\n				min: p.get( "min", 0 ),\\n				max: p.get( "max", 100 ),\\n				indeterminate: p.get( "indeterminate", false ),\\n				show_text: p.get( "show_text", false ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n			);\\n		case "Tabs":\\n			widget := new _TabsClass(\\n				id: p.get( "id", null ),\\n				selected: p.get( "selected", null ),\\n				placement: p.get( "placement", "top" ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n				children: child_widgets,\\n			);\\n		case "Tab":\\n			widget := new _TabClass(\\n				id: p.get( "id", null ),\\n				title: p.get( "title", "" ),\\n				value: p.get( "value", "" ),\\n				selected: p.get( "selected", false ),\\n				closable: p.get( "closable", false ),\\n				icon: p.get( "icon", null ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n				children: child_widgets,\\n			);\\n		case "ListView":\\n			widget := ListView(\\n				id: p.get( "id", null ),\\n				selected_index: p.get( "selected_index", null ),\\n				multiple: p.get( "multiple", false ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n			);\\n		case "TreeView":\\n			widget := TreeView(\\n				id: p.get( "id", null ),\\n				selected_path: p.get( "selected_path", [] ),\\n				multiple: p.get( "multiple", false ),\\n				visible: p.get( "visible", true ),\\n				enabled: p.get( "enabled", true ),\\n				disabled: p.get( "disabled", false ),\\n			);\\n		default:\\n			_xml_error(\\n				"GUI_XML_STRUCTURE",\\n				`unsupported GUI XML element \\\'${tag}\\\'`,\\n			);\\n	}\\n\\n	_xml_apply_meta( widget, parsed{meta}, parsed{meta_keys} );\\n	return _xml_apply_style( widget, parsed{style}, parsed{style_keys} );\\n}\\n\\nfunction gui_from_xml ( String xml ) {\\n	return _xml_widget_from_node( XML.parse(xml).documentElement() );\\n}\\n\\nfunction gui_from_xml_file ( path ) {\\n	die "XML.load is denied by runtime policy" if __system__{deny_fs};\\n	from std/io import Path;\\n	let file := path instanceof Path ? path : new Path(path);\\n	return _xml_widget_from_node( XML.load(file).documentElement() );\\n}\\n\\nfunction _xml_tag_for_widget ( Widget widget ) {\\n	if ( widget instanceof _WindowClass ) { return "Window"; }\\n	if ( widget instanceof _VBoxClass ) { return "VBox"; }\\n	if ( widget instanceof _HBoxClass ) { return "HBox"; }\\n	if ( widget instanceof _FrameClass ) { return "Frame"; }\\n	if ( widget instanceof _LabelClass ) { return "Label"; }\\n	if ( widget instanceof _TextClass ) { return "Text"; }\\n	if ( widget instanceof _RichTextClass ) { return "RichText"; }\\n	if ( widget instanceof _ImageClass ) { return "Image"; }\\n	if ( widget instanceof _InputClass ) { return "Input"; }\\n	if ( widget instanceof _DatePickerClass ) { return "DatePicker"; }\\n	if ( widget instanceof _CheckboxClass ) { return "Checkbox"; }\\n	if ( widget instanceof _RadioClass ) { return "Radio"; }\\n	if ( widget instanceof _RadioGroupClass ) { return "RadioGroup"; }\\n	if ( widget instanceof _SelectClass ) { return "Select"; }\\n	if ( widget instanceof _MenuClass ) { return "Menu"; }\\n	if ( widget instanceof _MenuItemClass ) { return "MenuItem"; }\\n	if ( widget instanceof _ButtonClass ) { return "Button"; }\\n	if ( widget instanceof _SeparatorClass ) { return "Separator"; }\\n	if ( widget instanceof _SliderClass ) { return "Slider"; }\\n	if ( widget instanceof _ProgressClass ) { return "Progress"; }\\n	if ( widget instanceof _TabsClass ) { return "Tabs"; }\\n	if ( widget instanceof _TabClass ) { return "Tab"; }\\n	if ( widget instanceof _ListViewClass ) { return "ListView"; }\\n	if ( widget instanceof _TreeViewClass ) { return "TreeView"; }\\n	_xml_error( "GUI_XML_STRUCTURE", "unsupported widget for gui_to_xml" );\\n}\\n\\nfunction _xml_attr ( String name, value ) {\\n	return "" if value \\u2261 null;\\n	return ` ${name}="${escape_xml(value)}"`;\\n}\\n\\nfunction _xml_attr_if ( String name, value, fallback ) {\\n	return "" if value \\u2261 fallback;\\n	return _xml_attr( name, value );\\n}\\n\\nfunction _xml_bool_attr_if ( String name, value, fallback ) {\\n	let normalized := value ? true : false;\\n	let normalized_fallback := fallback ? true : false;\\n	return "" if normalized \\u2261 normalized_fallback;\\n	return _xml_attr( name, normalized ? "true" : "false" );\\n}\\n\\nfunction _xml_attr_nonempty ( String name, value ) {\\n	return "" if value \\u2261 null or value eq "";\\n	return _xml_attr( name, value );\\n}\\n\\nfunction _xml_join_ints ( Array values ) {\\n	let out := [];\\n	for ( let value in values ) {\\n		out.push( "" _ value );\\n	}\\n	return join( ",", out );\\n}\\n\\nfunction _xml_meta_attrs ( Widget widget ) {\\n	// These metadata slots are null or arrays; empty arrays are values.\\n	let keys := widget.meta( "__xml_meta_keys" ) ?: [];\\n	let out := "";\\n	for ( let key in keys ) {\\n		out _= _xml_attr( "meta." _ key, widget.meta(key) );\\n	}\\n	return out;\\n}\\n\\nfunction _xml_style_attrs ( Widget widget ) {\\n	// These metadata slots are null or arrays; empty arrays are values.\\n	let keys := widget.meta( "__xml_style_keys" ) ?: [];\\n	let out := "";\\n	for ( let key in keys ) {\\n		out _= _xml_attr( "style." _ key, widget.style(key) );\\n	}\\n	return out;\\n}\\n\\nfunction _xml_common_attrs ( Widget widget ) {\\n	let out := "";\\n	out _= _xml_attr( "id", widget.id() ) if widget.id() \\u2262 null;\\n	out _= _xml_bool_attr_if( "visible", widget.visible(), true );\\n	out _= _xml_bool_attr_if( "disabled", not widget.enabled(), false );\\n	out _= _xml_meta_attrs(widget);\\n	out _= _xml_style_attrs(widget);\\n	return out;\\n}\\n\\nfunction _xml_widget_attrs ( Widget widget ) {\\n	let out := _xml_common_attrs(widget);\\n	if ( widget instanceof _WindowClass ) {\\n		out _= _xml_attr_if( "title", widget.title(), "" );\\n	}\\n	else if ( widget instanceof _VBoxClass or widget instanceof _HBoxClass ) {\\n		let default_align := widget instanceof _VBoxClass ? "top" : "left";\\n		out _= _xml_attr_if( "align", widget.align(), default_align );\\n		out _= _xml_attr_if( "gap", widget.gap(), 0 );\\n		out _= _xml_attr_if( "padding", widget.padding(), 0 )\\n			unless widget.padding() instanceof Array;\\n	}\\n	else if ( widget instanceof _FrameClass ) {\\n		out _= _xml_attr_if( "label", widget.label(), "" );\\n		out _= _xml_bool_attr_if( "collapsible", widget.collapsible(), false );\\n		out _= _xml_bool_attr_if( "collapsed", widget.collapsed(), false );\\n	}\\n	else if ( widget instanceof _LabelClass ) {\\n		out _= _xml_attr_if( "text", widget.text(), "" );\\n		out _= _xml_attr_nonempty( "for", widget.for_id() );\\n	}\\n	else if ( widget instanceof _TextClass ) {\\n		out _= _xml_attr_if( "value", widget.value(), "" );\\n		out _= _xml_bool_attr_if( "multiline", widget.multiline(), false );\\n		out _= _xml_bool_attr_if( "readonly", widget.readonly(), false );\\n		out _= _xml_bool_attr_if( "wrap", widget.wrap(), true );\\n	}\\n	else if ( widget instanceof _RichTextClass ) {\\n		out _= _xml_attr_if( "value", widget.value(), "" );\\n		out _= _xml_bool_attr_if( "multiline", widget.multiline(), true );\\n		out _= _xml_bool_attr_if( "readonly", widget.readonly(), true );\\n	}\\n	else if ( widget instanceof _ImageClass ) {\\n		out _= _xml_attr_if( "src", widget.src(), "" );\\n		out _= _xml_attr_if( "alt", widget.alt(), "" );\\n		out _= _xml_attr_if( "fit", widget.fit(), "none" );\\n	}\\n	else if ( widget instanceof _InputClass ) {\\n		out _= _xml_attr_if( "value", widget.value(), "" );\\n		out _= _xml_attr_if( "placeholder", widget.placeholder(), "" );\\n		out _= _xml_bool_attr_if( "multiline", widget.multiline(), false );\\n		out _= _xml_bool_attr_if( "readonly", widget.readonly(), false );\\n		out _= _xml_bool_attr_if( "password", widget.password(), false );\\n		out _= _xml_bool_attr_if( "required", widget.required(), false );\\n	}\\n	else if ( widget instanceof _DatePickerClass ) {\\n		out _= _xml_attr( "value", widget.value() );\\n		out _= _xml_attr( "min", widget.min() ) if widget.min() \\u2262 null;\\n		out _= _xml_attr( "max", widget.max() ) if widget.max() \\u2262 null;\\n		out _= _xml_attr_if(\\n			"first_day_of_week",\\n			widget.first_day_of_week(),\\n			0,\\n		);\\n	}\\n	else if ( widget instanceof _CheckboxClass ) {\\n		out _= _xml_attr_if( "label", widget.label(), "" );\\n		out _= _xml_bool_attr_if( "checked", widget.checked(), false );\\n		out _= _xml_bool_attr_if( "indeterminate", widget.indeterminate(), false );\\n	}\\n	else if ( widget instanceof _RadioClass ) {\\n		out _= _xml_attr_if( "label", widget.label(), "" );\\n		out _= _xml_attr_if( "value", widget.value(), "" );\\n		out _= _xml_attr_nonempty( "group", widget.group() );\\n		out _= _xml_bool_attr_if( "checked", widget.checked(), false );\\n	}\\n	else if ( widget instanceof _RadioGroupClass ) {\\n		out _= _xml_attr_if( "name", widget.name(), "" );\\n		out _= _xml_attr( "value", widget.value() ) if widget.value() \\u2262 null;\\n	}\\n	else if ( widget instanceof _SelectClass ) {\\n		out _= _xml_attr( "value", widget.value() ) if widget.value() \\u2262 null;\\n		out _= _xml_bool_attr_if( "multiple", widget.multiple(), false );\\n	}\\n	else if ( widget instanceof _MenuClass ) {\\n		out _= _xml_attr_if( "text", widget.text(), "" );\\n	}\\n	else if ( widget instanceof _MenuItemClass ) {\\n		out _= _xml_attr_if( "text", widget.text(), "" );\\n	}\\n	else if ( widget instanceof _ButtonClass ) {\\n		out _= _xml_attr_if( "text", widget.text(), "" );\\n		out _= _xml_attr_if( "variant", widget.variant(), "default" );\\n	}\\n	else if ( widget instanceof _SeparatorClass ) {\\n		out _= _xml_attr_if( "orientation", widget.orientation(), "horizontal" );\\n	}\\n	else if ( widget instanceof _SliderClass ) {\\n		out _= _xml_attr_if( "value", widget.value(), 0 );\\n		out _= _xml_attr_if( "min", widget.min(), 0 );\\n		out _= _xml_attr_if( "max", widget.max(), 100 );\\n		out _= _xml_attr_if( "step", widget.step(), 1 );\\n		out _= _xml_attr_if( "orientation", widget.orientation(), "horizontal" );\\n		out _= _xml_bool_attr_if( "readonly", widget.readonly(), false );\\n	}\\n	else if ( widget instanceof _ProgressClass ) {\\n		out _= _xml_attr_if( "value", widget.value(), 0 );\\n		out _= _xml_attr_if( "min", widget.min(), 0 );\\n		out _= _xml_attr_if( "max", widget.max(), 100 );\\n		out _= _xml_bool_attr_if( "indeterminate", widget.indeterminate(), false );\\n		out _= _xml_bool_attr_if( "show_text", widget.show_text(), false );\\n	}\\n	else if ( widget instanceof _TabsClass ) {\\n		out _= _xml_attr( "selected", widget.selected() )\\n			if widget.selected() \\u2262 null;\\n		out _= _xml_attr_if( "placement", widget.placement(), "top" );\\n	}\\n	else if ( widget instanceof _TabClass ) {\\n		out _= _xml_attr_if( "title", widget.title(), "" );\\n		out _= _xml_attr_if( "value", widget.value(), "" );\\n		out _= _xml_attr( "icon", widget.icon() ) if widget.icon() \\u2262 null;\\n		out _= _xml_bool_attr_if( "selected", widget.selected(), false );\\n		out _= _xml_bool_attr_if( "closable", widget.closable(), false );\\n	}\\n	else if ( widget instanceof _ListViewClass ) {\\n		out _= _xml_attr( "selected_index", widget.selected_index() )\\n			if widget.selected_index() \\u2262 null;\\n		out _= _xml_bool_attr_if( "multiple", widget.multiple(), false );\\n	}\\n	else if ( widget instanceof _TreeViewClass ) {\\n		let selected_path := widget.selected_path();\\n		out _= _xml_attr( "selected_path", _xml_join_ints(selected_path) )\\n			if selected_path.length() > 0;\\n		out _= _xml_bool_attr_if( "multiple", widget.multiple(), false );\\n	}\\n	return out;\\n}\\n\\nfunction _xml_serialize_widget ( Widget widget, Number depth ) {\\n	let indent := "";\\n	let i := 0;\\n	while ( i < depth ) {\\n		indent _= "\\\\t";\\n		i++;\\n	}\\n\\n	let tag := _xml_tag_for_widget(widget);\\n	let attrs := _xml_widget_attrs(widget);\\n	attrs _= _xml_attr( "xmlns", GUI_XML_NS ) if depth = 0;\\n	let children := widget.children();\\n	if ( children.length() = 0 ) {\\n		return indent _ "<" _ tag _ attrs _ " />";\\n	}\\n\\n	let parts := [];\\n	for ( let child in children ) {\\n		parts.push( _xml_serialize_widget( child, depth + 1 ) );\\n	}\\n\\n	return indent _ "<" _ tag _ attrs _ ">\\\\n"\\n		_ join( "\\\\n", parts )\\n		_ "\\\\n" _ indent _ "</" _ tag _ ">";\\n}\\n\\nfunction gui_to_xml ( Widget root ) {\\n	return _xml_serialize_widget( root, 0 ) _ "\\\\n";\\n}\\n\';\n        virtualFiles["/modules/std/gui/dialogue.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/gui/dialogue - Dialogue helpers.\\n\\n=head1 SYNOPSIS\\n\\n  from std/gui/dialogue import *;\\n\\n  alert("Saved");\\n  let ok := confirm("Continue?");\\n  let name := prompt("Name:", value: "Ada");\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Electron\\nand Browser. It is not supported by zuzu-js on Node.\\n\\n=head1 DESCRIPTION\\n\\nThis module provides convenience dialogue helpers layered on top of the\\nregular C<std/gui> widgets.\\n\\n=head1 EXPORTS\\n\\n=head2 Functions\\n\\n=over\\n\\n=item C<< alert(String message, ... PairList p) >>, C<< alert_window(String message, ... PairList p) >>\\n\\nParameters: C<message> is display text and C<p> contains options.\\nReturns: C<null> for C<alert> or C<Window> for C<alert_window>. Shows or\\nbuilds an alert dialogue.\\n\\n=item C<< confirm(String message, ... PairList p) >>, C<< confirm_window(String message, ... PairList p) >>\\n\\nParameters: C<message> is display text and C<p> contains options.\\nReturns: C<Boolean> for C<confirm> or C<Window> for\\nC<confirm_window>. Shows or builds a confirmation dialogue.\\n\\n=item C<< prompt(String message, ... PairList p) >>, C<< prompt_window(String message, ... PairList p) >>\\n\\nParameters: C<message> is prompt text and C<p> contains options such as\\nC<value>. Returns: C<String> or C<null> for C<prompt>, or C<Window> for\\nC<prompt_window>. Shows or builds a text prompt.\\n\\n=item C<< file_open(... PairList p) >>, C<< file_save(... PairList p) >>\\n\\nParameters: C<p> contains dialogue options. Returns: path value or\\nC<null>. Opens a file selection dialogue.\\n\\n=item C<< directory_open(... PairList p) >>, C<< directory_save(... PairList p) >>\\n\\nParameters: C<p> contains dialogue options. Returns: path value or\\nC<null>. Opens a directory selection dialogue.\\n\\n=item C<< colour_picker(... PairList p) >>\\n\\nParameters: C<p> contains dialogue options. Returns: C<String> or\\nC<null>. Opens a colour picker and returns a normalized colour string.\\n\\n=item C<< file_open_window(... PairList p) >>, C<< file_save_window(... PairList p) >>, C<< directory_open_window(... PairList p) >>, C<< directory_save_window(... PairList p) >>, C<< colour_picker_window(... PairList p) >>\\n\\nParameters: C<p> contains dialogue options. Returns: C<Window>. Builds\\nthe corresponding GUI dialogue window.\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/gui/dialogue >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/gui try import\\n	EM,\\n	Window,\\n	VBox,\\n	HBox,\\n	Label,\\n	Text,\\n	Input,\\n	Button,\\n	Widget,\\n	native_file_open,\\n	native_file_save,\\n	native_directory_open,\\n	native_directory_save,\\n	native_colour_picker;\\nfrom std/gui/objects try import\\n	meta as _objects_meta,\\n	native_alert,\\n	native_confirm,\\n	native_prompt;\\nfrom std/colour import parse_colour;\\nfrom std/string import split;\\nfrom std/tui import\\n	colour_text,\\n	directory_completions,\\n	filename_completions,\\n	readline;\\n\\nfunction _tui_string ( value ) {\\n	return value \\u2261 null ? "" : "" _ value;\\n}\\n\\nfunction _gui_backend () {\\n	if ( _objects_meta \\u2262 null ) {\\n		return _objects_meta{backend};\\n	}\\n	return "";\\n}\\n\\nfunction _path_dialogue_unsupported () {\\n	if ( __system__{deny_fs} ) {\\n		die "GUI_DIALOGUE_FS_DENIED: file and directory dialogues require filesystem capability";\\n	}\\n	if ( _gui_backend() eq "browser-dom" ) {\\n		die "GUI_DIALOGUE_UNSUPPORTED: file and directory dialogues are unsupported in JS/Browser";\\n	}\\n}\\n\\nfunction _tui_prompt ( String message, PairList p, String default_value ) {\\n	return readline(\\n		colour_text( message _ " ", "cyan" ),\\n		default_value,\\n		null,\\n	);\\n}\\n\\nfunction _tui_path_dialog (\\n	String label,\\n	String default_value,\\n	completion,\\n	PairList p\\n) {\\n	let answer := readline(\\n		colour_text( p.get( "label", label ) _ " ", "cyan" ),\\n		_tui_string( p.get( "value", default_value ) ),\\n		completion,\\n	);\\n	if ( p.get( "multiple", false ) ) {\\n		return split( answer, p.get( "separator", "\\\\n" ) );\\n	}\\n	return answer;\\n}\\n\\nfunction _parse_colour_or_null ( value ) {\\n	return try {\\n		parse_colour( _tui_string(value) );\\n	}\\n	catch {\\n		null;\\n	};\\n}\\n\\nfunction _colour_initial_value ( PairList p ) {\\n	let raw := _tui_string( p.get( "value", "#000000" ) );\\n	let parsed := _parse_colour_or_null(raw);\\n	return parsed \\u2262 null ? parsed : raw;\\n}\\n\\nfunction _colour_default_value ( PairList p ) {\\n	// The parser returns null for invalid input; valid colours are values.\\n	return _parse_colour_or_null( p.get( "value", "#000000" ) ) ?: "#000000";\\n}\\n\\nfunction _tui_colour_dialog ( PairList p ) {\\n	let default_value := _colour_default_value(p);\\n	while ( true ) {\\n		let answer := readline(\\n			colour_text( p.get( "label", "Colour:" ) _ " ", "cyan" ),\\n			default_value,\\n			null,\\n		);\\n		let parsed := _parse_colour_or_null(answer);\\n		if ( parsed \\u2262 null ) {\\n			return parsed;\\n		}\\n		say( colour_text( "Invalid colour; try #336699 or red.", "yellow" ) );\\n	}\\n}\\n\\nfunction _dialogue_window (\\n	String kind,\\n	String title,\\n	Widget body,\\n	Array buttons,\\n	PairList p\\n) {\\n	let button_row := HBox(\\n		id: "buttons",\\n		align: "right",\\n		gap: 6,\\n		height: p.get( "button_row_height", 2.125 \\xD7 EM ),\\n		maxheight: p.get( "button_row_height", 2.125 \\xD7 EM ),\\n	);\\n	for ( let button in buttons ) {\\n		button_row.add_child(button);\\n	}\\n	let w := Window(\\n		title: title,\\n		width: p.get( "width", 360 ),\\n		height: p.get( "height", 180 ),\\n		resizable: p.get( "resizable", false ),\\n		modal: true,\\n		VBox(\\n			id: p.get( "id", null ),\\n			gap: p.get( "gap", 8 ),\\n			padding: p.get( "padding", 12 ),\\n			body,\\n			button_row,\\n		),\\n	);\\n	w.meta( "dialogue.kind", kind );\\n	return w;\\n}\\n\\nfunction _message_body ( String message, PairList p ) {\\n	return Text(\\n		id: p.get( "message_id", "message" ),\\n		value: message,\\n		readonly: true,\\n		wrap: true,\\n	);\\n}\\n\\nfunction _primary_button ( PairList p, String fallback ) {\\n	return Button(\\n		id: p.get( "ok_id", "ok" ),\\n		text: p.get( "ok_text", fallback ),\\n		variant: "primary",\\n		width: p.get( "button_width", 5.5 \\xD7 EM ),\\n		height: p.get( "button_height", 1.75 \\xD7 EM ),\\n		maxheight: p.get( "button_height", 1.75 \\xD7 EM ),\\n	);\\n}\\n\\nfunction _cancel_button ( PairList p ) {\\n	return Button(\\n		id: p.get( "cancel_id", "cancel" ),\\n		text: p.get( "cancel_text", "Cancel" ),\\n		width: p.get( "button_width", 5.5 \\xD7 EM ),\\n		height: p.get( "button_height", 1.75 \\xD7 EM ),\\n		maxheight: p.get( "button_height", 1.75 \\xD7 EM ),\\n	);\\n}\\n\\nfunction _alert_window ( String message, PairList p ) {\\n	let ok := _primary_button( p, "OK" );\\n	let w := _dialogue_window(\\n		"alert",\\n		p.get( "title", "Alert" ),\\n		_message_body( message, p ),\\n		[ ok ],\\n		p,\\n	);\\n	ok.click( function () {\\n		w.close(null);\\n	} );\\n	return w;\\n}\\n\\nfunction alert_window ( String message, ... PairList p ) {\\n	return _alert_window( message, p );\\n}\\n\\nfunction alert ( String message, ... PairList p ) {\\n	if ( p.has("auto_result") ) {\\n		return null;\\n	}\\n	if ( __system__{deny_gui} ) {\\n		say( colour_text( message, "yellow" ) );\\n		return null;\\n	}\\n	if ( native_alert \\u2262 null ) {\\n		let native_result := native_alert( message, p );\\n		if ( native_result ) {\\n			return null;\\n		}\\n	}\\n	return _alert_window( message, p ).call();\\n}\\n\\nfunction _confirm_window ( String message, PairList p ) {\\n	let ok := _primary_button( p, p.get( "ok_text", "OK" ) );\\n	let cancel := _cancel_button(p);\\n	let w := _dialogue_window(\\n		"confirm",\\n		p.get( "title", "Confirm" ),\\n		_message_body( message, p ),\\n		[ cancel, ok ],\\n		p,\\n	);\\n	ok.click( function () {\\n		w.close(true);\\n	} );\\n	cancel.click( function () {\\n		w.close(false);\\n	} );\\n	return w;\\n}\\n\\nfunction confirm_window ( String message, ... PairList p ) {\\n	return _confirm_window( message, p );\\n}\\n\\nfunction confirm ( String message, ... PairList p ) {\\n	if ( p.has("auto_result") ) {\\n		return p.get("auto_result") ? true : false;\\n	}\\n	if ( __system__{deny_gui} ) {\\n		let yes_default := p.get( "value", p.get( "default", false ) );\\n		let suffix := yes_default ? " [Y/n] " : " [y/N] ";\\n		let answer := readline(\\n			colour_text( message _ suffix, "cyan" ),\\n			yes_default ? "y" : "n",\\n			null,\\n		);\\n		return ( answer ~ /^(?:y|yes|1|true)$/i ) ? true : false;\\n	}\\n	if ( native_confirm \\u2262 null ) {\\n		let native_result := native_confirm( message, p );\\n		if ( native_result \\u2262 null ) {\\n			return native_result ? true : false;\\n		}\\n	}\\n	return _confirm_window( message, p ).call() ? true : false;\\n}\\n\\nfunction _prompt_window ( String message, PairList p ) {\\n	let input := Input(\\n		id: p.get( "input_id", "value" ),\\n		value: p.get( "value", "" ),\\n		placeholder: p.get( "placeholder", "" ),\\n	);\\n	let ok := _primary_button( p, p.get( "ok_text", "OK" ) );\\n	let cancel := _cancel_button(p);\\n	let w := _dialogue_window(\\n		"prompt",\\n		p.get( "title", "Prompt" ),\\n		VBox(\\n			gap: 6,\\n			_message_body( message, p ),\\n			input,\\n		),\\n		[ cancel, ok ],\\n		p,\\n	);\\n	ok.click( function () {\\n		w.close( input.value() );\\n	} );\\n	cancel.click( function () {\\n		w.close(null);\\n	} );\\n	return w;\\n}\\n\\nfunction prompt_window ( String message, ... PairList p ) {\\n	return _prompt_window( message, p );\\n}\\n\\nfunction prompt ( String message, ... PairList p ) {\\n	if ( p.has("auto_result") ) {\\n		return p.get("auto_result");\\n	}\\n	if ( __system__{deny_gui} ) {\\n		return _tui_prompt(\\n			message,\\n			p,\\n			_tui_string( p.get( "value", "" ) ),\\n		);\\n	}\\n	if ( native_prompt \\u2262 null ) {\\n		let native_result := native_prompt( message, p );\\n		if ( _gui_backend() eq "browser-dom" ) {\\n			return native_result;\\n		}\\n		if ( native_result \\u2262 null ) {\\n			return native_result;\\n		}\\n	}\\n	return _prompt_window( message, p ).call();\\n}\\n\\nfunction _path_dialog_window (\\n	String kind,\\n	String title,\\n	String label,\\n	String default_value,\\n	PairList p\\n) {\\n	let input := Input(\\n		id: p.get( "input_id", "path" ),\\n		value: p.get( "value", default_value ),\\n		placeholder: p.get( "placeholder", "" ),\\n		multiline: p.get( "multiple", false ),\\n	);\\n	let ok := _primary_button( p, p.get( "ok_text", "OK" ) );\\n	let cancel := _cancel_button(p);\\n	let w := _dialogue_window(\\n		kind,\\n		p.get( "title", title ),\\n		VBox(\\n			gap: 6,\\n			Label( text: p.get( "label", label ), ("for"): input.id() ),\\n			input,\\n		),\\n		[ cancel, ok ],\\n		p,\\n	);\\n	ok.click( function () {\\n		if ( p.get( "multiple", false ) ) {\\n			w.close( split( input.value(), p.get( "separator", "\\\\n" ) ) );\\n		}\\n		else {\\n			w.close( input.value() );\\n		}\\n	} );\\n	cancel.click( function () {\\n		w.close(null);\\n	} );\\n	return w;\\n}\\n\\nfunction file_open_window ( ... PairList p ) {\\n	return _path_dialog_window( "file_open", "Open File", "File:", "", p );\\n}\\n\\nfunction file_save_window ( ... PairList p ) {\\n	return _path_dialog_window( "file_save", "Save File", "File:", "", p );\\n}\\n\\nfunction directory_open_window ( ... PairList p ) {\\n	return _path_dialog_window(\\n		"directory_open",\\n		"Open Directory",\\n		"Directory:",\\n		"",\\n		p,\\n	);\\n}\\n\\nfunction directory_save_window ( ... PairList p ) {\\n	return _path_dialog_window(\\n		"directory_save",\\n		"Save Directory",\\n		"Directory:",\\n		"",\\n		p,\\n	);\\n}\\n\\nfunction _colour_picker_window ( PairList p ) {\\n	let input := Input(\\n		id: p.get( "input_id", "path" ),\\n		value: _colour_initial_value(p),\\n		placeholder: p.get( "placeholder", "#336699" ),\\n	);\\n	let ok := _primary_button( p, p.get( "ok_text", "OK" ) );\\n	let cancel := _cancel_button(p);\\n	let default_value := _colour_default_value(p);\\n	let sync_ok := function () {\\n		ok.set_enabled( _parse_colour_or_null( input.value() ) \\u2262 null );\\n	};\\n	let w := _dialogue_window(\\n		"colour_picker",\\n		p.get( "title", "Choose Colour" ),\\n		VBox(\\n			gap: 6,\\n			Label(\\n				text: p.get( "label", "Colour:" ),\\n				("for"): input.id(),\\n			),\\n			input,\\n		),\\n		[ cancel, ok ],\\n		p,\\n	);\\n	sync_ok();\\n	input.on( "change", sync_ok );\\n	ok.click( function () {\\n		let parsed := _parse_colour_or_null( input.value() );\\n		if ( parsed \\u2262 null ) {\\n			w.close(parsed);\\n		}\\n	} );\\n	cancel.click( function () {\\n		w.close(default_value);\\n	} );\\n	return w;\\n}\\n\\nfunction colour_picker_window ( ... PairList p ) {\\n	return _colour_picker_window(p);\\n}\\n\\nfunction file_open ( ... PairList p ) {\\n	_path_dialogue_unsupported();\\n	if ( p.has("auto_result") ) {\\n		return p.get("auto_result");\\n	}\\n	if ( __system__{deny_gui} ) {\\n		return _tui_path_dialog( "File:", "", filename_completions, p );\\n	}\\n	return native_file_open(p);\\n}\\n\\nfunction file_save ( ... PairList p ) {\\n	_path_dialogue_unsupported();\\n	if ( p.has("auto_result") ) {\\n		return p.get("auto_result");\\n	}\\n	if ( __system__{deny_gui} ) {\\n		return _tui_path_dialog( "File:", "", filename_completions, p );\\n	}\\n	return native_file_save(p);\\n}\\n\\nfunction directory_open ( ... PairList p ) {\\n	_path_dialogue_unsupported();\\n	if ( p.has("auto_result") ) {\\n		return p.get("auto_result");\\n	}\\n	if ( __system__{deny_gui} ) {\\n		return _tui_path_dialog(\\n			"Directory:",\\n			"",\\n			directory_completions,\\n			p,\\n		);\\n	}\\n	return native_directory_open(p);\\n}\\n\\nfunction directory_save ( ... PairList p ) {\\n	_path_dialogue_unsupported();\\n	if ( p.has("auto_result") ) {\\n		return p.get("auto_result");\\n	}\\n	if ( __system__{deny_gui} ) {\\n		return _tui_path_dialog(\\n			"Directory:",\\n			"",\\n			directory_completions,\\n			p,\\n		);\\n	}\\n	if ( native_directory_save \\u2262 null ) {\\n		let native_result := native_directory_save(p);\\n		if ( native_result \\u2262 null ) {\\n			return native_result;\\n		}\\n		if ( _gui_backend() eq "electron-dom" ) {\\n			return null;\\n		}\\n	}\\n	return _path_dialog_window(\\n		"directory_save",\\n		"Save Directory",\\n		"Directory:",\\n		"",\\n		p,\\n	).call();\\n}\\n\\nfunction colour_picker ( ... PairList p ) {\\n	if ( p.has("auto_result") ) {\\n		return parse_colour( _tui_string( p.get("auto_result") ) );\\n	}\\n	if ( __system__{deny_gui} ) {\\n		return _tui_colour_dialog(p);\\n	}\\n	if ( native_colour_picker \\u2262 null ) {\\n		let native_result := native_colour_picker(p);\\n		if ( native_result \\u2262 null ) {\\n			return parse_colour(native_result);\\n		}\\n		if ( _gui_backend() eq "browser-dom" ) {\\n			return null;\\n		}\\n	}\\n	if ( _gui_backend() eq "electron-dom" ) {\\n		return _colour_picker_window(p).call();\\n	}\\n	return parse_colour( _colour_picker_window(p).call() );\\n}\\n\';\n        virtualFiles["/modules/std/uuid.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/uuid - Pure ZuzuScript UUID v1 generator.\\n\\n=head1 SYNOPSIS\\n\\n  from std/uuid import create_uuid, create_uuid_binary;\\n\\n  let text := create_uuid();\\n  let raw := create_uuid_binary();\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nThis module implements UUID version 1 generation using only\\nZuzuScript code.\\n\\n=head1 EXPORTS\\n\\n=head2 Functions\\n\\n=over\\n\\n=item * C<create_uuid_binary()>\\n\\nParameters: none. Returns: C<BinaryString>. Returns a single UUID as 16\\nraw bytes.\\n\\n=item * C<create_uuid()>\\n\\nParameters: none. Returns: C<String>. Returns a single UUID as\\nlowercase hexadecimal text with hyphens in the usual C<8-4-4-4-12>\\nlayout.\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/uuid >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/math import Math;\\nfrom std/string import substr;\\nfrom std/string/base64 import decode;\\nfrom std/time import Time;\\n\\nlet _B64_ALPHABET := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";\\nlet _HEX_ALPHABET := "0123456789abcdef";\\n\\nfunction _div_floor ( Number n, Number d ) {\\n	return floor( n / d );\\n}\\n\\nfunction _mod ( Number n, Number d ) {\\n	return n - _div_floor( n, d ) * d;\\n}\\n\\nfunction _rand_int ( Number max ) {\\n	return floor( Math.rand(max) );\\n}\\n\\nfunction _bytes_to_binary ( Array bytes ) {\\n	let out := "";\\n	let i := 0;\\n	let n := bytes.length();\\n\\n	while ( i < n ) {\\n		let b0 := bytes[i];\\n		let b1 := null;\\n		let b2 := null;\\n		if ( i + 1 < n ) {\\n			b1 := bytes[i + 1];\\n		}\\n		if ( i + 2 < n ) {\\n			b2 := bytes[i + 2];\\n		}\\n\\n		let c0 := _div_floor( b0, 4 );\\n		let c1 := _mod( b0, 4 ) * 16;\\n		let c2 := 64;\\n		let c3 := 64;\\n\\n		if ( b1 \\u2262 null ) {\\n			c1 += _div_floor( b1, 16 );\\n			c2 := _mod( b1, 16 ) * 4;\\n			if ( b2 \\u2262 null ) {\\n				c2 += _div_floor( b2, 64 );\\n				c3 := _mod( b2, 64 );\\n			}\\n		}\\n\\n		out _= substr( _B64_ALPHABET, c0, 1 );\\n		out _= substr( _B64_ALPHABET, c1, 1 );\\n		if ( c2 \\u2261 64 ) {\\n			out _= "=";\\n		}\\n		else {\\n			out _= substr( _B64_ALPHABET, c2, 1 );\\n		}\\n		if ( c3 \\u2261 64 ) {\\n			out _= "=";\\n		}\\n		else {\\n			out _= substr( _B64_ALPHABET, c3, 1 );\\n		}\\n\\n		i += 3;\\n	}\\n\\n	return decode(out);\\n}\\n\\nfunction _timestamp_words () {\\n	// Seconds between 1582-10-15 and 1970-01-01.\\n	let epoch_offset := 12219292800;\\n	let seconds := floor( new Time().epoch() ) + epoch_offset;\\n	let ticks := _rand_int(10000000);\\n\\n	let words := [\\n		_mod( seconds, 65536 ),\\n		_mod( _div_floor( seconds, 65536 ), 65536 ),\\n		_mod( _div_floor( seconds, 4294967296 ), 65536 ),\\n		0,\\n		0,\\n	];\\n\\n	let scale := 10000000;\\n	let i := 0;\\n	let carry := 0;\\n	while ( i < words.length() ) {\\n		let product := words[i] * scale + carry;\\n		words[i] := _mod( product, 65536 );\\n		carry := _div_floor( product, 65536 );\\n		i++;\\n	}\\n\\n	let add_i := 0;\\n	let add_carry := ticks;\\n	while ( add_carry > 0 and add_i < words.length() ) {\\n		let sum := words[add_i] + _mod( add_carry, 65536 );\\n		words[add_i] := _mod( sum, 65536 );\\n		add_carry := _div_floor( add_carry, 65536 ) + _div_floor( sum, 65536 );\\n		add_i++;\\n	}\\n\\n	return words;\\n}\\n\\nfunction _create_uuid_bytes () {\\n	let words := _timestamp_words();\\n	let time_low := words[0] + words[1] * 65536;\\n	let time_mid := words[2];\\n	let time_hi_and_version := _mod( words[3], 4096 ) + 4096;\\n\\n	let clock_seq := _rand_int(16384);\\n	let clock_seq_hi_and_reserved := _mod( _div_floor( clock_seq, 256 ), 64 ) + 128;\\n	let clock_seq_low := _mod( clock_seq, 256 );\\n\\n	let node := [];\\n	let j := 0;\\n	while ( j < 6 ) {\\n		node.push( _rand_int(256) );\\n		j++;\\n	}\\n	// Multicast bit set means this is not an IEEE MAC address.\\n	node[0] := node[0] | 1;\\n\\n	return [\\n		_mod( _div_floor( time_low, 16777216 ), 256 ),\\n		_mod( _div_floor( time_low, 65536 ), 256 ),\\n		_mod( _div_floor( time_low, 256 ), 256 ),\\n		_mod( time_low, 256 ),\\n		_mod( _div_floor( time_mid, 256 ), 256 ),\\n		_mod( time_mid, 256 ),\\n		_mod( _div_floor( time_hi_and_version, 256 ), 256 ),\\n		_mod( time_hi_and_version, 256 ),\\n		clock_seq_hi_and_reserved,\\n		clock_seq_low,\\n		node[0],\\n		node[1],\\n		node[2],\\n		node[3],\\n		node[4],\\n		node[5],\\n	];\\n}\\n\\nfunction _byte_to_hex ( Number b ) {\\n	let hi := _div_floor( b, 16 );\\n	let lo := _mod( b, 16 );\\n	return substr( _HEX_ALPHABET, hi, 1 ) _ substr( _HEX_ALPHABET, lo, 1 );\\n}\\n\\nfunction _bytes_to_uuid_text ( Array bytes ) {\\n	let out := "";\\n	let i := 0;\\n	while ( i < 16 ) {\\n		out _= _byte_to_hex( bytes[i] );\\n		if ( i \\u2261 3 or i \\u2261 5 or i \\u2261 7 or i \\u2261 9 ) {\\n			out _= "-";\\n		}\\n		i++;\\n	}\\n	return out;\\n}\\n\\nfunction create_uuid_binary () {\\n	return _bytes_to_binary( _create_uuid_bytes() );\\n}\\n\\nfunction create_uuid () {\\n	return _bytes_to_uuid_text( _create_uuid_bytes() );\\n}\\n\';\n        virtualFiles["/modules/std/dump.zzm"] = `=encoding utf8\n\n=head1 NAME\n\nstd/dump - Structured value dumper for ZuzuScript.\n\n=head1 SYNOPSIS\n\n  from std/dump import Dumper;\n\n  let text := Dumper.dump(\n    { nums: [ 1, 2, 3 ] },\n    { pretty: true, sort_keys: true }\n  );\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module provides a pure-Zuzu C<Dumper> class which serializes\nZuzu values into code-like text.\n\nIf a value cannot be realistically dumped (for example a function),\nC<Dumper> emits a warning and inserts C<null> in that location.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<Dumper>\n\nPure-Zuzu structured value dumper.\n\n=over\n\n=item C<< Dumper.dump(value, options?) >>\n\nParameters: C<value> is any ZuzuScript value and C<options> is an\noptional dictionary. Returns: C<String>. Serializes C<value> into\ncode-like text.\n\n=back\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/dump >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/internals import class_name, object_slots, ansi_esc, ref_id;\nfrom std/string import join, substr;\n\nlet _ANSI_RESET := ansi_esc() _ "[0m";\nlet _ANSI_NUMBER := ansi_esc() _ "[33m";\nlet _ANSI_STRING := ansi_esc() _ "[32m";\nlet _ANSI_BOOL := ansi_esc() _ "[35m";\nlet _ANSI_NULL := ansi_esc() _ "[90m";\nlet _ANSI_PUNC := ansi_esc() _ "[36m";\nlet _ANSI_KEYWORD := ansi_esc() _ "[34m";\n\nfunction _is_true (value) {\n	return value ? true: false;\n}\n\nfunction _warn_unless_quiet ( String msg, Dict cfg ) {\n	warn msg if not cfg{quiet};\n}\n\nfunction _indent_pad ( depth, cfg ) {\n	return "" if not cfg{pretty};\n	let out := "";\n	let i := 0;\n	while ( i < depth ) {\n		out _= "  ";\n		i++;\n	}\n\n	return out;\n}\n\nfunction _colourize ( String text, String tone, Dict cfg ) {\n	return text if not cfg{colour};\n	return tone _ text _ _ANSI_RESET;\n}\n\nfunction _punc ( String text, Dict cfg ) {\n	return _colourize( text, _ANSI_PUNC, cfg );\n}\n\nfunction _quote ( String text, Dict cfg ) {\n	let s := text;\n	s := "" if s \\u2261 null;\n	let out := "";\n	let i := 0;\n	let n := length s;\n\n	while ( i < n ) {\n		let ch := substr( s, i, 1 );\n		if ( ch \\u2261 "\\\\\\\\" ) {\n			out _= "\\\\\\\\\\\\\\\\";\n		}\n		else if ( ch \\u2261 "\\\\"" ) {\n			out _= "\\\\\\\\\\\\"";\n		}\n		else if ( ch \\u2261 "\\\\n" ) {\n			out _= "\\\\\\\\n";\n		}\n		else if ( ch \\u2261 "\\\\r" ) {\n			out _= "\\\\\\\\r";\n		}\n		else if ( ch \\u2261 "\\\\t" ) {\n			out _= "\\\\\\\\t";\n		}\n		else {\n			out _= ch;\n		}\n		i++;\n	}\n\n	return _colourize( "\\\\"" _ out _ "\\\\"", _ANSI_STRING, cfg );\n}\n\nfunction _keys_for ( Dict d, Dict cfg ) {\n	return cfg{sort_keys} ? d.sorted_keys(): d.keys();\n}\n\nfunction _null_literal ( Dict cfg ) {\n	return _colourize( "null", _ANSI_NULL, cfg );\n}\n\nfunction _seen_check_and_mark ( value, String label, Dict cfg, Dict state ) {\n	let id := ref_id(value);\n	if ( id \\u2262 null and state{seen}.exists(id) ) {\n		_warn_unless_quiet( "Dumper: recursive " _ label _ " detected; dumping null", cfg );\n		return true;\n	}\n	if ( id \\u2262 null ) {\n		state{seen}.set( id, true );\n	}\n\n	return false;\n}\n\nfunction _dump_value ( value, Dict cfg, Dict state, Number depth ) {\n	if ( value instanceof Null ) {\n		return _null_literal(cfg);\n	}\n	if ( value instanceof Boolean ) {\n		return _colourize( value ? "true": "false", _ANSI_BOOL, cfg );\n	}\n	if ( value instanceof Number ) {\n		return _colourize( "" _ value, _ANSI_NUMBER, cfg );\n	}\n	if ( value instanceof String ) {\n		return _quote( value, cfg );\n	}\n\n	if ( value instanceof Array ) {\n		return _null_literal(cfg) if _seen_check_and_mark( value, "array", cfg, state );\n		if ( value.length() \\u2261 0 ) {\n			return _punc( "[", cfg ) _ _punc( "]", cfg );\n		}\n		let pretty := cfg{pretty};\n		let sep := pretty ? _punc( ",\\\\n", cfg ): _punc(",", cfg );\n		let parts := [];\n		for ( let item in value ) {\n			parts.push( _dump_value( item, cfg, state, depth + 1 ) );\n		}\n		if ( not pretty ) {\n			return _punc( "[", cfg ) _ join( sep, parts ) _ _punc( "]", cfg );\n		}\n		let inner := [];\n		for ( let p in parts ) {\n			inner.push( _indent_pad( depth + 1, cfg ) _ p );\n		}\n		return _punc( "[\\\\n", cfg ) _ join( sep, inner ) _ _punc( "\\\\n", cfg ) _ _indent_pad( depth, cfg ) _\n		    _punc( "]", cfg );\n	}\n\n	if ( value instanceof Dict ) {\n		return _null_literal(cfg) if _seen_check_and_mark( value, "dict", cfg, state );\n		let keys := _keys_for( value, cfg );\n		if ( keys.length() \\u2261 0 ) {\n			return _punc( "{" , cfg ) _ _punc( "}", cfg );\n		}\n		let pretty := cfg{pretty};\n		let sep := pretty ? _punc( ",\\\\n", cfg ): _punc(",", cfg );\n		let colon := pretty ? _punc( ": ", cfg ): _punc(":", cfg );\n		let entries := [];\n		for ( let key in keys ) {\n			let dumped := _dump_value( value.get(key), cfg, state, depth + 1 );\n			entries.push( _quote( key, cfg ) _ colon _ dumped );\n		}\n		if ( not pretty ) {\n			return _punc( "{" , cfg ) _ join( sep, entries ) _ _punc( "}", cfg );\n		}\n		let inner := [];\n		for ( let e in entries ) {\n			inner.push( _indent_pad( depth + 1, cfg ) _ e );\n		}\n		return _punc( "{\\\\n", cfg ) _ join( sep, inner ) _ _punc( "\\\\n", cfg ) _ _indent_pad( depth, cfg ) _\n		    _punc( "}", cfg );\n	}\n\n	if ( value instanceof PairList ) {\n		return _null_literal(cfg) if _seen_check_and_mark( value, "pairlist", cfg, state );\n		if ( value.empty ) {\n			return _punc( "{{" , cfg ) _ _punc( "}}", cfg );\n		}\n		let pretty := cfg{pretty};\n		let sep := pretty ? _punc( ",\\\\n", cfg ): _punc(",", cfg );\n		let colon := pretty ? _punc( ": ", cfg ): _punc(":", cfg );\n		let entries := [];\n		value.for_each_pair( function (p) {\n			let dumped := _dump_value( p.value, cfg, state, depth + 1 );\n			entries.push( _quote( p.key, cfg ) _ colon _ dumped );\n		} );\n		if ( not pretty ) {\n			return _punc( "{{" , cfg ) _ join( sep, entries ) _ _punc( "}}", cfg );\n		}\n		let inner := [];\n		for ( let e in entries ) {\n			inner.push( _indent_pad( depth + 1, cfg ) _ e );\n		}\n		return _punc( "{{\\\\n", cfg ) _ join( sep, inner ) _ _punc( "\\\\n", cfg ) _ _indent_pad( depth, cfg ) _\n		    _punc( "}}", cfg );\n	}\n\n	if ( value instanceof Set or value instanceof Bag ) {\n		let is_set := value instanceof Set;\n		return _null_literal(cfg)\n			if _seen_check_and_mark( value, is_set ? "set" : "bag", cfg, state );\n		let left := is_set ? "<<": "<<<";\n		let right := is_set ? ">>": ">>>";\n		let sep := cfg{pretty} ? _punc( ", ", cfg ): _punc(",", cfg );\n		let items := [];\n		for ( let item in value ) {\n			items.push( _dump_value( item, cfg, state, depth + 1 ) );\n		}\n		return _punc( left, cfg ) _ join( sep, items ) _ _punc( right, cfg );\n	}\n\n	if ( value instanceof Pair ) {\n		let pair_value := value{pair};\n		if ( not( pair_value instanceof Array ) or pair_value.length() < 2 ) {\n			_warn_unless_quiet( "Dumper: invalid Pair shape; using null", cfg );\n			return _null_literal(cfg);\n		}\n		let first := _dump_value( pair_value[0], cfg, state, depth + 1 );\n		let second := _dump_value( pair_value[1], cfg, state, depth + 1 );\n		let body := _punc( "[", cfg ) _ first _ _punc(",", cfg ) _ second _ _punc( "]", cfg );\n		let kw_new := _colourize( "new", _ANSI_KEYWORD, cfg );\n		return kw_new _ " Pair" _ _punc("(", cfg ) _ "pair" _ _punc(":", cfg ) _ body _ _punc(")", cfg );\n	}\n\n	if (\n		value instanceof Function or\n		value instanceof Class or\n		typeof value \\u2261 "Regexp" or\n		typeof value \\u2261 "Method"\n	) {\n		let t := typeof value;\n		_warn_unless_quiet( "Dumper: value of type \'" _ t _ "\' is not dumpable; using null", cfg, );\n		return _null_literal(cfg);\n	}\n	return _null_literal(cfg) if _seen_check_and_mark( value, "object", cfg, state );\n	let cname := class_name(value);\n	let slots := object_slots(value);\n	if ( cname \\u2261 null or not( slots instanceof Dict ) ) {\n		_warn_unless_quiet( "Dumper: object internals unavailable; dumping null", cfg );\n		return _null_literal(cfg);\n	}\n	let keys := _keys_for( slots, cfg );\n	let colon := cfg{pretty} ? _punc( ": ", cfg ): _punc(":", cfg );\n	let args := [];\n	for ( let key in keys ) {\n		args.push( key _ colon _ _dump_value( slots.get(key), cfg, state, depth + 1 ) );\n	}\n	let kw_new := _colourize( "new", _ANSI_KEYWORD, cfg );\n	if ( args.length() \\u2261 0 ) {\n		return kw_new _ " " _ cname _ _punc( "()", cfg );\n	}\n	if ( not cfg{pretty} ) {\n		return kw_new _ " " _ cname _ _punc("(", cfg ) _ join( _punc(",", cfg ), args ) _ _punc(")", cfg );\n	}\n	let inner := [];\n	for ( let arg in args ) {\n		inner.push( _indent_pad( depth + 1, cfg ) _ arg );\n	}\n	return kw_new _ " " _ cname _ _punc( "(\\\\n", cfg ) _ join( _punc( ",\\\\n", cfg ), inner ) _ _punc( "\\\\n",\n	    cfg ) _ _indent_pad( depth, cfg ) _ _punc(")", cfg );\n}\n\nclass Dumper {\n\n	static method dump ( value, options? ) {\n		let cfg := { pretty: false, sort_keys: false, colour: false, quiet: false };\n		if ( options instanceof Dict ) {\n			cfg{pretty} := _is_true( options{pretty} ) if "pretty" in options;\n			cfg{sort_keys} := _is_true( options{sort_keys} ) if "sort_keys" in options;\n			cfg{colour} := _is_true( options{colour} ) if "colour" in options;\n			cfg{quiet} := _is_true( options{quiet} ) if "quiet" in options;\n		}\n		return _dump_value( value, cfg, { seen: {} }, 0 );\n	}\n\n}\n`;\n        virtualFiles["/modules/std/data/cbor.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/data/cbor - CBOR encoding and decoding for ZuzuScript.\\n\\n=head1 SYNOPSIS\\n\\n  from std/data/cbor import CBOR, TaggedValue;\\n\\n  let codec := new CBOR();\\n  let bytes := codec.encode({ answer: 42 });\\n  let value := codec.decode(bytes);\\n\\n  // Decode CBOR maps to Zuzu PairLists instead of Dicts.\\n  // This preserves key order and allows duplicate keys.\\n  codec := new CBOR( pairlists: true );\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Node and\\nElectron. It is partially supported by zuzu-js in the browser: in-memory\\nCBOR encode/decode coverage passes, but file-backed load/dump coverage is\\nunsupported because browser filesystem capability is unavailable.\\n\\n=head1 DESCRIPTION\\n\\nPure-Zuzu implementation of CBOR (RFC 8949).\\n\\n=head1 EXPORTS\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<< TaggedValue({ tag: Number, value: value }) >>\\n\\nConstructs a tagged CBOR value. Returns: C<TaggedValue>. Stores the CBOR\\ntag number and associated value.\\n\\n=item C<< CBOR({ pairlists?: Boolean }) >>\\n\\nConstructs a CBOR codec. Returns: C<CBOR>. The C<pairlists> option makes\\ndecoded maps return as C<PairList> values instead of C<Dict> values.\\n\\n=over\\n\\n=item C<< codec.encode(value) >>\\n\\nParameters: C<value> is any CBOR-encodable ZuzuScript value. Returns:\\nC<BinaryString>. Encodes C<value> as CBOR bytes.\\n\\n=item C<< codec.encode_binarystring(value) >>\\n\\nAlias for C<codec.encode(value)>.\\n\\n=item C<< codec.decode(BinaryString raw) >>\\n\\nParameters: C<raw> is CBOR data. Returns: value. Decodes CBOR bytes into\\nthe equivalent ZuzuScript value.\\n\\n=item C<< codec.decode_binarystring(BinaryString raw) >>\\n\\nAlias for C<codec.decode(raw)>.\\n\\n=item C<< codec.load(Path path) >>\\n\\nParameters: C<path> is a C<std/io> C<Path>. Returns: value. Reads CBOR\\nbytes from C<path> and decodes them.\\n\\n=item C<< codec.dump(Path path, value) >>\\n\\nParameters: C<path> is a C<std/io> C<Path> and C<value> is any\\nCBOR-encodable value. Returns: C<null>. Encodes C<value> and writes CBOR\\nbytes to C<path>.\\n\\n=back\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/data/cbor >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/string import substr, index;\\nfrom std/string/base64 import encode, decode;\\nfrom std/time import Time;\\n\\n\\nlet _B64_ALPHABET  := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";\\n\\n// Set to "PairList" to return CBOR objects as Zuzu PairLists.\\nlet _DECODE_MAP_AS := "Dict";\\n\\nclass TaggedValue {\\n	let Number tag;\\n	let value;\\n}\\n\\nfunction _div_floor ( Number n, Number d ) {\\n	return floor( n / d ); // fix syntax highlighting\\n}\\n\\nfunction _mod ( Number n, Number d ) {\\n	return n - _div_floor( n, d ) * d;\\n}\\n\\nfunction _bytes_to_binary ( Array bytes ) {\\n	let out := "";\\n	let i := 0;\\n	let n := bytes.length();\\n\\n	while ( i < n ) {\\n		let b0 := bytes[i];\\n		let b1 := null;\\n		let b2 := null;\\n		if ( i + 1 < n ) {\\n			b1 := bytes[i + 1];\\n		}\\n		if ( i + 2 < n ) {\\n			b2 := bytes[i + 2];\\n		}\\n\\n		let c0 := _div_floor( b0, 4 );\\n		let c1 := _mod( b0, 4 ) * 16;\\n		let c2 := 64;\\n		let c3 := 64;\\n\\n		if ( b1 \\u2262 null ) {\\n			c1 += _div_floor( b1, 16 );\\n			c2 := _mod( b1, 16 ) * 4;\\n			if ( b2 \\u2262 null ) {\\n				c2 += _div_floor( b2, 64 );\\n				c3 := _mod( b2, 64 );\\n			}\\n		}\\n\\n		out _= substr( _B64_ALPHABET, c0, 1 );\\n		out _= substr( _B64_ALPHABET, c1, 1 );\\n		if ( c2 \\u2261 64 ) {\\n			out _= "=";\\n		}\\n		else {\\n			out _= substr( _B64_ALPHABET, c2, 1 );\\n		}\\n		if ( c3 \\u2261 64 ) {\\n			out _= "=";\\n		}\\n		else {\\n			out _= substr( _B64_ALPHABET, c3, 1 );\\n		}\\n		i += 3;\\n	}\\n\\n	return decode(out);\\n}\\n\\nfunction _binary_to_bytes ( BinaryString raw ) {\\n	let b64 := encode(raw);\\n	let out := [];\\n	let i := 0;\\n	let n := length b64;\\n\\n	while ( i < n ) {\\n		let c0 := index( _B64_ALPHABET, substr( b64, i, 1 ) );\\n		let c1 := index( _B64_ALPHABET, substr( b64, i + 1, 1 ) );\\n		let ch2 := substr( b64, i + 2, 1 );\\n		let ch3 := substr( b64, i + 3, 1 );\\n		let c2 := -1;\\n		let c3 := -1;\\n		if ( ch2 \\u2262 "=" ) {\\n			c2 := index( _B64_ALPHABET, ch2 );\\n		}\\n		if ( ch3 \\u2262 "=" ) {\\n			c3 := index( _B64_ALPHABET, ch3 );\\n		}\\n\\n		out.push( c0 * 4 + _div_floor( c1, 16 ) );\\n\\n		if ( c2 >= 0 ) {\\n			out.push( _mod( c1, 16 ) * 16 + _div_floor( c2, 4 ) );\\n		}\\n		if ( c3 >= 0 ) {\\n			out.push( _mod( c2, 4 ) * 64 + c3 );\\n		}\\n\\n		i += 4;\\n	}\\n\\n	return out;\\n}\\n\\nfunction _is_int ( value ) {\\n	if ( not( value instanceof Number ) ) {\\n		return false;\\n	}\\n\\n	return _mod( value, 1 ) \\u2261 0;\\n}\\n\\nfunction _emit_uint ( Array out, Number major, Number n ) {\\n	if ( n < 24 ) {\\n		out.push( major * 32 + n );\\n		return;\\n	}\\n	if ( n < 256 ) {\\n		out.push( major * 32 + 24 );\\n		out.push(n);\\n		return;\\n	}\\n	if ( n < 65536 ) {\\n		out.push( major * 32 + 25 );\\n		out.push( _mod( _div_floor( n, 256 ), 256 ) );\\n		out.push( _mod( n, 256 ) );\\n		return;\\n	}\\n	if ( n < 4294967296 ) {\\n		out.push( major * 32 + 26 );\\n		out.push( _mod( _div_floor( n, 16777216 ), 256 ) );\\n		out.push( _mod( _div_floor( n, 65536 ), 256 ) );\\n		out.push( _mod( _div_floor( n, 256 ), 256 ) );\\n		out.push( _mod( n, 256 ) );\\n		return;\\n	}\\n\\n	let hi := _div_floor( n, 4294967296 );\\n	let lo := _mod( n, 4294967296 );\\n	out.push( major * 32 + 27 );\\n	out.push( _mod( _div_floor( hi, 16777216 ), 256 ) );\\n	out.push( _mod( _div_floor( hi, 65536 ), 256 ) );\\n	out.push( _mod( _div_floor( hi, 256 ), 256 ) );\\n	out.push( _mod( hi, 256 ) );\\n	out.push( _mod( _div_floor( lo, 16777216 ), 256 ) );\\n	out.push( _mod( _div_floor( lo, 65536 ), 256 ) );\\n	out.push( _mod( _div_floor( lo, 256 ), 256 ) );\\n	out.push( _mod( lo, 256 ) );\\n}\\n\\nfunction _encode_value ( Array out, value ) {\\n	if ( value \\u2261 null ) {\\n		out.push(246);\\n		return;\\n	}\\n	if ( value \\u2261 true ) {\\n		out.push(245);\\n		return;\\n	}\\n	if ( value \\u2261 false ) {\\n		out.push(244);\\n		return;\\n	}\\n\\n	if ( value instanceof Number ) {\\n		die "CBOR.encode currently supports only integer Number values" if not _is_int(value);\\n		if ( value >= 0 ) {\\n			_emit_uint( out, 0, value );\\n		}\\n		else {\\n			_emit_uint( out, 1, -1 - value );\\n		}\\n		return;\\n	}\\n\\n	if ( value instanceof BinaryString ) {\\n		let b := _binary_to_bytes(value);\\n		_emit_uint( out, 2, b.length() );\\n		let i := 0;\\n		while ( i < b.length() ) {\\n			out.push( b[i] );\\n			i++;\\n		}\\n		return;\\n	}\\n\\n	if ( value instanceof String ) {\\n		let b := _binary_to_bytes( to_binary(value) );\\n		_emit_uint( out, 3, b.length() );\\n		let i := 0;\\n		while ( i < b.length() ) {\\n			out.push( b[i] );\\n			i++;\\n		}\\n		return;\\n	}\\n\\n	if ( value instanceof Array ) {\\n		_emit_uint( out, 4, value.length() );\\n		let i := 0;\\n		while ( i < value.length() ) {\\n			_encode_value( out, value[i] );\\n			i++;\\n		}\\n		return;\\n	}\\n\\n	if ( value instanceof Set ) {\\n		_emit_uint( out, 6, 258 );\\n		_encode_value( out, value.sortstr() );\\n		return;\\n	}\\n\\n	if ( value instanceof Bag ) {\\n		_encode_value( out, value.sortstr() );\\n		return;\\n	}\\n\\n	if ( value instanceof PairList ) {\\n		let pairs := value.to_Array();\\n		_emit_uint( out, 5, pairs.length() );\\n		let i := 0;\\n		while ( i < pairs.length() ) {\\n			let pair := pairs[i]{pair};\\n			_encode_value( out, pair[0] );\\n			_encode_value( out, pair[1] );\\n			i++;\\n		}\\n		return;\\n	}\\n\\n	if ( value instanceof Dict ) {\\n		let keys := value.sorted_keys();\\n		_emit_uint( out, 5, keys.length() );\\n		let i := 0;\\n		while ( i < keys.length() ) {\\n			let k := keys[i];\\n			_encode_value( out, k );\\n			_encode_value( out, value.get(k) );\\n			i++;\\n		}\\n		return;\\n	}\\n\\n	if ( value instanceof TaggedValue ) {\\n		_emit_uint( out, 6, value { tag } );\\n		_encode_value( out, value { value } );\\n		return;\\n	}\\n	if ( value instanceof Time ) {\\n		_emit_uint( out, 6, 0 );\\n		_encode_value( out, value.epoch() );\\n		return;\\n	}\\n\\n	die `CBOR cannot encode value of type ${typeof value}`;\\n}\\n\\nfunction _read_uint ( Array bytes, Number ai, Number pos ) {\\n	if ( ai < 24 ) {\\n		return [ ai, pos ];\\n	}\\n	if ( ai \\u2261 24 ) {\\n		return [ bytes[pos], pos + 1 ];\\n	}\\n	if ( ai \\u2261 25 ) {\\n		return [ bytes[pos] * 256 + bytes[pos + 1], pos + 2 ];\\n	}\\n	if ( ai \\u2261 26 ) {\\n		return [ bytes[pos] * 16777216 + bytes[pos + 1] * 65536 + bytes[pos + 2] * 256 + bytes[pos + 3], pos + 4 ];\\n	}\\n	if ( ai \\u2261 27 ) {\\n		let hi := bytes[pos] * 16777216 + bytes[pos + 1] * 65536 + bytes[pos + 2] * 256 + bytes[pos + 3];\\n		let lo := bytes[pos + 4] * 16777216 + bytes[pos + 5] * 65536 + bytes[pos + 6] * 256 + bytes[pos + 7];\\n		return [ hi * 4294967296 + lo, pos + 8 ];\\n	}\\n\\n	die `Unsupported CBOR additional info: ${ai}`;\\n}\\n\\nfunction _decode_at ( Array bytes, Number pos ) {\\n	let head := bytes[pos];\\n	let major := _div_floor( head, 32 );\\n	let ai := _mod( head, 32 );\\n	let parsed := _read_uint( bytes, ai, pos + 1 );\\n	let arg := parsed[0];\\n	let p := parsed[1];\\n\\n	if ( major \\u2261 0 ) {\\n		return [ arg, p ];\\n	}\\n	if ( major \\u2261 1 ) {\\n		return [ -1 - arg, p ];\\n	}\\n	if ( major \\u2261 2 ) {\\n		let chunk := [];\\n		let i := 0;\\n		while ( i < arg ) {\\n			chunk.push( bytes[p + i] );\\n			i++;\\n		}\\n		return [ _bytes_to_binary(chunk), p + arg ];\\n	}\\n	if ( major \\u2261 3 ) {\\n		let chunk := [];\\n		let i := 0;\\n		while ( i < arg ) {\\n			chunk.push( bytes[p + i] );\\n			i++;\\n		}\\n		return [ to_string( _bytes_to_binary(chunk) ), p + arg ];\\n	}\\n	if ( major \\u2261 4 ) {\\n		let arr := [];\\n		let i := 0;\\n		let q := p;\\n		while ( i < arg ) {\\n			let item := _decode_at( bytes, q );\\n			arr.push( item[0] );\\n			q := item[1];\\n			i++;\\n		}\\n		return [ arr, q ];\\n	}\\n	if ( major \\u2261 5 ) {\\n		let d := _DECODE_MAP_AS eq "PairList" ? new PairList() : new Dict();\\n		let i := 0;\\n		let q := p;\\n		while ( i < arg ) {\\n			let k := _decode_at( bytes, q );\\n			let v := _decode_at( bytes, k[1] );\\n			d.add( k[0], v[0] ) unless _DECODE_MAP_AS eq "Dict" and d.exists( k[0] );\\n			q := v[1];\\n			i++;\\n		}\\n		return [ d, q ];\\n	}\\n	if ( major \\u2261 6 ) {\\n		let tagged := _decode_at( bytes, p );\\n		if ( arg \\u2261 0 and tagged[0] instanceof Number ) {\\n			return [ new Time( tagged[0] ), tagged[1] ];\\n		}\\n		if ( arg \\u2261 258 and tagged[0] instanceof Array ) {\\n			return [ tagged[0].to_Set(), tagged[1] ];\\n		}\\n		return [ new TaggedValue( tag: arg, value: tagged[0] ), tagged[1] ];\\n	}\\n	if ( major \\u2261 7 ) {\\n		if ( ai \\u2261 20 ) {\\n			return [ false, pos + 1 ];\\n		}\\n		if ( ai \\u2261 21 ) {\\n			return [ true, pos + 1 ];\\n		}\\n		if ( ai \\u2261 22 ) {\\n			return [ null, pos + 1 ];\\n		}\\n		die `Unsupported CBOR simple/float value (ai=${ai})`;\\n	}\\n\\n	die `Unsupported CBOR major type: ${major}`;\\n}\\n\\nclass CBOR {\\n	let pairlists := false;\\n\\n	method encode ( value ) {\\n		let out := [];\\n		_encode_value( out, value );\\n		return _bytes_to_binary(out);\\n	}\\n\\n	method encode_binarystring ( value ) {\\n		return self.encode(value);\\n	}\\n\\n	method decode ( BinaryString raw ) {\\n		_DECODE_MAP_AS := pairlists ? "PairList" : "Dict";\\n		let bytes := _binary_to_bytes(raw);\\n		let parsed := _decode_at( bytes, 0 );\\n		die "Trailing bytes after CBOR value" if parsed[1] < bytes.length();\\n		return parsed[0];\\n	}\\n\\n	method decode_binarystring ( BinaryString raw ) {\\n		return self.decode(raw);\\n	}\\n\\n	method load ( path ) {\\n		from std/io import Path;\\n		die "CBOR.load is denied by runtime policy" if __system__{deny_fs};\\n		die "CBOR.load expects a std/io Path object" if not( path instanceof Path );\\n		return self.decode( path.slurp() );\\n	}\\n\\n	method dump ( path, value ) {\\n		from std/io import Path;\\n		die "CBOR.dump is denied by runtime policy" if __system__{deny_fs};\\n		die "CBOR.dump expects a std/io Path object" if not( path instanceof Path );\\n		path.spew( self.encode(value) );\\n		return path;\\n	}\\n}\\n\';\n        virtualFiles["/modules/std/data/kdl.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/data/kdl - KDL parsing and serialization for ZuzuScript.\\n\\n=head1 SYNOPSIS\\n\\n  from std/data/kdl import KDL;\\n\\n  let kdl := new KDL();\\n  let doc := kdl.decode("""\\n    package name="zuzu" { version "0.1.0" }\\n  """);\\n  let text := kdl.encode(doc);\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Node and\\nElectron. It is partially supported by zuzu-js in the browser: in-memory\\nKDL parsing and serialization coverage passes, but fixture and load/dump\\ncoverage is unsupported because browser filesystem capability is\\nunavailable.\\n\\n=head1 DESCRIPTION\\n\\nThis module provides a pure-Zuzu implementation of the KDL document\\nmodel and parser, with a user-facing API modelled on C<std/data/json>.\\n\\n=head1 EXPORTS\\n\\nThe parser returns explicit KDL model objects rather than generic Dict\\nand Array structures.\\n\\n=head2 C<KDLDocument>\\n\\nC<KDLDocument> represents a complete parsed KDL document.\\n\\nConstructor fields:\\n\\n=over\\n\\n=item * C<nodes>\\n\\nAn Array of top-level C<KDLNode> objects. Defaults to an empty Array.\\n\\n=back\\n\\nMethods:\\n\\n=over\\n\\n=item C<nodes()>\\n\\nParameters: none. Returns: C<Array>. Returns the Array of top-level\\nC<KDLNode> objects.\\n\\n=item C<to_Iterator()>\\n\\nParameters: none. Returns: C<Function>. Returns an iterator over the\\ndocument\\\'s top-level nodes.\\n\\n=back\\n\\n=head2 C<KDLNode>\\n\\nC<KDLNode> represents one KDL node.\\n\\nConstructor fields:\\n\\n=over\\n\\n=item * C<name>\\n\\nThe node name as a String.\\n\\n=item * C<type_annotation>\\n\\nThe node type annotation as a String, or C<null> when unannotated.\\n\\n=item * C<args>\\n\\nAn Array of unnamed argument C<KDLValue> objects. Defaults to an empty\\nArray.\\n\\n=item * C<props>\\n\\nA C<PairList> mapping property names to C<KDLValue> objects. Defaults\\nto an empty C<PairList>, and preserves duplicate property names.\\n\\n=item * C<children>\\n\\nAn Array of child C<KDLNode> objects. Defaults to an empty Array.\\n\\n=back\\n\\nMethods:\\n\\n=over\\n\\n=item C<name()>\\n\\nParameters: none. Returns: C<String>. Returns the node name.\\n\\n=item C<type_annotation()>\\n\\nParameters: none. Returns: C<String> or C<null>. Returns the node type\\nannotation.\\n\\n=item C<args()>\\n\\nParameters: none. Returns: C<Array>. Returns the unnamed argument\\nC<KDLValue> objects.\\n\\n=item C<props()>\\n\\nParameters: none. Returns: C<PairList>. Returns the named property\\nC<KDLValue> objects.\\n\\n=item C<children()>\\n\\nParameters: none. Returns: C<Array>. Returns the child C<KDLNode>\\nobjects.\\n\\n=item C<to_Iterator()>\\n\\nParameters: none. Returns: C<Function>. Returns an iterator over the\\nnode\\\'s arguments followed by its child nodes.\\n\\n=back\\n\\n=head2 C<KDLValue>\\n\\nC<KDLValue> represents an unnamed argument or named property value.\\n\\nConstructor fields:\\n\\n=over\\n\\n=item * C<type>\\n\\nThe KDL value type: C<null>, C<boolean>, C<number>, or C<string>.\\nSome conversion helpers may create opaque C<KDLValue> objects with\\nother type names; those are not KDL primitives.\\n\\n=item * C<kind>\\n\\nFor numbers, one of C<integer>, C<float>, or C<string>. C<string> is\\nused for KDL number keywords such as C<#inf> that do not have a native\\nJSON-like numeric value.\\n\\n=item * C<value>\\n\\nThe raw native value.\\n\\n=item * C<type_annotation>\\n\\nThe value type annotation as a String, or C<null> when unannotated.\\n\\n=item * C<canonical_number>\\n\\nThe canonical numeric spelling used by canonical serialization, or\\nC<null>.\\n\\n=back\\n\\nMethods:\\n\\n=over\\n\\n=item C<type()>\\n\\nParameters: none. Returns: C<String>. Returns the value type.\\n\\n=item C<kind()>\\n\\nParameters: none. Returns: C<String> or C<null>. Returns the numeric\\nkind for number values.\\n\\n=item C<value()>\\n\\nParameters: none. Returns: value. Returns the raw native value.\\n\\n=item C<type_annotation()>\\n\\nParameters: none. Returns: C<String> or C<null>. Returns the value type\\nannotation.\\n\\n=item C<canonical_number()>\\n\\nParameters: none. Returns: C<String> or C<null>. Returns the canonical\\nnumeric spelling.\\n\\n=item C<is_null()>, C<is_boolean()>, C<is_number()>, C<is_string()>\\n\\nParameters: none. Returns: C<Boolean>. Predicate methods for the four\\nKDL primitive value types.\\n\\n=item C<is_true()>, C<is_false()>\\n\\nParameters: none. Returns: C<Boolean>. Predicate methods for boolean\\nC<#true> and C<#false> values.\\n\\n=item C<to_Number()>\\n\\nParameters: none. Returns: C<Number>. Returns the native number, or\\nthrows when the value is not a finite native number.\\n\\n=item C<to_String()>\\n\\nParameters: none. Returns: C<String>. Coerces the value to a string.\\n\\n=item C<to_Boolean()>\\n\\nParameters: none. Returns: C<Boolean>. Coerces the value to a boolean.\\n\\n=item C<native_value()>\\n\\nParameters: none. Returns: value. Returns the raw native value, with KDL\\nC<#null> represented as C<null>.\\n\\n=back\\n\\n=head2 C<KDL>\\n\\nC<KDL> is the codec class for KDL text.\\n\\n=over\\n\\n=item C<< codec.decode(String text) >>\\n\\nParameters: C<text> is KDL text. Returns: C<KDLDocument>. Parses KDL\\ntext.\\n\\n=item C<< codec.decode_binarystring(BinaryString bytes) >>\\n\\nParameters: C<bytes> is UTF-8 KDL bytes. Returns: C<KDLDocument>.\\nParses KDL bytes.\\n\\n=item C<< codec.encode(value) >>\\n\\nParameters: C<value> is a C<KDLDocument>, C<KDLNode>, or compatible\\nvalue. Returns: C<String>. Serializes KDL data to text.\\n\\n=item C<< codec.encode_binarystring(value) >>\\n\\nParameters: C<value> is a C<KDLDocument>, C<KDLNode>, or compatible\\nvalue. Returns: C<BinaryString>. Serializes KDL data to UTF-8 bytes.\\n\\n=item C<< codec.load(path) >>\\n\\nParameters: C<path> is a C<std/io> C<Path>. Returns: C<KDLDocument>.\\nReads and parses a KDL file.\\n\\n=item C<< codec.dump(path, value) >>\\n\\nParameters: C<path> is a C<std/io> C<Path> and C<value> is KDL data.\\nReturns: C<null>. Serializes and writes a KDL file.\\n\\n=back\\n\\n=head1 ZPATH\\n\\nC<KDLDocument>, C<KDLNode>, and C<KDLValue> objects can be queried with\\nC<std/path/z>. A KDL document\\\'s top-level nodes are exposed as children.\\nA KDL node exposes its arguments first, then its child nodes, as ZPath\\nchildren. KDL properties are exposed as ZPath attributes.\\n\\n  from std/data/kdl import KDL;\\n  from std/path/z import ZPath;\\n\\n  let doc := ( new KDL() ).decode( """\\n  (pkg)package "zuzu" (email)"dev@example.test" version="0.1.0" {\\n    foo "first"\\n    bar "middle"\\n    foo "second"\\n    foo "third"\\n  }\\n  """ );\\n\\n  // The package node\\\'s first child is its first argument.\\n  say( ( new ZPath( path: "/package/#0" ) ).first(doc) );       // zuzu\\n\\n  // Properties are attributes.\\n  say( ( new ZPath( path: "/package/@version" ) ).first(doc) ); // 0.1.0\\n\\n  // Child nodes can be selected by name and zero-based occurrence.\\n  say( ( new ZPath( path: "/package/foo#2/#0" ) ).first(doc) ); // third\\n\\n  // tag() exposes type annotations on nodes and values.\\n  say( ( new ZPath( path: "tag(/package)" ) ).first(doc) );     // pkg\\n  say( ( new ZPath( path: "tag(/package/#1)" ) ).first(doc) );  // email\\n\\n  // local-name() exposes the node name, like it does for XML elements.\\n  say( ( new ZPath( path: "local-name(/package)" ) ).first(doc) );\\n  say( ( new ZPath( path: "/package/foo#2/local-name()" ) ).first(doc) );\\n\\n=head1 COMPATIBILITY\\n\\nThe parser is recursive descent and covers the usual KDL 2.0 document\\nmodel: nodes, arguments, properties, annotations, comments, slashdash,\\nstrings, booleans, nulls, numbers, and children.\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/data/kdl >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/string import substr, index, chr, ord, sprint;\\n\\n\\nfunction _kdl_starts_with ( String text, Number pos, String prefix ) {\\n	return substr( text, pos, length prefix ) \\u2261 prefix;\\n}\\n\\nfunction _kdl_is_newline ( String ch ) {\\n	return ch \\u2261 "\\\\n" or ch \\u2261 "\\\\r" or ch \\u2261 chr(11)\\n		or ch \\u2261 chr(133) or ch \\u2261 chr(8232) or ch \\u2261 chr(8233);\\n}\\n\\nfunction _kdl_is_ws ( String ch ) {\\n	return false if ch \\u2261 "";\\n	let code := ord(ch);\\n	return ch \\u2261 " " or ch \\u2261 "\\\\t" or ch \\u2261 chr(12)\\n		or code \\u2261 160 or code \\u2261 5760 or code \\u2261 8239\\n		or code \\u2261 8287 or code \\u2261 12288\\n		or ( code >= 8192 and code <= 8202 );\\n}\\n\\nfunction _kdl_is_line_space ( String ch ) {\\n	return _kdl_is_ws(ch) or _kdl_is_newline(ch);\\n}\\n\\nfunction _kdl_is_digit ( String ch ) {\\n	return ch ~ /^[0-9]$/;\\n}\\n\\nfunction _kdl_is_hex_digit ( String ch ) {\\n	return ch ~ /^[0-9a-fA-F]$/;\\n}\\n\\nfunction _kdl_hex_value ( String ch ) {\\n	if ( _kdl_is_digit(ch) ) {\\n		return ch + 0;\\n	}\\n	if ( index( "abcdef", ch ) >= 0 ) {\\n		return 10 + index( "abcdef", ch );\\n	}\\n	if ( index( "ABCDEF", ch ) >= 0 ) {\\n		return 10 + index( "ABCDEF", ch );\\n	}\\n	die `Invalid hexadecimal digit \\\'${ch}\\\'`;\\n}\\n\\nfunction _kdl_from_hex ( String raw ) {\\n	let n := 0;\\n	let i := 0;\\n	while ( i < length raw ) {\\n		n := n * 16 + _kdl_hex_value( substr( raw, i, 1 ) );\\n		i++;\\n	}\\n	return n;\\n}\\n\\nfunction _kdl_clean_number ( String token ) {\\n	let out := "";\\n	let i := 0;\\n	while ( i < length token ) {\\n		let ch := substr( token, i, 1 );\\n		out _= ch if ch \\u2262 "_";\\n		i++;\\n	}\\n	return out;\\n}\\n\\nfunction _kdl_parse_radix ( String token, Number radix ) {\\n	let sign := 1;\\n	let i := 0;\\n	if ( substr( token, 0, 1 ) \\u2261 "-" ) {\\n		sign := -1;\\n		i := 1;\\n	}\\n	else if ( substr( token, 0, 1 ) \\u2261 "+" ) {\\n		i := 1;\\n	}\\n	i += 2;\\n\\n	let n := 0;\\n	while ( i < length token ) {\\n		let ch := substr( token, i, 1 );\\n		if ( ch \\u2262 "_" ) {\\n			let v := radix \\u2261 16 ? _kdl_hex_value(ch) : ch + 0;\\n			die `Invalid digit \\\'${ch}\\\' for radix ${radix}` if v >= radix;\\n			n := n * radix + v;\\n		}\\n		i++;\\n	}\\n	return sign * n;\\n}\\n\\nfunction _kdl_strip_decimal_zeroes ( String raw ) {\\n	let i := 0;\\n	while ( i < length raw - 1 and substr( raw, i, 1 ) \\u2261 "0" ) {\\n		i++;\\n	}\\n	return substr( raw, i, length raw - i );\\n}\\n\\nfunction _kdl_decimal_mul_add ( String raw, Number factor, Number add ) {\\n	let out := "";\\n	let carry := add;\\n	let i := length raw - 1;\\n	while ( i >= 0 ) {\\n		let n := ( substr( raw, i, 1 ) + 0 ) * factor + carry;\\n		out := "" _ ( n mod 10 ) _ out;\\n		carry := floor( n / 10 );\\n		i--;\\n	}\\n	while ( carry > 0 ) {\\n		out := "" _ ( carry mod 10 ) _ out;\\n		carry := floor( carry / 10 );\\n	}\\n	return _kdl_strip_decimal_zeroes(out);\\n}\\n\\nfunction _kdl_decimal_from_radix ( String token, Number radix ) {\\n	let sign := "";\\n	let i := 0;\\n	if ( substr( token, 0, 1 ) \\u2261 "-" ) {\\n		sign := "-";\\n		i := 1;\\n	}\\n	else if ( substr( token, 0, 1 ) \\u2261 "+" ) {\\n		i := 1;\\n	}\\n	i += 2;\\n\\n	let out := "0";\\n	while ( i < length token ) {\\n		out := _kdl_decimal_mul_add(\\n			out,\\n			radix,\\n			_kdl_hex_value( substr( token, i, 1 ) ),\\n		);\\n		i++;\\n	}\\n	return sign _ out if sign \\u2262 "" and out \\u2262 "0";\\n	return out;\\n}\\n\\nfunction _kdl_canonical_decimal_int ( String token ) {\\n	let sign := "";\\n	let i := 0;\\n	if ( substr( token, 0, 1 ) \\u2261 "-" ) {\\n		sign := "-";\\n		i := 1;\\n	}\\n	else if ( substr( token, 0, 1 ) \\u2261 "+" ) {\\n		i := 1;\\n	}\\n	let body := _kdl_strip_decimal_zeroes(\\n		substr( token, i, length token - i )\\n	);\\n	return sign _ body if sign \\u2262 "" and body \\u2262 "0";\\n	return body;\\n}\\n\\nfunction _kdl_canonical_float ( String token ) {\\n	let epos := index( token, "e" );\\n	epos := index( token, "E" ) if epos < 0;\\n	return token if epos < 0;\\n\\n	let mantissa := substr( token, 0, epos );\\n	let exponent := substr( token, epos + 1, length token - epos - 1 );\\n	if ( substr( exponent, 0, 1 ) \\u2262 "+"\\n		and substr( exponent, 0, 1 ) \\u2262 "-"\\n	) {\\n		exponent := "+" _ exponent;\\n	}\\n	return mantissa _ "E" _ exponent;\\n}\\n\\nfunction _kdl_find_multiline_close (\\n	String text,\\n	String close,\\n	Number start,\\n	Boolean raw,\\n) {\\n	let found := index( text, close, start );\\n	while ( found >= 0 ) {\\n		if ( raw or found = 0 or substr( text, found - 1, 1 ) \\u2262 "\\\\\\\\" ) {\\n			return found;\\n		}\\n		found := index( text, close, found + 1 );\\n	}\\n	return -1;\\n}\\n\\nfunction _kdl_reserved_ident ( String text ) {\\n	return text \\u2261 "true" or text \\u2261 "false" or text \\u2261 "null"\\n		or text \\u2261 "inf" or text \\u2261 "-inf" or text \\u2261 "nan";\\n}\\n\\nfunction _kdl_ident_break ( String ch ) {\\n	return ch \\u2261 "" or _kdl_is_line_space(ch)\\n		or ch \\u2261 "\\\\\\\\" or ch \\u2261 "/" or ch \\u2261 "(" or ch \\u2261 ")"\\n		or ch \\u2261 "{" or ch \\u2261 "}" or ch \\u2261 ";" or ch \\u2261 "["\\n		or ch \\u2261 "]" or ch \\u2261 "\\\\"" or ch \\u2261 "#" or ch \\u2261 "=";\\n}\\n\\nfunction _kdl_forbidden_codepoint ( Number code ) {\\n	return code < 32 or code \\u2261 127 or code \\u2261 65279\\n		or code \\u2261 8206 or code \\u2261 8207\\n		or ( code >= 8234 and code <= 8238 )\\n		or ( code >= 8294 and code <= 8297 );\\n}\\n\\nfunction _kdl_is_plain_ident ( String text ) {\\n	if ( text \\u2261 "" or _kdl_reserved_ident(text) ) {\\n		return false;\\n	}\\n	let first := substr( text, 0, 1 );\\n	let second := substr( text, 1, 1 );\\n	if ( _kdl_is_digit(first) ) {\\n		return false;\\n	}\\n	if ( ( first \\u2261 "+" or first \\u2261 "-" ) and _kdl_is_digit(second) ) {\\n		return false;\\n	}\\n	if ( first \\u2261 "." and _kdl_is_digit(second) ) {\\n		return false;\\n	}\\n	let i := 0;\\n	while ( i < length text ) {\\n		return false if _kdl_ident_break( substr( text, i, 1 ) );\\n		i++;\\n	}\\n	return true;\\n}\\n\\nfunction _kdl_escape_string ( String text ) {\\n	let out := "";\\n	let i := 0;\\n	while ( i < length text ) {\\n		let ch := substr( text, i, 1 );\\n		if ( ch \\u2261 "\\\\\\\\" ) { out _= "\\\\\\\\\\\\\\\\"; }\\n		else if ( ch \\u2261 "\\\\"" ) { out _= "\\\\\\\\\\\\""; }\\n		else if ( ch \\u2261 chr(8) ) { out _= "\\\\\\\\b"; }\\n		else if ( ch \\u2261 chr(12) ) { out _= "\\\\\\\\f"; }\\n		else if ( ch \\u2261 "\\\\n" ) { out _= "\\\\\\\\n"; }\\n		else if ( ch \\u2261 "\\\\r" ) { out _= "\\\\\\\\r"; }\\n		else if ( ch \\u2261 "\\\\t" ) { out _= "\\\\\\\\t"; }\\n		else if ( ord(ch) < 32 ) {\\n			out _= "\\\\\\\\u{" _ sprint( "%x", ord(ch) ) _ "}";\\n		}\\n		else { out _= ch; }\\n		i++;\\n	}\\n	return out;\\n}\\n\\nfunction _kdl_name ( String text ) {\\n	return _kdl_is_plain_ident(text) ? text : `"${_kdl_escape_string(text)}"`;\\n}\\n\\nfunction _kdl_indent ( Number level, Boolean canonical := false ) {\\n	let out := "";\\n	let i := 0;\\n	let unit := canonical ? "    " : "\\\\t";\\n	while ( i < level ) {\\n		out _= unit;\\n		i++;\\n	}\\n	return out;\\n}\\n\\nfunction _kdl_canonical_props ( PairList props ) {\\n	let latest := {};\\n	for ( let pair in props.to_Array() ) {\\n		let kv := pair{pair};\\n		latest{(kv[0])} := kv[1];\\n	}\\n\\n	let out := [];\\n	for ( let key in latest.sorted_keys() ) {\\n		out.push( [ key, latest{(key)} ] );\\n	}\\n	return out;\\n}\\n\\nclass KDLValue {\\n	let String type := "null";\\n	let kind := null;\\n	let value := null;\\n	let type_annotation := null;\\n	let canonical_number := null;\\n\\n	method type () { return type; }\\n	method kind () { return kind; }\\n	method value () { return value; }\\n	method type_annotation () { return type_annotation; }\\n	method canonical_number () { return canonical_number; }\\n\\n	method is_null () { return type \\u2261 "null"; }\\n	method is_boolean () { return type \\u2261 "boolean"; }\\n	method is_number () { return type \\u2261 "number"; }\\n	method is_string () { return type \\u2261 "string"; }\\n	method is_true () { return type \\u2261 "boolean" and value; }\\n	method is_false () { return type \\u2261 "boolean" and not value; }\\n\\n	method to_Number () {\\n		die "KDLValue is not a number" if type \\u2262 "number";\\n		die "KDL keyword number has no native numeric value" if kind \\u2261 "string";\\n		return value;\\n	}\\n\\n	method to_String () {\\n		return "" if type \\u2261 "null";\\n		return "" _ value;\\n	}\\n\\n	method to_Boolean () {\\n		if ( type \\u2261 "boolean" ) { return value; }\\n		if ( type \\u2261 "null" ) { return false; }\\n		if ( type \\u2261 "number" ) {\\n			return kind \\u2262 "string" and value \\u2262 0;\\n		}\\n		return value \\u2262 "";\\n	}\\n\\n	method native_value () {\\n		return null if type \\u2261 "null";\\n		return value;\\n	}\\n}\\n\\nclass KDLNode {\\n	let name := "";\\n	let type_annotation := null;\\n	let args := [];\\n	let props := null;\\n	let children := [];\\n\\n	method __build__ () {\\n		props := new PairList() if props \\u2261 null;\\n		args := [] if args \\u2261 null;\\n		children := [] if children \\u2261 null;\\n	}\\n\\n	method name () { return name; }\\n	method type_annotation () { return type_annotation; }\\n	method args () { return args; }\\n	method props () { return props; }\\n	method children () { return children; }\\n\\n	method to_Iterator () {\\n		let values := [];\\n		for ( let arg in args ) {\\n			values.push(arg);\\n		}\\n		for ( let child in children ) {\\n			values.push(child);\\n		}\\n		return values.to_Iterator();\\n	}\\n}\\n\\nclass KDLDocument {\\n	let nodes := [];\\n\\n	method __build__ () {\\n		nodes := [] if nodes \\u2261 null;\\n	}\\n\\n	method nodes () { return nodes; }\\n\\n	method to_Iterator () {\\n		return nodes.to_Iterator();\\n	}\\n}\\n\\nclass _KDLParser {\\n	let String text := "";\\n	let Number pos := 0;\\n\\n	method _eof () {\\n		return pos >= length text;\\n	}\\n\\n	method _peek () {\\n		return "" if self._eof();\\n		return substr( text, pos, 1 );\\n	}\\n\\n	method _take () {\\n		let ch := self._peek();\\n		pos++;\\n		return ch;\\n	}\\n\\n	method _error ( String message ) {\\n		die `KDL parse error at offset ${pos}: ${message}`;\\n	}\\n\\n	method _skip_newline () {\\n		if ( _kdl_starts_with( text, pos, "\\\\r\\\\n" ) ) {\\n			pos += 2;\\n			return true;\\n		}\\n		if ( _kdl_is_newline( self._peek() ) ) {\\n			pos++;\\n			return true;\\n		}\\n		return false;\\n	}\\n\\n	method _skip_line_comment () {\\n		return false if not _kdl_starts_with( text, pos, "//" );\\n		pos += 2;\\n		while ( not self._eof() and not _kdl_is_newline( self._peek() ) ) {\\n			pos++;\\n		}\\n		self._skip_newline();\\n		return true;\\n	}\\n\\n	method _skip_block_comment () {\\n		return false if not _kdl_starts_with( text, pos, "/*" );\\n		pos += 2;\\n		let depth := 1;\\n		while ( depth > 0 ) {\\n			self._error("Unterminated block comment") if self._eof();\\n			if ( _kdl_starts_with( text, pos, "/*" ) ) {\\n				depth++;\\n				pos += 2;\\n			}\\n			else if ( _kdl_starts_with( text, pos, "*/" ) ) {\\n				depth--;\\n				pos += 2;\\n			}\\n			else {\\n				pos++;\\n			}\\n		}\\n		return true;\\n	}\\n\\n	method _skip_line_space () {\\n		let moved := false;\\n		let keep := true;\\n		while ( keep and not self._eof() ) {\\n			keep := false;\\n			if ( _kdl_is_ws( self._peek() ) ) {\\n				pos++;\\n				moved := true;\\n				keep := true;\\n			}\\n			else if ( self._skip_newline() ) {\\n				moved := true;\\n				keep := true;\\n			}\\n			else if ( self._skip_line_comment() ) {\\n				moved := true;\\n				keep := true;\\n			}\\n			else if ( self._skip_block_comment() ) {\\n				moved := true;\\n				keep := true;\\n			}\\n			else if ( self._skip_escline() ) {\\n				moved := true;\\n				keep := true;\\n			}\\n		}\\n		return moved;\\n	}\\n\\n	method _skip_node_space () {\\n		let moved := false;\\n		let keep := true;\\n		while ( keep and not self._eof() ) {\\n			keep := false;\\n			if ( _kdl_is_ws( self._peek() ) ) {\\n				pos++;\\n				moved := true;\\n				keep := true;\\n			}\\n			else if ( self._skip_block_comment() ) {\\n				moved := true;\\n				keep := true;\\n			}\\n			else if ( self._skip_escline() ) {\\n				moved := true;\\n				keep := true;\\n			}\\n		}\\n		return moved;\\n	}\\n\\n	method _skip_escline () {\\n		return false if self._peek() \\u2262 "\\\\\\\\";\\n		let save := pos;\\n		pos++;\\n		let keep := true;\\n		while ( keep and not self._eof() ) {\\n			keep := false;\\n			while ( _kdl_is_ws( self._peek() ) ) {\\n				pos++;\\n				keep := true;\\n			}\\n			if ( self._skip_block_comment() ) {\\n				keep := true;\\n			}\\n		}\\n		if ( self._skip_line_comment() or self._skip_newline() or self._eof() ) {\\n			return true;\\n		}\\n		pos := save;\\n		return false;\\n	}\\n\\n	method _parse_document () {\\n		if ( _kdl_starts_with( text, pos, chr(65279) ) ) {\\n			pos++;\\n		}\\n		let nodes := self._parse_nodes(false);\\n		self._skip_line_space();\\n		self._error("Unexpected trailing input") if not self._eof();\\n		return new KDLDocument( nodes: nodes );\\n	}\\n\\n	method _parse_nodes ( Boolean in_children ) {\\n		let nodes := [];\\n		while (true) {\\n			self._skip_line_space();\\n			if ( self._eof() ) {\\n				return nodes;\\n			}\\n			if ( in_children and self._peek() \\u2261 "}" ) {\\n				return nodes;\\n			}\\n			if ( _kdl_starts_with( text, pos, "/-" ) ) {\\n				self._consume_slashdash();\\n				self._parse_node(true);\\n			}\\n			else {\\n				let node := self._parse_node(false);\\n				nodes.push(node) if node \\u2262 null;\\n			}\\n		}\\n		return nodes;\\n	}\\n\\n	method _consume_slashdash () {\\n		self._error("Expected slashdash") if not _kdl_starts_with( text, pos, "/-" );\\n		pos += 2;\\n		self._skip_line_space();\\n	}\\n\\n	method _parse_type_annotation () {\\n		return null if self._peek() \\u2262 "(";\\n		pos++;\\n		self._skip_node_space();\\n		let name := self._parse_string();\\n		self._skip_node_space();\\n		self._error("Expected \\\')\\\' after type annotation") if self._peek() \\u2262 ")";\\n		pos++;\\n		self._skip_node_space();\\n		return name;\\n	}\\n\\n	method _parse_node ( Boolean discard ) {\\n		let annotation := self._parse_type_annotation();\\n		self._skip_node_space();\\n		let name := self._parse_string();\\n		let args := [];\\n		let props := new PairList();\\n		let children := [];\\n		let slashdash_child_before_entry := false;\\n\\n		while (true) {\\n			let had_space := self._skip_node_space();\\n			if ( self._eof() ) {\\n				return discard ? null : new KDLNode(\\n					name: name,\\n					type_annotation: annotation,\\n					args: args,\\n					props: props,\\n					children: children,\\n				);\\n			}\\n\\n			let ch := self._peek();\\n			if ( ch \\u2261 ";" ) {\\n				pos++;\\n				return discard ? null : new KDLNode(\\n					name: name,\\n					type_annotation: annotation,\\n					args: args,\\n					props: props,\\n					children: children,\\n				);\\n			}\\n			if ( ch \\u2261 "}" ) {\\n				return discard ? null : new KDLNode(\\n					name: name,\\n					type_annotation: annotation,\\n					args: args,\\n					props: props,\\n					children: children,\\n				);\\n			}\\n			if ( _kdl_is_newline(ch) ) {\\n				self._skip_newline();\\n				return discard ? null : new KDLNode(\\n					name: name,\\n					type_annotation: annotation,\\n					args: args,\\n					props: props,\\n					children: children,\\n				);\\n			}\\n			if ( _kdl_starts_with( text, pos, "//" ) ) {\\n				self._skip_line_comment();\\n				return discard ? null : new KDLNode(\\n					name: name,\\n					type_annotation: annotation,\\n					args: args,\\n					props: props,\\n					children: children,\\n				);\\n			}\\n			if ( _kdl_starts_with( text, pos, "/-" ) ) {\\n				self._consume_slashdash();\\n				if ( self._peek() \\u2261 "{" ) {\\n					self._parse_children();\\n					slashdash_child_before_entry := true;\\n				}\\n				else {\\n					self._parse_entry(true, args, props);\\n				}\\n				next;\\n			}\\n			if ( ch \\u2261 "{" ) {\\n				self._error("Child block must be the final node field")\\n					if children.length() > 0;\\n				children := self._parse_children();\\n				next;\\n			}\\n			self._error("Expected whitespace before node field")\\n				if not had_space;\\n			self._error("Child block must be the final node field")\\n				if children.length() > 0;\\n			self._error("Discarded child block must not precede node fields")\\n				if slashdash_child_before_entry;\\n			self._parse_entry(discard, args, props);\\n		}\\n	}\\n\\n	method _parse_children () {\\n		self._error("Expected \\\'{\\\'") if self._peek() \\u2262 "{";\\n		pos++;\\n		let kids := self._parse_nodes(true);\\n		self._skip_line_space();\\n		self._error("Expected \\\'}\\\' after child block") if self._peek() \\u2262 "}";\\n		pos++;\\n		return kids;\\n	}\\n\\n	method _parse_entry ( Boolean discard, Array args, PairList props ) {\\n		if ( self._peek() \\u2261 "(" ) {\\n			let value := self._parse_value();\\n			args.push(value) if not discard;\\n			return;\\n		}\\n\\n		if ( self._peek() \\u2261 "#" or self._starts_number() ) {\\n			let value := self._parse_value();\\n			args.push(value) if not discard;\\n			return;\\n		}\\n\\n		let key := self._parse_string();\\n		let after_key := pos;\\n		self._skip_node_space();\\n		if ( self._peek() \\u2261 "=" ) {\\n			pos++;\\n			self._skip_node_space();\\n			let value := self._parse_value();\\n			props.add( key, value ) if not discard;\\n			return;\\n		}\\n		pos := after_key;\\n\\n		let value := new KDLValue( type: "string", value: key );\\n		args.push(value) if not discard;\\n		return;\\n	}\\n\\n	method _parse_value () {\\n		let annotation := self._parse_type_annotation();\\n		self._skip_node_space();\\n\\n		if ( self._peek() \\u2261 "#" ) {\\n			return self._parse_hash_value(annotation);\\n		}\\n		if ( self._starts_number() ) {\\n			return self._parse_number(annotation);\\n		}\\n		return new KDLValue(\\n			type: "string",\\n			value: self._parse_string(),\\n			type_annotation: annotation,\\n		);\\n	}\\n\\n	method _starts_number () {\\n		let ch := self._peek();\\n		let nxt := substr( text, pos + 1, 1 );\\n		return _kdl_is_digit(ch)\\n			or ( ( ch \\u2261 "+" or ch \\u2261 "-" ) and _kdl_is_digit(nxt) );\\n	}\\n\\n	method _read_token () {\\n		let start := pos;\\n		while ( not self._eof() ) {\\n			let ch := self._peek();\\n			last if _kdl_ident_break(ch);\\n			pos++;\\n		}\\n		return substr( text, start, pos - start );\\n	}\\n\\n	method _parse_hash_value ( annotation ) {\\n		if ( _kdl_starts_with( text, pos, "#true" ) ) {\\n			pos += 5;\\n			return new KDLValue(\\n				type: "boolean",\\n				value: true,\\n				type_annotation: annotation,\\n			);\\n		}\\n		if ( _kdl_starts_with( text, pos, "#false" ) ) {\\n			pos += 6;\\n			return new KDLValue(\\n				type: "boolean",\\n				value: false,\\n				type_annotation: annotation,\\n			);\\n		}\\n		if ( _kdl_starts_with( text, pos, "#null" ) ) {\\n			pos += 5;\\n			return new KDLValue(\\n				type: "null",\\n				value: null,\\n				type_annotation: annotation,\\n			);\\n		}\\n		if ( _kdl_starts_with( text, pos, "#inf" ) ) {\\n			pos += 4;\\n			return new KDLValue(\\n				type: "number",\\n				kind: "string",\\n				value: "#inf",\\n				type_annotation: annotation,\\n			);\\n		}\\n		if ( _kdl_starts_with( text, pos, "#-inf" ) ) {\\n			pos += 5;\\n			return new KDLValue(\\n				type: "number",\\n				kind: "string",\\n				value: "#-inf",\\n				type_annotation: annotation,\\n			);\\n		}\\n		if ( _kdl_starts_with( text, pos, "#nan" ) ) {\\n			pos += 4;\\n			return new KDLValue(\\n				type: "number",\\n				kind: "string",\\n				value: "#nan",\\n				type_annotation: annotation,\\n			);\\n		}\\n		return new KDLValue(\\n			type: "string",\\n			value: self._parse_raw_string(),\\n			type_annotation: annotation,\\n		);\\n	}\\n\\n	method _parse_number ( annotation ) {\\n		let token := self._read_token();\\n		self._error( `Invalid number \\\'${token}\\\'` )\\n			if token ~ /^[+-]?0[xob]_/i or token ~ /\\\\._/;\\n		let clean := _kdl_clean_number(token);\\n		if ( clean ~ /^[+-]?0x[0-9a-fA-F]+$/ ) {\\n			return new KDLValue(\\n				type: "number",\\n				kind: "integer",\\n				value: _kdl_parse_radix( clean, 16 ),\\n				canonical_number: _kdl_decimal_from_radix( clean, 16 ),\\n				type_annotation: annotation,\\n			);\\n		}\\n		if ( clean ~ /^[+-]?0o[0-7]+$/ ) {\\n			return new KDLValue(\\n				type: "number",\\n				kind: "integer",\\n				value: _kdl_parse_radix( clean, 8 ),\\n				canonical_number: _kdl_decimal_from_radix( clean, 8 ),\\n				type_annotation: annotation,\\n			);\\n		}\\n		if ( clean ~ /^[+-]?0b[01]+$/ ) {\\n			return new KDLValue(\\n				type: "number",\\n				kind: "integer",\\n				value: _kdl_parse_radix( clean, 2 ),\\n				canonical_number: _kdl_decimal_from_radix( clean, 2 ),\\n				type_annotation: annotation,\\n			);\\n		}\\n		if ( clean ~ /^[+-]?[0-9]+$/ ) {\\n			return new KDLValue(\\n				type: "number",\\n				kind: "integer",\\n				value: clean + 0,\\n				canonical_number: _kdl_canonical_decimal_int(clean),\\n				type_annotation: annotation,\\n			);\\n		}\\n		if ( clean ~ /^[+-]?[0-9]+(\\\\.[0-9]+)?([eE][+-]?[0-9]+)?$/ ) {\\n			return new KDLValue(\\n				type: "number",\\n				kind: "float",\\n				value: clean + 0,\\n				canonical_number: _kdl_canonical_float(clean),\\n				type_annotation: annotation,\\n			);\\n		}\\n		self._error( `Invalid number \\\'${token}\\\'` );\\n	}\\n\\n	method _parse_string () {\\n		if ( self._peek() \\u2261 "#" ) {\\n			return self._parse_raw_string();\\n		}\\n		if ( self._peek() \\u2261 "\\\\"" ) {\\n			return self._parse_quoted_string();\\n		}\\n		return self._parse_identifier_string();\\n	}\\n\\n	method _parse_identifier_string () {\\n		let ident := self._read_token();\\n		self._error("Expected string") if ident \\u2261 "";\\n		self._error( `Reserved KDL identifier \\\'${ident}\\\'` )\\n			if _kdl_reserved_ident(ident);\\n		self._error( `Invalid KDL identifier \\\'${ident}\\\'` )\\n			if substr( ident, 0, 1 ) \\u2261 "."\\n				and _kdl_is_digit( substr( ident, 1, 1 ) );\\n		let i := 0;\\n		while ( i < length ident ) {\\n			let code := ord( substr( ident, i, 1 ) );\\n			self._error( `Forbidden codepoint in KDL identifier \\\'${ident}\\\'` )\\n				if _kdl_forbidden_codepoint(code);\\n			i++;\\n		}\\n		return ident;\\n	}\\n\\n	method _parse_quoted_string () {\\n		if ( _kdl_starts_with( text, pos, "\\\\"\\\\"\\\\"" ) ) {\\n			return self._parse_multiline_string( "", false );\\n		}\\n		pos++;\\n		let out := "";\\n		while ( not self._eof() ) {\\n			let ch := self._take();\\n			if ( ch \\u2261 "\\\\"" ) {\\n				return out;\\n			}\\n			if ( ch \\u2261 "\\\\\\\\" ) {\\n				out _= self._parse_escape();\\n			}\\n			else {\\n				self._error("Newline in quoted string") if _kdl_is_newline(ch);\\n				out _= ch;\\n			}\\n		}\\n		self._error("Unterminated quoted string");\\n	}\\n\\n	method _parse_escape () {\\n		self._error("Unterminated string escape") if self._eof();\\n		let ch := self._take();\\n		if ( ch \\u2261 "\\\\"" ) { return "\\\\""; }\\n		if ( ch \\u2261 "\\\\\\\\" ) { return "\\\\\\\\"; }\\n		if ( ch \\u2261 "b" ) { return chr(8); }\\n		if ( ch \\u2261 "f" ) { return chr(12); }\\n		if ( ch \\u2261 "n" ) { return "\\\\n"; }\\n		if ( ch \\u2261 "r" ) { return "\\\\r"; }\\n		if ( ch \\u2261 "s" ) { return " "; }\\n		if ( ch \\u2261 "t" ) { return "\\\\t"; }\\n		if ( _kdl_is_line_space(ch) ) {\\n			while ( _kdl_is_line_space(ch) ) {\\n				if ( _kdl_is_newline(ch) ) {\\n					self._skip_newline();\\n				}\\n				ch := self._peek();\\n				pos++ if _kdl_is_ws(ch);\\n			}\\n			return "";\\n		}\\n		if ( ch \\u2261 "u" ) {\\n			self._error("Expected \\\'{\\\' in Unicode escape") if self._peek() \\u2262 "{";\\n			pos++;\\n			let start := pos;\\n			while ( not self._eof() and self._peek() \\u2262 "}" ) {\\n				self._error("Invalid Unicode escape") if not _kdl_is_hex_digit( self._peek() );\\n				pos++;\\n			}\\n			self._error("Unterminated Unicode escape") if self._peek() \\u2262 "}";\\n			let raw := substr( text, start, pos - start );\\n			self._error("Unicode escape must contain 1 to 6 hex digits")\\n				if length raw < 1 or length raw > 6;\\n			pos++;\\n			let code := _kdl_from_hex(raw);\\n			return chr(code);\\n		}\\n		self._error( `Invalid string escape \\\'\\\\\\\\${ch}\\\'` );\\n	}\\n\\n	method _parse_raw_string () {\\n		let hashes := "";\\n		while ( self._peek() \\u2261 "#" ) {\\n			hashes _= "#";\\n			pos++;\\n		}\\n		self._error("Expected raw string quotes") if self._peek() \\u2262 "\\\\"";\\n		if ( _kdl_starts_with( text, pos, "\\\\"\\\\"\\\\"" ) ) {\\n			return self._parse_multiline_string( hashes, true );\\n		}\\n		pos++;\\n		let close := "\\\\"" _ hashes;\\n		let end := index( text, close, pos );\\n		self._error("Unterminated raw string") if end < 0;\\n		let out := substr( text, pos, end - pos );\\n		self._error("Newline in raw string") if out ~ /[\\\\r\\\\n\\\\v]/;\\n		pos := end + length close;\\n		return out;\\n	}\\n\\n	method _parse_multiline_string ( String hashes, Boolean raw ) {\\n		pos += 3;\\n		self._error("Expected newline after multiline string opener")\\n			if not self._skip_newline();\\n		let close := "\\\\"\\\\"\\\\"" _ hashes;\\n		let end := _kdl_find_multiline_close( text, close, pos, raw );\\n		self._error("Unterminated multiline string") if end < 0;\\n		let body := substr( text, pos, end - pos );\\n		pos := end + length close;\\n\\n		let last_nl := -1;\\n		let i := length body - 1;\\n		while ( i >= 0 and last_nl < 0 ) {\\n			if ( substr( body, i, 1 ) \\u2261 "\\\\n" ) {\\n				last_nl := i;\\n			}\\n			i--;\\n		}\\n		return "" if last_nl < 0;\\n			let content := substr( body, 0, last_nl );\\n			let indent := substr( body, last_nl + 1, length body - last_nl - 1 );\\n			if ( not raw ) {\\n				let bs := 0;\\n				while ( bs < length indent\\n					and _kdl_is_ws( substr( indent, bs, 1 ) )\\n				) {\\n					bs++;\\n				}\\n				if ( bs < length indent and substr( indent, bs, 1 ) \\u2261 "\\\\\\\\" ) {\\n					let k := bs + 1;\\n					let only_ws := true;\\n					while ( k < length indent ) {\\n						only_ws := false\\n							if not _kdl_is_ws( substr( indent, k, 1 ) );\\n						k++;\\n					}\\n					indent := substr( indent, 0, bs ) if only_ws;\\n				}\\n			}\\n			if ( indent \\u2261 "" ) {\\n				let min_indent := null;\\n				let scan := 0;\\n				let scan_start := 0;\\n				while ( scan <= length content ) {\\n					if ( scan \\u2261 length content\\n						or substr( content, scan, 1 ) \\u2261 "\\\\n"\\n					) {\\n						let raw_line := substr(\\n							content,\\n							scan_start,\\n							scan - scan_start,\\n						);\\n						if ( not( raw_line ~ /^\\\\s*$/ ) ) {\\n							let width := 0;\\n							while ( width < length raw_line\\n								and _kdl_is_ws( substr( raw_line, width, 1 ) )\\n							) {\\n								width++;\\n							}\\n							min_indent := width\\n								if min_indent \\u2261 null or width < min_indent;\\n						}\\n						scan_start := scan + 1;\\n					}\\n					scan++;\\n				}\\n				if ( min_indent \\u2262 null and min_indent > 0 ) {\\n					indent := "";\\n					let si := 0;\\n					while ( si < min_indent ) {\\n						indent _= " ";\\n						si++;\\n					}\\n				}\\n			}\\n			let out := "";\\n		i := 0;\\n		let line_start := 0;\\n			let emitted := false;\\n			let continued := false;\\n			let last_line_continued_with_text := false;\\n			while ( i <= length content ) {\\n			if ( i \\u2261 length content or substr( content, i, 1 ) \\u2261 "\\\\n" ) {\\n				let line := substr( content, line_start, i - line_start );\\n				if ( line ~ /^\\\\s*$/ ) {\\n					line := "";\\n				}\\n					else if ( continued ) {\\n						if ( length indent > 0\\n							and substr( line, 0, length indent ) \\u2261 indent\\n						) {\\n							line := substr(\\n								line,\\n								length indent,\\n								length line - length indent,\\n							);\\n						}\\n					}\\n					else if ( length indent > 0 and substr( line, 0, length indent ) \\u2261 indent ) {\\n						line := substr( line, length indent, length line - length indent );\\n					}\\n					else if ( length indent > 0 ) {\\n						let k := 0;\\n						while ( k < length line\\n							and _kdl_is_ws( substr( line, k, 1 ) )\\n						) {\\n							k++;\\n						}\\n						let ok_escape_prefix := false;\\n						if ( not raw and substr( line, k, 1 ) \\u2261 "\\\\\\\\" ) {\\n							k++;\\n							ok_escape_prefix := true;\\n							while ( k < length line ) {\\n								ok_escape_prefix := false\\n									if not _kdl_is_ws( substr( line, k, 1 ) );\\n								k++;\\n							}\\n						}\\n						self._error("Multiline string indentation mismatch")\\n							if not ok_escape_prefix;\\n					}\\n\\n				let line_continues := false;\\n				if ( not raw ) {\\n					let j := length line - 1;\\n					while ( j >= 0 and _kdl_is_ws( substr( line, j, 1 ) ) ) {\\n						j--;\\n					}\\n					if ( j >= 0 and substr( line, j, 1 ) \\u2261 "\\\\\\\\" ) {\\n						let slashes := 0;\\n						while ( j - slashes >= 0\\n							and substr( line, j - slashes, 1 ) \\u2261 "\\\\\\\\"\\n						) {\\n							slashes++;\\n						}\\n						if ( slashes mod 2 = 1 ) {\\n							line_continues := true;\\n							line := substr( line, 0, j );\\n						}\\n					}\\n				}\\n				self._error("Invalid final multiline whitespace escape")\\n					if line_continues and line \\u2261 "" and indent \\u2261 "";\\n\\n				out _= "\\\\n"\\n					if emitted and not continued\\n						and not ( line_continues and line \\u2261 "" );\\n				out _= raw ? line : self._unescape_multiline_line(line);\\n				emitted := true;\\n				continued := line_continues;\\n				last_line_continued_with_text := line_continues and line \\u2262 "";\\n				line_start := i + 1;\\n			}\\n			i++;\\n		}\\n		self._error("Invalid final multiline whitespace escape")\\n			if last_line_continued_with_text;\\n		return out;\\n	}\\n\\n	method _unescape_multiline_line ( String line ) {\\n		let out := "";\\n		let i := 0;\\n		while ( i < length line ) {\\n			let ch := substr( line, i, 1 );\\n			if ( ch \\u2262 "\\\\\\\\" ) {\\n				out _= ch;\\n				i++;\\n				next;\\n			}\\n\\n			i++;\\n			self._error("Unterminated string escape") if i >= length line;\\n			ch := substr( line, i, 1 );\\n			if ( ch \\u2261 "\\\\"" ) { out _= "\\\\""; }\\n			else if ( ch \\u2261 "\\\\\\\\" ) { out _= "\\\\\\\\"; }\\n			else if ( ch \\u2261 "b" ) { out _= chr(8); }\\n			else if ( ch \\u2261 "f" ) { out _= chr(12); }\\n			else if ( ch \\u2261 "n" ) { out _= "\\\\n"; }\\n			else if ( ch \\u2261 "r" ) { out _= "\\\\r"; }\\n			else if ( ch \\u2261 "s" ) { out _= " "; }\\n			else if ( ch \\u2261 "t" ) { out _= "\\\\t"; }\\n			else if ( _kdl_is_ws(ch) ) {\\n				while ( i < length line and _kdl_is_ws( substr( line, i, 1 ) ) ) {\\n					i++;\\n				}\\n				i--;\\n			}\\n			else if ( ch \\u2261 "u" ) {\\n				self._error("Expected \\\'{\\\' in Unicode escape")\\n					if substr( line, i + 1, 1 ) \\u2262 "{";\\n				i += 2;\\n				let start := i;\\n				while ( i < length line and substr( line, i, 1 ) \\u2262 "}" ) {\\n					self._error("Invalid Unicode escape")\\n						if not _kdl_is_hex_digit( substr( line, i, 1 ) );\\n					i++;\\n				}\\n				self._error("Unterminated Unicode escape")\\n					if i >= length line;\\n				let raw := substr( line, start, i - start );\\n				self._error("Unicode escape must contain 1 to 6 hex digits")\\n					if length raw < 1 or length raw > 6;\\n				let code := _kdl_from_hex(raw);\\n				out _= chr(code);\\n			}\\n			else {\\n				self._error( `Invalid string escape \\\'\\\\\\\\${ch}\\\'` );\\n			}\\n			i++;\\n		}\\n		return out;\\n	}\\n}\\n\\nfunction _kdl_value ( value ) {\\n	if ( value instanceof KDLValue ) {\\n		return value;\\n	}\\n	if ( value \\u2261 null ) {\\n		return new KDLValue( type: "null", value: null );\\n	}\\n	if ( value instanceof Boolean ) {\\n		return new KDLValue( type: "boolean", value: value );\\n	}\\n	if ( value instanceof Number ) {\\n		return new KDLValue( type: "number", kind: "float", value: value );\\n	}\\n	return new KDLValue( type: "string", value: "" _ value );\\n}\\n\\nfunction _kdl_encode_value ( value, Boolean canonical := false ) {\\n	let v := _kdl_value(value);\\n	let prefix := "";\\n	if ( v.type_annotation() \\u2262 null ) {\\n		prefix := "(" _ _kdl_name( v.type_annotation() ) _ ")";\\n	}\\n	if ( v.is_null() ) { return prefix _ "#null"; }\\n	if ( v.is_boolean() ) {\\n		return prefix _ ( v.native_value() ? "#true" : "#false" );\\n	}\\n	if ( v.is_number() ) {\\n		if ( canonical and v.canonical_number() \\u2262 null ) {\\n			return prefix _ v.canonical_number();\\n		}\\n		return prefix _ ( v.kind() \\u2261 "string" ? v.value() : "" _ v.value() );\\n	}\\n	if ( v.is_string() ) {\\n		if ( canonical and _kdl_is_plain_ident( v.native_value() ) ) {\\n			return prefix _ v.native_value();\\n		}\\n		return prefix _ "\\\\"" _ _kdl_escape_string( v.native_value() ) _ "\\\\"";\\n	}\\n\\n	let native := v.native_value();\\n	try {\\n		if ( native can "to_String" ) {\\n			let text := native.to_String();\\n			if ( canonical and _kdl_is_plain_ident(text) ) {\\n				return prefix _ text;\\n			}\\n			return prefix _ "\\\\"" _ _kdl_escape_string(text) _ "\\\\"";\\n		}\\n	}\\n	catch {\\n	}\\n\\n	die `Cannot serialize KDLValue of type \\\'${v.type()}\\\'`;\\n}\\n\\nfunction _kdl_encode_node (\\n	KDLNode node,\\n	Number level,\\n	Boolean canonical := false,\\n) {\\n	let out := _kdl_indent( level, canonical );\\n	if ( node.type_annotation() \\u2262 null ) {\\n		out _= "(" _ _kdl_name( node.type_annotation() ) _ ")";\\n	}\\n	out _= _kdl_name( node.name() );\\n	for ( let arg in node.args() ) {\\n		out _= " " _ _kdl_encode_value( arg, canonical );\\n	}\\n	if ( canonical ) {\\n		for ( let kv in _kdl_canonical_props( node.props() ) ) {\\n			out _= " " _ _kdl_name(kv[0]) _ "="\\n				_ _kdl_encode_value( kv[1], canonical );\\n		}\\n	}\\n	else {\\n		for ( let pair in node.props().to_Array() ) {\\n			let kv := pair{pair};\\n			out _= " " _ _kdl_name(kv[0]) _ "="\\n				_ _kdl_encode_value( kv[1], canonical );\\n		}\\n	}\\n	if ( node.children().length() > 0 ) {\\n		out _= " {\\\\n";\\n		let i := 0;\\n		while ( i < node.children().length() ) {\\n			out _= _kdl_encode_node(\\n				node.children()[i],\\n				level + 1,\\n				canonical,\\n			);\\n			out _= "\\\\n";\\n			i++;\\n		}\\n		out _= _kdl_indent( level, canonical ) _ "}";\\n	}\\n	return out;\\n}\\n\\nfunction _kdl_encode_document ( KDLDocument doc, Boolean canonical := false ) {\\n	let out := "";\\n	let i := 0;\\n	while ( i < doc.nodes().length() ) {\\n		out _= "\\\\n" if i > 0;\\n		out _= _kdl_encode_node( doc.nodes()[i], 0, canonical );\\n		i++;\\n	}\\n	out _= "\\\\n" if canonical;\\n	return out;\\n}\\n\\nclass KDL {\\n	let Boolean canonical := false;\\n\\n	method decode ( String text ) {\\n		return new _KDLParser( text: text, pos: 0 )._parse_document();\\n	}\\n\\n	method decode_binarystring ( BinaryString raw ) {\\n		return self.decode( to_string(raw) );\\n	}\\n\\n	method encode ( value ) {\\n		if ( value instanceof KDLDocument ) {\\n			return _kdl_encode_document( value, canonical );\\n		}\\n		if ( value instanceof KDLNode ) {\\n			return _kdl_encode_node( value, 0, canonical );\\n		}\\n		if ( value instanceof Array ) {\\n			return _kdl_encode_document(\\n				new KDLDocument( nodes: value ),\\n				canonical,\\n			);\\n		}\\n		die "KDL.encode expects a KDLDocument, KDLNode, or Array of KDLNode";\\n	}\\n\\n	method encode_binarystring ( value ) {\\n		return to_binary( self.encode(value) );\\n	}\\n\\n	method load ( path ) {\\n		from std/io import Path;\\n		die "KDL.load is denied by runtime policy" if __system__{deny_fs};\\n		die "KDL.load expects a std/io Path object" if not( path instanceof Path );\\n		return self.decode_binarystring( path.slurp() );\\n	}\\n\\n	method dump ( path, value ) {\\n		from std/io import Path;\\n		die "KDL.dump is denied by runtime policy" if __system__{deny_fs};\\n		die "KDL.dump expects a std/io Path object" if not( path instanceof Path );\\n		path.spew( self.encode_binarystring(value) );\\n		return path;\\n	}\\n}\\n\';\n        virtualFiles["/modules/std/data/kdl/json.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/data/kdl/json - JSON-in-KDL structure conversion.\\n\\n=head1 SYNOPSIS\\n\\n  from std/data/kdl import KDL;\\n  from std/data/kdl/json import kdl_to_json, json_to_kdl;\\n\\n  let kdl_doc := ( new KDL() ).decode( """- foo=1 bar=#true""" );\\n  let data := kdl_to_json(kdl_doc);\\n  let roundtrip := json_to_kdl(data);\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nThis module implements the JSON-in-KDL (JiK) mapping for parsed Zuzu\\nobjects. C<kdl_to_json> accepts a C<KDLDocument> or C<KDLNode> and\\nreturns native Zuzu data structures. C<json_to_kdl> accepts native\\nJSON-like data structures and returns a C<KDLDocument>.\\n\\nC<kdl_to_json(value, pairlists: true)> maps object-like JiK nodes to\\nC<PairList> values instead of C<Dict> values, preserving key order and\\nduplicate keys.\\n\\n=head1 EXPORTS\\n\\n=head2 Functions\\n\\n=over\\n\\n=item C<< kdl_to_json(value, ... PairList opts) >>\\n\\nParameters: C<value> is a C<KDLDocument>, C<KDLNode>, or compatible KDL\\nvalue and C<opts> may include C<pairlists>. Returns: value. Converts\\nJSON-in-KDL structures into native JSON-like ZuzuScript data.\\n\\n=item C<< json_to_kdl(value) >>\\n\\nParameters: C<value> is a JSON-like ZuzuScript value. Returns:\\nC<KDLDocument>. Converts native JSON-like data into JSON-in-KDL nodes.\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/data/kdl/json >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/data/kdl import KDLDocument, KDLNode, KDLValue;\\nfrom std/data/kdl/xml import xml_to_kdl;\\nfrom std/time import Time;\\n\\n\\nfunction _jik_has_props ( KDLNode node ) {\\n	return node.props().to_Array().length() > 0;\\n}\\n\\nfunction _jik_literal_value ( value ) {\\n	die "JSON-in-KDL literal must be a KDLValue"\\n		if not( value instanceof KDLValue );\\n	if ( value.is_number() and value.kind() \\u2261 "string" ) {\\n		die "JSON-in-KDL does not support non-finite KDL number keywords";\\n	}\\n	return value.native_value();\\n}\\n\\nfunction _jik_is_time_native ( value ) {\\n	return value instanceof Time;\\n}\\n\\nfunction _jik_pad2 ( value ) {\\n	let text := "" _ value;\\n	return length text < 2 ? "0" _ text : text;\\n}\\n\\nfunction _jik_pad4 ( value ) {\\n	let text := "" _ value;\\n	while ( length text < 4 ) {\\n		text := "0" _ text;\\n	}\\n	return text;\\n}\\n\\nfunction _jik_time_text ( value ) {\\n	return _jik_pad4( value.year() )\\n		_ "-" _ _jik_pad2( value.mon() )\\n		_ "-" _ _jik_pad2( value.day_of_month() )\\n		_ "T" _ _jik_pad2( value.hour() )\\n		_ ":" _ _jik_pad2( value.min() )\\n		_ ":" _ _jik_pad2( value.sec() );\\n}\\n\\nfunction _jik_value ( value ) {\\n	if ( value instanceof KDLValue ) {\\n		return value;\\n	}\\n	if ( value \\u2261 null ) {\\n		return new KDLValue( type: "null", value: null );\\n	}\\n\\n	if ( value instanceof Boolean ) {\\n		return new KDLValue( type: "boolean", value: value );\\n	}\\n	if ( value instanceof Number ) {\\n		return new KDLValue( type: "number", kind: "float", value: value );\\n	}\\n	if ( value instanceof String or value instanceof BinaryString ) {\\n		return new KDLValue( type: "string", value: "" _ value );\\n	}\\n	if ( _jik_is_time_native(value) ) {\\n		return new KDLValue(\\n			type: "string",\\n			value: _jik_time_text(value),\\n			type_annotation: "date-time",\\n		);\\n	}\\n\\n	return new KDLValue( type: typeof value, value: value );\\n}\\n\\nfunction _jik_is_array_native ( value ) {\\n	return value instanceof Array or value instanceof Set or value instanceof Bag;\\n}\\n\\nfunction _jik_is_object_native ( value ) {\\n	return value instanceof Dict or value instanceof PairList;\\n}\\n\\nfunction _jik_is_kdl_native ( value ) {\\n	return value instanceof KDLDocument or value instanceof KDLNode;\\n}\\n\\nfunction _jik_is_xml_native ( value ) {\\n	try {\\n		if ( value can nodeType ) {\\n			return true if value.nodeType() \\u2262 null;\\n		}\\n	}\\n	catch {\\n	}\\n\\n	try {\\n		return false if not( value can documentElement );\\n		value.documentElement();\\n		return true;\\n	}\\n	catch {\\n	}\\n\\n	return false;\\n}\\n\\nfunction _jik_is_opaque_literal_native ( value ) {\\n	return not _jik_is_array_native(value)\\n		and not _jik_is_object_native(value)\\n		and not _jik_is_kdl_native(value)\\n		and not _jik_is_xml_native(value);\\n}\\n\\nfunction _jik_is_literal_native ( value ) {\\n	return value \\u2261 null\\n		or value instanceof Boolean\\n		or value instanceof Number\\n		or value instanceof String\\n		or value instanceof BinaryString\\n		or _jik_is_time_native(value)\\n		or value instanceof KDLValue\\n		or _jik_is_opaque_literal_native(value);\\n}\\n\\nfunction _jik_sorted_array ( value ) {\\n	if ( value instanceof Set or value instanceof Bag ) {\\n		return value.sortstr();\\n	}\\n	return value;\\n}\\n\\nfunction _jik_pairs ( obj ) {\\n	let out := [];\\n	if ( obj instanceof PairList ) {\\n		for ( let p in obj.to_Array() ) {\\n			out.push( p{pair} );\\n		}\\n		return out;\\n	}\\n\\n	for ( let key in obj.sorted_keys() ) {\\n		out.push( [ key, obj.get(key) ] );\\n	}\\n	return out;\\n}\\n\\nfunction _jik_native_to_node;\\nfunction _jik_native_to_nodes;\\n\\nfunction _jik_xml_nodes ( value ) {\\n	return xml_to_kdl(value).nodes();\\n}\\n\\nfunction _jik_kdl_nodes ( value ) {\\n	if ( value instanceof KDLDocument ) {\\n		return value.nodes();\\n	}\\n	return [ value ];\\n}\\n\\nfunction _jik_structural_nodes ( value, String name := "-" ) {\\n	let nodes := _jik_is_kdl_native(value)\\n		? _jik_kdl_nodes(value)\\n		: _jik_xml_nodes(value);\\n\\n	if ( name \\u2261 "-" ) {\\n		return nodes.length() = 0 ? [ new KDLNode( name: name ) ] : nodes;\\n	}\\n	return [ new KDLNode( name: name, children: nodes ) ];\\n}\\n\\nfunction _jik_make_array_node ( value, String name := "-" ) {\\n	let items := _jik_sorted_array(value);\\n	let all_literals := true;\\n	for ( let item in items ) {\\n		all_literals := false unless _jik_is_literal_native(item);\\n	}\\n\\n	let annotate := items.length() < 2;\\n	if ( all_literals ) {\\n		return new KDLNode(\\n			name: name,\\n			type_annotation: annotate ? "array" : null,\\n			args: items.map( fn item -> _jik_value(item) ),\\n		);\\n	}\\n\\n	let children := [];\\n	for ( let item in items ) {\\n		for ( let child in _jik_native_to_nodes( item, "-" ) ) {\\n			children.push(child);\\n		}\\n	}\\n\\n	return new KDLNode(\\n		name: name,\\n		type_annotation: annotate ? "array" : null,\\n		children: children,\\n	);\\n}\\n\\nfunction _jik_object_needs_annotation ( Array pairs, Boolean pairlist ) {\\n	if ( pairs.length() = 0 ) {\\n		return true;\\n	}\\n	if ( pairlist ) {\\n		return pairs.all( fn pair -> pair[0] \\u2261 "-" );\\n	}\\n	return pairs.length() = 1 and pairs[0][0] \\u2261 "-"\\n		and not _jik_is_literal_native( pairs[0][1] );\\n}\\n\\nfunction _jik_make_object_node ( value, String name := "-" ) {\\n	let pairs := _jik_pairs(value);\\n	let pairlist := value instanceof PairList;\\n	let props := new PairList();\\n	let children := [];\\n\\n	if ( pairlist ) {\\n		for ( let pair in pairs ) {\\n			for ( let child in _jik_native_to_nodes( pair[1], pair[0] ) ) {\\n				children.push(child);\\n			}\\n		}\\n	}\\n	else {\\n		for ( let pair in pairs ) {\\n			if ( _jik_is_literal_native( pair[1] ) ) {\\n				props.add( pair[0], _jik_value( pair[1] ) );\\n			}\\n			else {\\n				for ( let child in _jik_native_to_nodes( pair[1], pair[0] ) ) {\\n					children.push(child);\\n				}\\n			}\\n		}\\n	}\\n\\n	return new KDLNode(\\n		name: name,\\n		type_annotation: _jik_object_needs_annotation( pairs, pairlist )\\n			? "object"\\n			: null,\\n		props: props,\\n		children: children,\\n	);\\n}\\n\\nfunction _jik_native_to_node ( value, String name := "-" ) {\\n	if ( _jik_is_literal_native(value) ) {\\n		return new KDLNode( name: name, args: [ _jik_value(value) ] );\\n	}\\n	if ( _jik_is_array_native(value) ) {\\n		return _jik_make_array_node( value, name );\\n	}\\n	if ( _jik_is_object_native(value) ) {\\n		return _jik_make_object_node( value, name );\\n	}\\n	if ( _jik_is_kdl_native(value) or _jik_is_xml_native(value) ) {\\n		let nodes := _jik_structural_nodes( value, name );\\n		return nodes.length() = 1 ? nodes[0] : new KDLNode(\\n			name: name,\\n			children: nodes,\\n		);\\n	}\\n	die `Cannot convert ${typeof value} to JSON-in-KDL`;\\n}\\n\\nfunction _jik_native_to_nodes ( value, String name := "-" ) {\\n	if ( _jik_is_kdl_native(value) or _jik_is_xml_native(value) ) {\\n		return _jik_structural_nodes( value, name );\\n	}\\n	return [ _jik_native_to_node( value, name ) ];\\n}\\n\\nfunction _jik_node_has_only_dash_children ( KDLNode node ) {\\n	return node.children().all( fn child -> child.name() \\u2261 "-" );\\n}\\n\\nfunction _jik_node_kind ( KDLNode node ) {\\n	let annotation := node.type_annotation();\\n	if ( annotation \\u2261 "array" or annotation \\u2261 "object" ) {\\n		return annotation;\\n	}\\n	if ( _jik_has_props(node) ) {\\n		return "object";\\n	}\\n	if ( node.children().length() > 0 ) {\\n		if ( _jik_node_has_only_dash_children(node) ) {\\n			return "array";\\n		}\\n		return "object";\\n	}\\n	if ( node.args().length() = 1 ) {\\n		return "literal";\\n	}\\n	if ( node.args().length() > 1 ) {\\n		return "array";\\n	}\\n	die "Empty JSON-in-KDL node must be annotated as array or object";\\n}\\n\\nfunction _jik_node_to_native;\\n\\nfunction _jik_array_from_node ( KDLNode node, PairList opts ) {\\n	die "JSON-in-KDL array node cannot contain properties"\\n		if _jik_has_props(node);\\n	die "Empty JSON-in-KDL array node must be annotated as array"\\n		if node.args().length() = 0\\n			and node.children().length() = 0\\n			and node.type_annotation() \\u2262 "array";\\n	die "JSON-in-KDL array child nodes must be named \\\'-\\\'"\\n		unless _jik_node_has_only_dash_children(node);\\n\\n	let out := [];\\n	for ( let arg in node.args() ) {\\n		out.push( _jik_literal_value(arg) );\\n	}\\n	for ( let child in node.children() ) {\\n		out.push( _jik_node_to_native( child, opts ) );\\n	}\\n	return out;\\n}\\n\\nfunction _jik_store_object_item ( obj, String key, value, Boolean pairlists ) {\\n	if ( pairlists ) {\\n		obj.add( key, value );\\n		return;\\n	}\\n	die `Duplicate JSON-in-KDL object key \\\'${key}\\\'` if obj.exists(key);\\n	obj.set( key, value );\\n}\\n\\nfunction _jik_object_from_node ( KDLNode node, PairList opts ) {\\n	die "JSON-in-KDL object node cannot contain unnamed arguments"\\n		if node.args().length() > 0;\\n	die "Empty JSON-in-KDL object node must be annotated as object"\\n		if not _jik_has_props(node)\\n			and node.children().length() = 0\\n			and node.type_annotation() \\u2262 "object";\\n\\n	let pairlists := opts.get( "pairlists", false );\\n	let out := pairlists ? new PairList() : {};\\n\\n	for ( let pair in node.props().to_Array() ) {\\n		let kv := pair{pair};\\n		_jik_store_object_item(\\n			out,\\n			kv[0],\\n			_jik_literal_value( kv[1] ),\\n			pairlists,\\n		);\\n	}\\n	for ( let child in node.children() ) {\\n		_jik_store_object_item(\\n			out,\\n			child.name(),\\n			_jik_node_to_native( child, opts ),\\n			pairlists,\\n		);\\n	}\\n	return out;\\n}\\n\\nfunction _jik_node_to_native ( KDLNode node, PairList opts ) {\\n	let kind := _jik_node_kind(node);\\n	if ( kind \\u2261 "literal" ) {\\n		die "JSON-in-KDL literal node must contain one argument only"\\n			if node.args().length() \\u2262 1\\n				or _jik_has_props(node)\\n				or node.children().length() > 0;\\n		return _jik_literal_value( node.args()[0] );\\n	}\\n	if ( kind \\u2261 "array" ) {\\n		return _jik_array_from_node( node, opts );\\n	}\\n	if ( kind \\u2261 "object" ) {\\n		return _jik_object_from_node( node, opts );\\n	}\\n	die `Unknown JSON-in-KDL node kind \\\'${kind}\\\'`;\\n}\\n\\nfunction kdl_to_json ( value, ... PairList opts ) {\\n	if ( value instanceof KDLNode ) {\\n		return _jik_node_to_native( value, opts );\\n	}\\n	if ( value instanceof KDLDocument ) {\\n		die "JSON-in-KDL document must contain exactly one top-level node"\\n			if value.nodes().length() \\u2262 1;\\n		return _jik_node_to_native( value.nodes()[0], opts );\\n	}\\n	die "kdl_to_json expects a KDLDocument or KDLNode";\\n}\\n\\nfunction json_to_kdl ( value ) {\\n	if ( value instanceof KDLDocument ) {\\n		return value;\\n	}\\n	if ( value instanceof KDLNode ) {\\n		return value;\\n	}\\n	return new KDLDocument( nodes: [ _jik_native_to_node(value) ] );\\n}\\n\';\n        virtualFiles["/modules/std/data/kdl/xml.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/data/kdl/xml - XML-in-KDL structure conversion.\\n\\n=head1 SYNOPSIS\\n\\n  from std/data/kdl import KDL;\\n  from std/data/kdl/xml import kdl_to_xml, xml_to_kdl;\\n  from std/data/xml import XML;\\n\\n  let kdl_doc := ( new KDL() ).decode(\\n    "a href=\\\\"http://example.com\\\\" \\\\"here\\\'s a link\\\\""\\n  );\\n  let xml_doc := kdl_to_xml(kdl_doc);\\n  let roundtrip := xml_to_kdl(xml_doc);\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nThis module implements the XML-in-KDL (XiK) mapping for parsed Zuzu\\nobjects. C<kdl_to_xml> accepts a C<KDLDocument> or C<KDLNode> and\\nreturns an C<XMLDocument>. C<xml_to_kdl> accepts an C<XMLDocument> or\\nC<XMLNode> and returns a C<KDLDocument>.\\n\\n=head1 EXPORTS\\n\\n=head2 Functions\\n\\n=over\\n\\n=item C<< kdl_to_xml(value) >>\\n\\nParameters: C<value> is a C<KDLDocument>, C<KDLNode>, or compatible KDL\\nvalue. Returns: C<XMLDocument>. Converts XML-in-KDL structures into an\\nXML document.\\n\\n=item C<< xml_to_kdl(value) >>\\n\\nParameters: C<value> is an C<XMLDocument>, C<XMLNode>, or compatible XML\\nvalue. Returns: C<KDLDocument>. Converts XML data into XML-in-KDL nodes.\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/data/kdl/xml >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/data/kdl import KDLDocument, KDLNode, KDLValue;\\nfrom std/data/xml import XML;\\nfrom std/data/xml/escape import escape_xml;\\nfrom std/string import index, substr;\\n\\nfunction _xik_starts_with ( String text, String prefix ) {\\n	return substr( text, 0, length prefix ) \\u2261 prefix;\\n}\\n\\nfunction _xik_has_props ( KDLNode node ) {\\n	return node.props().to_Array().length() > 0;\\n}\\n\\nfunction _xik_string_value ( value, String context ) {\\n	die `${context} must be a KDLValue` if not( value instanceof KDLValue );\\n	die `${context} must be a string value` if not value.is_string();\\n	return value.native_value();\\n}\\n\\nfunction _xik_single_string_arg ( KDLNode node, String context ) {\\n	die `${context} must contain one string argument`\\n		if node.args().length() \\u2262 1;\\n	return _xik_string_value( node.args()[0], context );\\n}\\n\\nfunction _xik_no_props_or_children ( KDLNode node, String context ) {\\n	die `${context} cannot contain properties` if _xik_has_props(node);\\n	die `${context} cannot contain children`\\n		if node.children().length() > 0;\\n}\\n\\nfunction _xik_attr_text ( PairList props ) {\\n	let out := "";\\n	for ( let pair in props.to_Array() ) {\\n		let kv := pair{pair};\\n		let key := kv[0];\\n		let value := _xik_string_value(\\n			kv[1],\\n			`XML-in-KDL attribute \\\'${key}\\\'`,\\n		);\\n		out _= ` ${key}="${escape_xml(value)}"`;\\n	}\\n	return out;\\n}\\n\\nfunction _xik_comment_text ( KDLNode node ) {\\n	_xik_no_props_or_children( node, "XML-in-KDL comment node" );\\n	let text := _xik_single_string_arg( node, "XML-in-KDL comment node" );\\n	die "XML-in-KDL comment cannot contain \\\'--\\\'" if index( text, "--" ) >= 0;\\n	die "XML-in-KDL comment cannot end with \\\'-\\\'"\\n		if length text > 0 and substr( text, length text - 1, 1 ) \\u2261 "-";\\n	return "<!--" _ text _ "-->";\\n}\\n\\nfunction _xik_doctype_text ( KDLNode node ) {\\n	_xik_no_props_or_children( node, "XML-in-KDL doctype node" );\\n	let text := _xik_single_string_arg( node, "XML-in-KDL doctype node" );\\n	die "XML-in-KDL doctype cannot contain \\\'>\\\'" if index( text, ">" ) >= 0;\\n	return "<!DOCTYPE " _ text _ ">";\\n}\\n\\nfunction _xik_pi_text ( KDLNode node ) {\\n	die "XML-in-KDL processing instruction cannot contain children"\\n		if node.children().length() > 0;\\n\\n	let target := substr( node.name(), 1, length node.name() - 1 );\\n	die "XML-in-KDL processing instruction has an empty target"\\n		if target \\u2261 "";\\n\\n	let content := "";\\n	if ( node.args().length() > 0 ) {\\n		_xik_no_props_or_children(\\n			node,\\n			"XML-in-KDL unstructured processing instruction",\\n		);\\n		content := _xik_single_string_arg(\\n			node,\\n			"XML-in-KDL unstructured processing instruction",\\n		);\\n	}\\n	else {\\n		content := _xik_attr_text( node.props() );\\n		content := substr( content, 1, length content - 1 )\\n			if length content > 0;\\n	}\\n\\n	die "XML-in-KDL processing instruction cannot contain \\\'?>\\\'"\\n		if index( content, "?>" ) >= 0;\\n\\n	return content \\u2261 "" ? `<?${target}?>` : `<?${target} ${content}?>`;\\n}\\n\\nfunction _xik_text_node_text ( KDLNode node ) {\\n	_xik_no_props_or_children( node, "XML-in-KDL text node" );\\n	return escape_xml( _xik_single_string_arg( node, "XML-in-KDL text node" ) );\\n}\\n\\nfunction _xik_node_text;\\n\\nfunction _xik_element_text ( KDLNode node ) {\\n	die `XML-in-KDL element \\\'${node.name()}\\\' cannot have type annotations`\\n		if node.type_annotation() \\u2262 null;\\n\\n	let args := node.args();\\n	let children := node.children();\\n	die `XML-in-KDL element \\\'${node.name()}\\\' cannot contain multiple arguments`\\n		if args.length() > 1;\\n	die `XML-in-KDL element \\\'${node.name()}\\\' cannot mix text argument and children`\\n		if args.length() > 0 and children.length() > 0;\\n\\n	let attrs := _xik_attr_text( node.props() );\\n	if ( args.length() = 0 and children.length() = 0 ) {\\n		return `<${node.name()}${attrs}/>`;\\n	}\\n\\n	let body := "";\\n	if ( args.length() = 1 ) {\\n		body := escape_xml(\\n			_xik_string_value(\\n				args[0],\\n				`XML-in-KDL element \\\'${node.name()}\\\' text argument`,\\n			),\\n		);\\n	}\\n	else {\\n		for ( let child in children ) {\\n			body _= _xik_node_text(child);\\n		}\\n	}\\n\\n	return `<${node.name()}${attrs}>${body}</${node.name()}>`;\\n}\\n\\nfunction _xik_node_text ( KDLNode node ) {\\n	let name := node.name();\\n	if ( name \\u2261 "-" ) {\\n		return _xik_text_node_text(node);\\n	}\\n	if ( name \\u2261 "!" ) {\\n		return _xik_comment_text(node);\\n	}\\n	if ( name \\u2261 "!doctype" ) {\\n		return _xik_doctype_text(node);\\n	}\\n	if ( _xik_starts_with( name, "?" ) ) {\\n		return _xik_pi_text(node);\\n	}\\n	return _xik_element_text(node);\\n}\\n\\nfunction _xik_is_element_node ( KDLNode node ) {\\n	let name := node.name();\\n	return name \\u2262 "-" and name \\u2262 "!" and name \\u2262 "!doctype"\\n		and not _xik_starts_with( name, "?" );\\n}\\n\\nfunction kdl_to_xml ( value ) {\\n	let nodes;\\n	if ( value instanceof KDLDocument ) {\\n		nodes := value.nodes();\\n	}\\n	else if ( value instanceof KDLNode ) {\\n		nodes := [ value ];\\n	}\\n	else {\\n		die "kdl_to_xml expects a KDLDocument or KDLNode";\\n	}\\n\\n	let element_count := 0;\\n	let out := "";\\n	for ( let node in nodes ) {\\n		element_count++ if _xik_is_element_node(node);\\n		out _= _xik_node_text(node);\\n	}\\n\\n	die "XML-in-KDL document must contain exactly one top-level element"\\n		if element_count \\u2262 1;\\n\\n	return XML.parse(out);\\n}\\n\\nfunction _xik_kdl_value ( String text ) {\\n	return new KDLValue( type: "string", value: text );\\n}\\n\\nfunction _xik_xml_attrs_to_kdl ( xml_node ) {\\n	let props := new PairList();\\n	for ( let attr in xml_node.attributes() ) {\\n		props.add( attr.nodeName(), _xik_kdl_value( attr.nodeValue() ) );\\n	}\\n	return props;\\n}\\n\\nfunction _xik_xml_text_to_kdl ( xml_node ) {\\n	return new KDLNode(\\n		name: "-",\\n		args: [ _xik_kdl_value( xml_node.nodeValue() ?: "" ) ],\\n	);\\n}\\n\\nfunction _xik_xml_comment_to_kdl ( xml_node ) {\\n	return new KDLNode(\\n		name: "!",\\n		args: [ _xik_kdl_value( xml_node.nodeValue() ?: "" ) ],\\n	);\\n}\\n\\nfunction _xik_xml_node_to_kdl;\\n\\nfunction _xik_xml_pi_to_kdl ( xml_node ) {\\n	return new KDLNode(\\n		name: "?" _ xml_node.nodeName(),\\n		args: [ _xik_kdl_value( xml_node.nodeValue() ?: "" ) ],\\n	);\\n}\\n\\nfunction _xik_xml_doctype_to_kdl ( xml_node ) {\\n	return new KDLNode(\\n		name: "!doctype",\\n		args: [ _xik_kdl_value( xml_node.nodeValue() or? xml_node.nodeName() ) ],\\n	);\\n}\\n\\nfunction _xik_xml_element_to_kdl ( xml_node ) {\\n	let child_nodes := xml_node.childNodes();\\n	let text_only := child_nodes.length() > 0;\\n	let text := "";\\n\\n	for ( let child in child_nodes ) {\\n		let kind := 0 + child.nodeType();\\n		if ( kind = 3 or kind = 4 ) {\\n			text _= child.nodeValue() ?: "";\\n		}\\n		else {\\n			text_only := false;\\n		}\\n	}\\n\\n	if ( text_only ) {\\n		return new KDLNode(\\n			name: xml_node.nodeName(),\\n			props: _xik_xml_attrs_to_kdl(xml_node),\\n			args: [ _xik_kdl_value(text) ],\\n		);\\n	}\\n\\n	let children := [];\\n	for ( let child in child_nodes ) {\\n		let kdl_child := _xik_xml_node_to_kdl(child);\\n		children.push(kdl_child) if kdl_child \\u2262 null;\\n	}\\n\\n	return new KDLNode(\\n		name: xml_node.nodeName(),\\n		props: _xik_xml_attrs_to_kdl(xml_node),\\n		children: children,\\n	);\\n}\\n\\nfunction _xik_xml_node_to_kdl ( xml_node ) {\\n	switch ( 0 + xml_node.nodeType() ) {\\n		case 1:\\n			return _xik_xml_element_to_kdl(xml_node);\\n		case 3, 4:\\n			return _xik_xml_text_to_kdl(xml_node);\\n		case 7:\\n			return _xik_xml_pi_to_kdl(xml_node);\\n		case 8:\\n			return _xik_xml_comment_to_kdl(xml_node);\\n		case 10:\\n			return _xik_xml_doctype_to_kdl(xml_node);\\n	}\\n	return null;\\n}\\n\\nfunction _xik_xml_document_nodes ( xml_doc ) {\\n	let raw_nodes := null;\\n	try {\\n		raw_nodes := xml_doc.childNodes();\\n	}\\n	catch {\\n		try {\\n			raw_nodes := xml_doc.findnodes("/node()");\\n		}\\n		catch {\\n			let root := xml_doc.documentElement();\\n			raw_nodes := root \\u2261 null ? [] : [ root ];\\n		}\\n	}\\n\\n	if ( raw_nodes.length() = 0 ) {\\n		let root := xml_doc.documentElement();\\n		raw_nodes := root \\u2261 null ? [] : [ root ];\\n	}\\n\\n	let nodes := [];\\n	for ( let raw in raw_nodes ) {\\n		let node := _xik_xml_node_to_kdl(raw);\\n		nodes.push(node) if node \\u2262 null;\\n	}\\n	return nodes;\\n}\\n\\nfunction xml_to_kdl ( value ) {\\n	let node_type := null;\\n	try {\\n		node_type := 0 + value.nodeType();\\n	}\\n	catch {\\n	}\\n\\n	if ( node_type \\u2262 null ) {\\n		if ( node_type = 9 ) {\\n			return new KDLDocument( nodes: _xik_xml_document_nodes(value) );\\n		}\\n\\n		let node := _xik_xml_node_to_kdl(value);\\n		die "xml_to_kdl cannot convert this XML node type" if node \\u2261 null;\\n		return new KDLDocument( nodes: [ node ] );\\n	}\\n\\n	try {\\n		value.documentElement();\\n		return new KDLDocument( nodes: _xik_xml_document_nodes(value) );\\n	}\\n	catch {\\n		die "xml_to_kdl expects an XMLDocument or XMLNode";\\n	}\\n}\\n\';\n        virtualFiles["/modules/std/path/jsonpointer.zzm"] = `=encoding utf8\n\n=head1 NAME\n\nstd/path/jsonpointer - RFC 6901 JSON Pointer selectors.\n\n=head1 SYNOPSIS\n\n  from std/path/jsonpointer import JSONPointer;\n\n  let data := {\n    users: [\n      { name: "Ada" },\n      { name: "Bob" },\n    ],\n  };\n\n  let pointer := new JSONPointer( path: "/users/0/name" );\n  say( pointer.first(data) );\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nC<JSONPointer> implements JSON Pointer as defined by RFC 6901. It\nprovides the same path API shape as C<std/path/simple> and C<std/path/z>:\nC<get>, C<select>, C<query>, C<first>, C<exists>, assignment methods,\nreference methods, and lexical path-operator registration via C<use>.\n\nSyntactically valid pointers that do not resolve return no matches for\nread APIs.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<< JSONPointer({ path: String }) >>\n\nConstructs a JSON Pointer selector. Returns: C<JSONPointer>.\n\n=over\n\n=item C<< JSONPointer.use() >>\n\nParameters: none. Returns: C<null>. Makes this path class the lexical\nimplementation for C<@>, C<@@>, and C<@?>.\n\n=item C<< pointer.expression() >>\n\nParameters: none. Returns: C<String>. Returns the original pointer\nexpression.\n\n=item C<< pointer.get(value) >>, C<< pointer.select(value) >>,\nC<< pointer.query(value) >>\n\nParameters: C<value> is the query root. Returns: C<Array>. Evaluates the\npointer and returns selected values.\n\n=item C<< pointer.first(value, fallback?) >>\n\nParameters: C<value> is the query root and C<fallback> is optional.\nReturns: value. Returns the selected value, or C<fallback>/C<null> when\nthere is no match.\n\n=item C<< pointer.exists(value) >>\n\nParameters: C<value> is the query root. Returns: C<Boolean>. Returns\ntrue when the pointer resolves to a concrete value.\n\n=item C<< pointer.assign_first(target, value, op := ":=", weak := false) >>\n\nParameters: C<target> is the query root, C<value> is the assignment\nvalue, C<op> is an assignment operator, and C<weak> is accepted for path\nAPI compatibility. Returns: value. Updates the selected location.\n\n=item C<< pointer.assign_all(target, value, op := ":=", weak := false) >>\n\nParameters: same as C<assign_first>. Returns: value. Updates the\nselected location when it exists.\n\n=item C<< pointer.assign_maybe(target, value, op := ":=", weak := false) >>\n\nParameters: same as C<assign_first>. Returns: C<Boolean>. Updates the\nselected location when it exists.\n\n=item C<< pointer.ref_first(target) >>\n\nParameters: C<target> is the query root. Returns: C<Function>. Returns a\nreference-like getter/setter for the selected location.\n\n=item C<< pointer.ref_all(target) >>\n\nParameters: C<target> is the query root. Returns: C<Array>. Returns a\nsingle reference-like getter/setter when the pointer resolves, otherwise\nan empty array.\n\n=item C<< pointer.ref_maybe(target) >>\n\nParameters: C<target> is the query root. Returns: C<Function> or\nC<null>. Returns a reference-like getter/setter when the pointer\nresolves.\n\n=back\n\n=back\n\n=head2 Functions\n\n=over\n\n=item C<< extract_pointer_from_url(url) >>\n\nParameters: C<url> is a C<String>. Returns: C<Dict>. Splits a URL into\nC<baseurl> and C<pointer>. If the URL contains C<#>, C<baseurl> is the\ntext before C<#> and C<pointer> is the URI-fragment percent-decoded JSON\nPointer. If the URL has no C<#>, C<baseurl> is the full URL and\nC<pointer> is C<null>.\n\n=back\n\n=head1 SEE ALSO\n\nSpecification: L<https://www.rfc-editor.org/rfc/rfc6901>.\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/path/jsonpointer >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/string import index, ord, replace, substr;\nfrom std/string/base64 import decode as _base64_decode;\n\nlet _B64_ALPHABET := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"\n	_ "abcdefghijklmnopqrstuvwxyz0123456789+/";\n\nfunction _jsonpointer_div_floor ( Number n, Number d ) {\n	return floor( n / d );\n}\n\nfunction _jsonpointer_mod ( Number n, Number d ) {\n	return n - _jsonpointer_div_floor( n, d ) * d;\n}\n\nfunction _jsonpointer_bytes_to_binary ( Array bytes ) {\n	let out := "";\n	let i := 0;\n	let n := bytes.length();\n\n	while ( i < n ) {\n		let b0 := bytes[i];\n		let b1 := null;\n		let b2 := null;\n		if ( i + 1 < n ) {\n			b1 := bytes[i + 1];\n		}\n		if ( i + 2 < n ) {\n			b2 := bytes[i + 2];\n		}\n\n		let c0 := _jsonpointer_div_floor( b0, 4 );\n		let c1 := _jsonpointer_mod( b0, 4 ) * 16;\n		let c2 := 64;\n		let c3 := 64;\n\n		if ( not( b1 == null ) ) {\n			c1 += _jsonpointer_div_floor( b1, 16 );\n			c2 := _jsonpointer_mod( b1, 16 ) * 4;\n			if ( not( b2 == null ) ) {\n				c2 += _jsonpointer_div_floor( b2, 64 );\n				c3 := _jsonpointer_mod( b2, 64 );\n			}\n		}\n\n		out _= substr( _B64_ALPHABET, c0, 1 );\n		out _= substr( _B64_ALPHABET, c1, 1 );\n		out _= c2 == 64 ? "=" : substr( _B64_ALPHABET, c2, 1 );\n		out _= c3 == 64 ? "=" : substr( _B64_ALPHABET, c3, 1 );\n		i += 3;\n	}\n\n	return _base64_decode(out);\n}\n\nfunction _jsonpointer_hex_value ( String ch ) {\n	if ( ch ~ /[0-9]/ ) {\n		return 0 + ch;\n	}\n\n	let lower := lc(ch);\n	return 10 + index( "abcdef", lower );\n}\n\nfunction _jsonpointer_percent_decode ( String text ) {\n	let bytes := [];\n	let i := 0;\n	let n := length text;\n\n	while ( i < n ) {\n		let ch := substr( text, i, 1 );\n		if (\n			ch \\u2261 "%"\n			and i + 2 < n\n			and substr( text, i + 1, 1 ) ~ /[0-9A-Fa-f]/\n			and substr( text, i + 2, 1 ) ~ /[0-9A-Fa-f]/\n		) {\n			bytes.push(\n				_jsonpointer_hex_value( substr( text, i + 1, 1 ) ) * 16\n				+ _jsonpointer_hex_value( substr( text, i + 2, 1 ) ),\n			);\n			i += 3;\n			next;\n		}\n\n		let code := ord(ch);\n		die "JSONPointer URL fragment contains non-ASCII literal character"\n			if code > 127;\n		bytes.push(code);\n		i++;\n	}\n\n	return to_string( _jsonpointer_bytes_to_binary(bytes) );\n}\n\nfunction _jsonpointer_decode_token ( String raw ) {\n	let out := replace( raw, "~1", "/", "g" );\n	out := replace( out, "~0", "~", "g" );\n	return out;\n}\n\nfunction _jsonpointer_parse ( String raw ) {\n	die "JSONPointer parse error: pointer must be empty or start with \'/\'"\n		if raw \\u2262 "" and substr( raw, 0, 1 ) \\u2262 "/";\n\n	let steps := [];\n	return steps if raw \\u2261 "";\n\n	let i := 1;\n	let start := 1;\n	let n := length raw;\n\n	while ( i <= n ) {\n		if ( i \\u2261 n or substr( raw, i, 1 ) \\u2261 "/" ) {\n			let token := substr( raw, start, i - start );\n			let j := 0;\n			while ( j < length token ) {\n				if ( substr( token, j, 1 ) \\u2261 "~" ) {\n					die "JSONPointer parse error: invalid \'~\' escape"\n						if j + 1 >= length token;\n					let esc := substr( token, j + 1, 1 );\n					die "JSONPointer parse error: invalid \'~\' escape"\n						if esc \\u2262 "0" and esc \\u2262 "1";\n					j += 2;\n					next;\n				}\n				j++;\n			}\n			steps.push( _jsonpointer_decode_token(token) );\n			start := i + 1;\n		}\n		i++;\n	}\n\n	return steps;\n}\n\nfunction extract_pointer_from_url ( String url ) {\n	let hash := index( url, "#" );\n	if ( hash < 0 ) {\n		return {\n			baseurl: url,\n			pointer: null,\n		};\n	}\n\n	let pointer := _jsonpointer_percent_decode( substr( url, hash + 1 ) );\n	_jsonpointer_parse(pointer);\n\n	return {\n		baseurl: substr( url, 0, hash ),\n		pointer: pointer,\n	};\n}\n\nclass JSONPointer {\n	let String path;\n	let Array _steps := [];\n\n	static method use () {\n		from std/internals import setupperprop;\n		setupperprop( 1, "paths", self );\n	}\n\n	method __build__ () {\n		_steps := _jsonpointer_parse(path);\n	}\n\n	method expression () {\n		return path;\n	}\n\n	method _node ( value, parent, key ) {\n		return {\n			value: value,\n			parent: parent,\n			key: key,\n		};\n	}\n\n	method _evaluate_nodes ( value ) {\n		let current := [ self._node( value, null, null ) ];\n\n		for ( let step in _steps ) {\n			let next_nodes := [];\n\n			for ( let node in current ) {\n				let v := node{value};\n\n				if ( v instanceof Dict ) {\n					if ( v.exists(step) ) {\n						next_nodes.push( self._node( v.get(step), node, step ) );\n					}\n					next;\n				}\n\n				if ( v instanceof PairList ) {\n					let found := v.get_all(step);\n					if ( found.length() \\u2261 1 ) {\n						next_nodes.push( self._node( found[0], node, step ) );\n					}\n					next;\n				}\n\n				if ( v instanceof Array ) {\n					if ( step ~ /^(0|[1-9][0-9]*)$/ ) {\n						let idx := int(step);\n						if ( idx < v.length() ) {\n							next_nodes.push( self._node( v[idx], node, idx ) );\n						}\n					}\n					next;\n				}\n			}\n\n			current := next_nodes;\n		}\n\n		return current;\n	}\n\n	method _evaluate ( value ) {\n		return self._evaluate_nodes(value).map( fn n -> n{value} );\n	}\n\n	method get ( value ) {\n		return self._evaluate(value);\n	}\n\n	method select ( value ) {\n		return self._evaluate(value);\n	}\n\n	method query ( value ) {\n		return self._evaluate(value);\n	}\n\n	method first ( value, fallback? ) {\n		let out := self._evaluate(value);\n		return out.length() \\u2261 0 ? fallback : out[0];\n	}\n\n	method exists ( value ) {\n		return self._evaluate(value).length() > 0;\n	}\n\n	method _ref_for_node ( Dict node ) {\n		let parent := node{parent};\n		die "JSONPointer assignment target has no parent node"\n			if parent \\u2261 null;\n\n		let container := parent{value};\n		let key := node{key};\n\n		if ( container instanceof Array ) {\n			die "JSONPointer assignment expects numeric array index"\n				if not( key instanceof Number );\n			return \\\\ container[key];\n		}\n\n		if ( container instanceof Dict ) {\n			die "JSONPointer assignment expects string dict key"\n				if not( key instanceof String );\n			return \\\\ container{(key)};\n		}\n\n		if ( container instanceof PairList ) {\n			die "JSONPointer assignment expects string pairlist key"\n				if not( key instanceof String );\n			return \\\\ container{(key)};\n		}\n\n		die "JSONPointer assignment target container \'"\n			_ typeof container\n			_ "\' is not assignable";\n	}\n\n	method _apply_assignment_ref ( ref, value, op := ":=", weak := false ) {\n		die "JSONPointer weak assignment is not supported"\n			if weak;\n\n		if ( op \\u2261 ":=" ) {\n			return ref(value);\n		}\n\n		let current := ref();\n\n		if ( op \\u2261 "+=" ) {\n			current += value;\n		}\n		else if ( op \\u2261 "-=" ) {\n			current -= value;\n		}\n		else if ( op \\u2261 "*=" or op \\u2261 "\\xD7=" ) {\n			current *= value;\n		}\n		else if ( op \\u2261 "/=" or op \\u2261 "\\xF7=" ) {\n			current /= value;\n		}\n		else if ( op \\u2261 "**=" ) {\n			current **= value;\n		}\n		else if ( op \\u2261 "_=" ) {\n			current _= value;\n		}\n		else if ( op \\u2261 "?:=" ) {\n			current ?:= value;\n		}\n		else if ( op \\u2261 "~=" ) {\n			current ~= value[0] -> value[1](m);\n		}\n		else {\n			die \\`Unsupported path assignment operator \'\\${op}\'\\`;\n		}\n\n		ref(current);\n		return current;\n	}\n\n	method _assign_all_result ( value, op, last_result ) {\n		return op \\u2261 "~=" ? last_result : value;\n	}\n\n	method assign_first ( target, value, op := ":=", weak := false ) {\n		let nodes := self._evaluate_nodes(target);\n		die "JSONPointer assignment found no matches"\n			if nodes.length() \\u2261 0;\n		return self._apply_assignment_ref(\n			self._ref_for_node( nodes[0] ),\n			value,\n			op,\n			weak,\n		);\n	}\n\n	method assign_all ( target, value, op := ":=", weak := false ) {\n		let nodes := self._evaluate_nodes(target);\n		if ( nodes.length() \\u2261 0 ) {\n			return self._assign_all_result( value, op, value );\n		}\n\n		let last_result := value;\n		for ( let node in nodes ) {\n			last_result := self._apply_assignment_ref(\n				self._ref_for_node(node),\n				value,\n				op,\n				weak,\n			);\n		}\n\n		return self._assign_all_result( value, op, last_result );\n	}\n\n	method assign_maybe ( target, value, op := ":=", weak := false ) {\n		let nodes := self._evaluate_nodes(target);\n		if ( nodes.length() \\u2261 0 ) {\n			return false;\n		}\n\n		self._apply_assignment_ref(\n			self._ref_for_node( nodes[0] ),\n			value,\n			op,\n			weak,\n		);\n		return true;\n	}\n\n	method ref_first ( target ) {\n		let nodes := self._evaluate_nodes(target);\n		die "JSONPointer assignment found no matches"\n			if nodes.length() \\u2261 0;\n		return self._ref_for_node( nodes[0] );\n	}\n\n	method ref_all ( target ) {\n		let out := [];\n		for ( let node in self._evaluate_nodes(target) ) {\n			out.push( self._ref_for_node(node) );\n		}\n		return out;\n	}\n\n	method ref_maybe ( target ) {\n		let nodes := self._evaluate_nodes(target);\n		return nodes.length() \\u2261 0 ? null : self._ref_for_node( nodes[0] );\n	}\n}\n`;\n        virtualFiles["/modules/std/data/json/schema.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/data/json/schema - JSON Schema 2020-12 validation.\\n\\n=head1 SYNOPSIS\\n\\n  from std/data/json/schema import\\n    JSONSchema,\\n    RequiredPropertyError,\\n    TypeMismatchError,\\n    validate,\\n    valid;\\n\\n  let person_schema := {\\n    type: "object",\\n    required: [ "name" ],\\n    properties: {\\n      name: { type: "string" },\\n      age:  { type: "integer", minimum: 0 },\\n    },\\n  };\\n\\n  say( valid( person_schema, { name: "Ada", age: 37 } ) );\\n\\n  let result := validate( person_schema, { age: -1 } );\\n  for ( let error in result.errors() ) {\\n    if ( error instanceof RequiredPropertyError ) {\\n      say( error.instanceLocation() _ ": " _ error.error() );\\n    }\\n  }\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis Pure Zuzu module is supported by all implementations of ZuzuScript.\\nNetwork reference loading needs C<std/net/http>, so it is available only in\\nruntimes that provide that module.\\n\\n=head1 DESCRIPTION\\n\\nI<std/data/json/schema> validates native Zuzu values against JSON Schema\\n2020-12 schemas. It is intended for already-decoded JSON data: schemas and\\ninstances are normally C<Dict>, C<Array>, strings, numbers, booleans, and\\nC<null>.\\n\\nThe validator also accepts some native collection types where the JSON model\\nhas a clear equivalent. C<PairList> is treated as an object and preserves\\nduplicate keys for keywords that need to inspect them. C<Set> and C<Bag> are\\ntreated as array-like values when order is not important, though ordered\\ntuple validation is meaningful only for C<Array>.\\n\\nValidation can be requested in two forms. Boolean validation short-circuits\\nafter the first failure and returns C<true> or C<false>. Full validation\\ncollects errors and returns a C<ValidationResult> whose errors are proper\\nZuzu objects with methods such as C<keywordLocation()>,\\nC<instanceLocation()>, and C<error()>.\\n\\n=head1 EXPORTS\\n\\n=head2 Functions\\n\\n=over\\n\\n=item C<< valid( schema, instance, options := {} ) >>\\n\\nReturns C<true> when C<instance> satisfies C<schema>, otherwise C<false>.\\nThis mode is the cheapest validation mode and stops as soon as a failure is\\nknown.\\n\\n=item C<< validate( schema, instance, options := {} ) >>\\n\\nReturns a C<ValidationResult>. This mode attempts to collect every\\nindependent validation error it can find.\\n\\n=back\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<JSONSchema>\\n\\nCompiled schema wrapper. Construct with C<< new JSONSchema( schema: ... ) >>\\nor pass C<options> as a named field.\\n\\nCommon methods:\\n\\n=over\\n\\n=item C<< is_valid( instance ) >>\\n\\nBoolean validation with short-circuiting.\\n\\n=item C<< validate( instance ) >>\\n\\nFull validation returning a C<ValidationResult>.\\n\\n=back\\n\\n=item C<ValidationResult>\\n\\nThe structured result returned by C<validate>. C<valid()> returns the boolean\\nstatus. C<errors()> returns an array of C<ValidationError> objects.\\nC<to_Dict()> converts to a Basic-style output shape.\\n\\n=item C<ValidationError>\\n\\nBase class for validation errors. The canonical methods are\\nC<keywordLocation()>, C<absoluteKeywordLocation()>, C<instanceLocation()>,\\nC<error()>, C<keyword()>, C<details()>, and C<to_Dict()>.\\n\\nErrors are grouped under C<MissingValueError>, C<UnexpectedValueError>, and\\nC<WrongValueError>. The module exports specific subclasses for individual\\nkeywords such as C<RequiredPropertyError>, C<TypeMismatchError>,\\nC<MaximumError>, C<PatternError>, C<AdditionalPropertiesError>,\\nC<OneOfError>, and C<ReferenceResolutionError>.\\n\\n=item C<SubschemaError>\\n\\nError class used for the message C<A subschema had errors.>. Its\\nC<suberrors()> method returns weak links to the errors produced inside the\\nsubschema.\\n\\n=item C<SchemaRegistry>\\n\\nRegistry for schema resources, anchors, and references. It is usually\\nmanaged by C<JSONSchema>, but may be supplied in C<options> when several\\nschemas share references.\\n\\n=item C<HTTPResourceLoader>\\n\\nReference loader for HTTP and HTTPS resources. It is used only when supplied\\ndirectly or when C<allow_network> is true.\\n\\n=item C<FormatRegistry>\\n\\nRegistry of C<format> validators. A custom registry may be passed with the\\nC<formats> or C<format_registry> option.\\n\\n=item C<RelativeJSONPointer>\\n\\nParser and evaluator for Relative JSON Pointers. This class is exported\\nbecause JSON Schema uses the syntax for the C<relative-json-pointer> format\\nand because it is useful with schema-adjacent data tools.\\n\\n=back\\n\\n=head1 OPTIONS\\n\\nThe C<options> value may be a C<Dict> or C<PairList>.\\n\\n=over\\n\\n=item C<base_uri>\\n\\nBase URI used when registering the root schema and resolving relative\\nreferences.\\n\\n=item C<registry>\\n\\nA C<SchemaRegistry> to use for C<$ref> and C<$dynamicRef>.\\n\\n=item C<loader>\\n\\nA callable or object with a C<load(uri)> method used to fetch missing schema\\nresources.\\n\\n=item C<allow_network>\\n\\nWhen true and no loader is supplied, C<JSONSchema> creates an\\nC<HTTPResourceLoader>.\\n\\n=item C<formats> or C<format_registry>\\n\\nA C<FormatRegistry> used for C<format> checks.\\n\\n=item C<format_assert>\\n\\nWhen false, C<format> is treated as an annotation and does not make\\nvalidation fail.\\n\\n=item C<unknown_format>\\n\\nControls unknown formats. The default is C<fail>; C<ignore> treats unknown\\nformats as annotations.\\n\\n=back\\n\\n=head1 KNOWN OPTIONAL FIXTURE GAPS\\n\\nThe validator covers all required JSON Schema draft 2020-12 fixture files\\nand many optional fixture files. The following optional fixture files are not\\nyet promoted to the expected-passing set.\\n\\n=over\\n\\n=item F<optional/cross-draft.json>\\n\\nReferences into older schema drafts are resolved, but draft-specific\\nvalidation semantics for referenced historic drafts are not yet applied.\\n\\n=item F<optional/float-overflow.json>\\n\\nVery large numeric values still use the host numeric model, so overflow and\\nprecision edge cases for C<multipleOf> are not fully handled.\\n\\n=item F<optional/ecmascript-regex.json>\\n\\nThe JavaScript runtime passes this fixture, but the Perl and Rust runtimes do\\nnot yet emulate enough ECMAScript regular-expression semantics.\\n\\n=item F<optional/format/duration.json>\\n\\nThe C<duration> format checker accepts basic duration shapes, but does not\\nyet implement the full RFC 3339 duration grammar.\\n\\n=item F<optional/format/hostname.json>\\n\\nHostname validation is intentionally conservative and does not yet fully\\nvalidate A-label, Punycode, and IDNA edge cases.\\n\\n=item F<optional/format/idn-hostname.json>\\n\\nInternationalized hostname validation does not yet implement the full IDNA\\nUnicode category, normalization, and bidirectional-text rules.\\n\\n=item F<optional/format/ipv6.json>\\n\\nIPv6 validation is still simplified and misses some invalid compression and\\ngroup-length edge cases.\\n\\n=item F<optional/format/time.json>\\n\\nTime validation handles common RFC 3339 forms, but still has some leap-second\\nand timezone-offset edge cases.\\n\\n=item F<optional/format/uri.json>\\n\\nURI validation is stricter than a plain string check, but still accepts some\\ninvalid authority, userinfo, character, and port cases.\\n\\n=back\\n\\n=head1 PORTABILITY\\n\\nThe module is pure ZuzuScript. Behaviour that depends on regular expression\\ndetails or HTTP support may vary with the host runtime.\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/data/json/schema >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/data/json/schema/core import HTTPResourceLoader, SchemaRegistry;\\nfrom std/data/json/schema/format import FormatRegistry;\\nfrom std/data/json/schema/output import\\n	AdditionalItemsError,\\n	AdditionalPropertiesError,\\n	AllOfError,\\n	AnyOfError,\\n	ConstMismatchError,\\n	ContentEncodingError,\\n	ContentMediaTypeError,\\n	DependentRequiredPropertyError,\\n	EnumMismatchError,\\n	ExclusiveMaximumError,\\n	ExclusiveMinimumError,\\n	FalseSchemaError,\\n	FormatError,\\n	IfThenElseError,\\n	MaxContainsError,\\n	MaximumError,\\n	MaxItemsError,\\n	MaxLengthError,\\n	MaxPropertiesError,\\n	MinContainsError,\\n	MinimumError,\\n	MinItemsError,\\n	MinLengthError,\\n	MinPropertiesError,\\n	MissingValueError,\\n	MultipleOfError,\\n	NotMatchedError,\\n	OneOfError,\\n	PatternError,\\n	PropertyNamesError,\\n	ReferenceResolutionError,\\n	RequiredPropertyError,\\n	SubschemaError,\\n	TypeMismatchError,\\n	UnevaluatedItemsError,\\n	UnevaluatedPropertiesError,\\n	UnexpectedValueError,\\n	UniqueItemsError,\\n	UnknownFormatError,\\n	ValidationError,\\n	ValidationResult,\\n	WrongValueError;\\nfrom std/data/json/schema/relative_pointer import RelativeJSONPointer;\\nfrom std/data/json/schema/validation import JSONSchema, validate, valid;\\n\';\n        virtualFiles["/modules/std/data/json/schema/core.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/data/json/schema/core - JSON Schema resources and reference registry.\\n\\n=head1 SYNOPSIS\\n\\n  from std/data/json/schema/core import SchemaRegistry;\\n\\n  let registry := new SchemaRegistry();\\n  registry.register( address_schema, "https://example.test/address" );\\n\\n  let subschema := registry.resolve(\\n    "https://example.test/address#/properties/postcode",\\n  );\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis Pure Zuzu module is supported by all implementations of ZuzuScript.\\nC<HTTPResourceLoader> requires C<std/net/http> and dies at construction time\\nwhen that module is unavailable.\\n\\n=head1 DESCRIPTION\\n\\nThis module contains the resource and reference support used by\\nI<std/data/json/schema>. It registers schemas under base URIs, indexes\\nC<$id>, C<$anchor>, and C<$dynamicAnchor>, and resolves references to either\\nwhole resources or JSON Pointer fragments.\\n\\nMost callers should use C<JSONSchema> from I<std/data/json/schema>. Import\\nthis module directly when schemas need to share a registry or when reference\\nloading needs to be customised.\\n\\n=head1 EXPORTS\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<SchemaRegistry>\\n\\nStores schema resources and resolves references.\\n\\n=over\\n\\n=item C<< register( schema, uri := "" ) >>\\n\\nRegisters C<schema> at C<uri>, indexes nested C<$id> values and anchors, and\\nreturns the registry.\\n\\n=item C<< set_loader( loader ) >>\\n\\nSets the loader used for missing resources. A loader may be a callable or an\\nobject with a C<load(uri)> method. Loaded strings are decoded as JSON before\\nbeing registered.\\n\\n=item C<< resolve( ref, base := "" ) >>\\n\\nResolves C<ref> against C<base>. Empty fragments return the resource.\\nAnchor fragments use the registry\\\'s anchor index. Pointer fragments are\\nresolved with I<std/path/jsonpointer>. Failure to find a resource or target\\nthrows an exception.\\n\\n=back\\n\\n=item C<HTTPResourceLoader>\\n\\nSimple HTTP and HTTPS loader. C<load(uri)> fetches C<uri> with\\nC<std/net/http> and returns the response content after requiring a successful\\nresponse.\\n\\n=back\\n\\n=head2 Functions\\n\\n=over\\n\\n=item C<< jschema_uri_resolve( base, ref ) >>\\n\\nResolves the URI reference C<ref> against C<base> for the subset of URI\\nresolution needed by this validator.\\n\\n=item C<< jschema_url_split( url ) >>\\n\\nReturns a C<Dict> with C<baseurl> and C<fragment>. C<fragment> is C<null>\\nwhen C<url> has no C<#>.\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/data/json/schema/core >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/data/json import JSON;\\nfrom std/internals import ref_id;\\nfrom std/net/http try import UserAgent as _HTTPUserAgent;\\nfrom std/path/jsonpointer import JSONPointer;\\nfrom std/string import index, join, ord, split, substr;\\nfrom std/string/base64 import decode as _base64_decode;\\nfrom std/data/json/schema/model import\\n	jschema_is_object,\\n	jschema_object_entries,\\n	jschema_object_get,\\n	jschema_object_has;\\n\\nfunction jschema_url_split ( String url ) {\\n	let hash := index( url, "#" );\\n	if ( hash < 0 ) {\\n		return {\\n			baseurl: url,\\n			fragment: null,\\n		};\\n	}\\n	return {\\n		baseurl: substr( url, 0, hash ),\\n		fragment: substr( url, hash + 1 ),\\n	};\\n}\\n\\nlet _JSCHEMA_B64_ALPHABET := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"\\n	_ "abcdefghijklmnopqrstuvwxyz0123456789+/";\\n\\nfunction _jschema_div_floor ( Number n, Number d ) {\\n	return floor( n / d );\\n}\\n\\nfunction _jschema_mod ( Number n, Number d ) {\\n	return n - _jschema_div_floor( n, d ) * d;\\n}\\n\\nfunction _jschema_bytes_to_binary ( Array bytes ) {\\n	let out := "";\\n	let i := 0;\\n	let n := bytes.length();\\n\\n	while ( i < n ) {\\n		let b0 := bytes[i];\\n		let b1 := null;\\n		let b2 := null;\\n		if ( i + 1 < n ) {\\n			b1 := bytes[i + 1];\\n		}\\n		if ( i + 2 < n ) {\\n			b2 := bytes[i + 2];\\n		}\\n\\n		let c0 := _jschema_div_floor( b0, 4 );\\n		let c1 := _jschema_mod( b0, 4 ) * 16;\\n		let c2 := 64;\\n		let c3 := 64;\\n\\n		if ( not( b1 == null ) ) {\\n			c1 += _jschema_div_floor( b1, 16 );\\n			c2 := _jschema_mod( b1, 16 ) * 4;\\n			if ( not( b2 == null ) ) {\\n				c2 += _jschema_div_floor( b2, 64 );\\n				c3 := _jschema_mod( b2, 64 );\\n			}\\n		}\\n\\n		out _= substr( _JSCHEMA_B64_ALPHABET, c0, 1 );\\n		out _= substr( _JSCHEMA_B64_ALPHABET, c1, 1 );\\n		out _= c2 == 64 ? "=" : substr( _JSCHEMA_B64_ALPHABET, c2, 1 );\\n		out _= c3 == 64 ? "=" : substr( _JSCHEMA_B64_ALPHABET, c3, 1 );\\n		i += 3;\\n	}\\n\\n	return _base64_decode(out);\\n}\\n\\nfunction _jschema_hex_value ( String ch ) {\\n	if ( ch ~ /[0-9]/ ) {\\n		return 0 + ch;\\n	}\\n\\n	return 10 + index( "abcdef", lc(ch) );\\n}\\n\\nfunction jschema_percent_decode ( String text ) {\\n	let bytes := [];\\n	let i := 0;\\n	let n := length text;\\n\\n	while ( i < n ) {\\n		let ch := substr( text, i, 1 );\\n		if (\\n			ch \\u2261 "%"\\n			and i + 2 < n\\n			and substr( text, i + 1, 1 ) ~ /[0-9A-Fa-f]/\\n			and substr( text, i + 2, 1 ) ~ /[0-9A-Fa-f]/\\n		) {\\n			bytes.push(\\n				_jschema_hex_value( substr( text, i + 1, 1 ) ) * 16\\n				+ _jschema_hex_value( substr( text, i + 2, 1 ) ),\\n			);\\n			i += 3;\\n			next;\\n		}\\n\\n		let code := ord(ch);\\n		die "JSON Schema URI fragment contains non-ASCII literal character"\\n			if code > 127;\\n		bytes.push(code);\\n		i++;\\n	}\\n\\n	return to_string( _jschema_bytes_to_binary(bytes) );\\n}\\n\\nfunction _jschema_uri_query_split ( String uri ) {\\n	let query := index( uri, "?" );\\n	if ( query < 0 ) {\\n		return {\\n			path: uri,\\n			query: "",\\n		};\\n	}\\n	return {\\n		path: substr( uri, 0, query ),\\n		query: substr( uri, query ),\\n	};\\n}\\n\\nfunction _jschema_uri_parts ( String uri ) {\\n	let m := uri ~ /^([A-Za-z][A-Za-z0-9+.-]*:\\\\/\\\\/[^\\\\/?#]*)(.*)$/;\\n	if ( m ) {\\n		return {\\n			prefix: m[1],\\n			path_query: m[2],\\n		};\\n	}\\n\\n	m := uri ~ /^([A-Za-z][A-Za-z0-9+.-]*:)(.*)$/;\\n	if ( m ) {\\n		return {\\n			prefix: m[1],\\n			path_query: m[2],\\n		};\\n	}\\n\\n	return {\\n		prefix: "",\\n		path_query: uri,\\n	};\\n}\\n\\nfunction _jschema_remove_dot_segments ( String path ) {\\n	let absolute := length path > 0 and substr( path, 0, 1 ) eq "/";\\n	let trailing := length path > 1 and substr( path, length path - 1, 1 ) eq "/";\\n	let out := [];\\n\\n	for ( let segment in split( path, "/" ) ) {\\n		if ( segment eq "" or segment eq "." ) {\\n			next;\\n		}\\n		if ( segment eq ".." ) {\\n			if (\\n				out.length() > 0\\n				and out[out.length() - 1] ne ".."\\n			) {\\n				out.pop();\\n			}\\n			else if ( not absolute ) {\\n				out.push(segment);\\n			}\\n			next;\\n		}\\n		out.push(segment);\\n	}\\n\\n	let result := join( "/", out );\\n	if ( absolute ) {\\n		result := "/" _ result;\\n	}\\n	if ( trailing and result ne "/" ) {\\n		result _= "/";\\n	}\\n	if ( result eq "" and absolute ) {\\n		return "/";\\n	}\\n	return result;\\n}\\n\\nfunction jschema_uri_resolve ( String base, String ref ) {\\n	let split_ref := jschema_url_split(ref);\\n	let ref_base := split_ref{baseurl};\\n	let fragment := split_ref{fragment} \\u2261 null\\n		? ""\\n		: "#" _ split_ref{fragment};\\n\\n	if ( ref ~ /^[A-Za-z][A-Za-z0-9+.-]*:/ ) {\\n		let absolute_parts := _jschema_uri_parts(ref_base);\\n		let absolute_query := _jschema_uri_query_split(\\n			absolute_parts{path_query},\\n		);\\n		return absolute_parts{prefix}\\n			_ _jschema_remove_dot_segments(absolute_query{path})\\n			_ absolute_query{query}\\n			_ fragment;\\n	}\\n	if ( substr( ref, 0, 1 ) eq "#" ) {\\n		return jschema_url_split(base){baseurl} _ ref;\\n	}\\n	if ( base eq "" ) {\\n		return ref;\\n	}\\n\\n	let split_base := jschema_url_split(base){baseurl};\\n	if ( ref_base eq "" ) {\\n		return split_base _ fragment;\\n	}\\n\\n	let base_parts := _jschema_uri_parts(split_base);\\n	let base_query := _jschema_uri_query_split(base_parts{path_query});\\n	let ref_query := _jschema_uri_query_split(ref_base);\\n\\n	if ( substr( ref_base, 0, 1 ) eq "?" ) {\\n		return base_parts{prefix} _ base_query{path} _ ref_base _ fragment;\\n	}\\n\\n	if ( substr( ref_query{path}, 0, 1 ) eq "/" ) {\\n		return base_parts{prefix}\\n			_ _jschema_remove_dot_segments(ref_query{path})\\n			_ ref_query{query}\\n			_ fragment;\\n	}\\n\\n	let slash := -1;\\n	let i := 0;\\n	while ( i < length base_query{path} ) {\\n		if ( substr( base_query{path}, i, 1 ) eq "/" ) {\\n			slash := i;\\n		}\\n		i++;\\n	}\\n\\n	let base_dir := slash >= 0 ? substr( base_query{path}, 0, slash + 1 ) : "";\\n	return base_parts{prefix}\\n		_ _jschema_remove_dot_segments( base_dir _ ref_query{path} )\\n		_ ref_query{query}\\n		_ fragment;\\n}\\n\\nclass HTTPResourceLoader {\\n	let _ua := null;\\n\\n	method __build__ () {\\n		die "std/net/http UserAgent is unavailable in this runtime"\\n			if _HTTPUserAgent \\u2261 null;\\n		_ua := new _HTTPUserAgent();\\n	}\\n\\n	method load ( String uri ) {\\n		die `JSON Schema network loader only supports HTTP(S): ${uri}`\\n			unless uri ~ /^https?:/;\\n		return _ua.get(uri).expect_success().content();\\n	}\\n}\\n\\nclass SchemaRegistry {\\n	let _resources := {};\\n	let _anchors := {};\\n	let _dynamic_anchors := {};\\n	let _schema_bases := [];\\n	let _loader := null;\\n	let Boolean allow_network := false;\\n	let _json := null;\\n\\n	method __build__ () {\\n		_json := new JSON();\\n	}\\n\\n	method set_loader ( loader ) {\\n		_loader := loader;\\n		return self;\\n	}\\n\\n	method register ( schema, String uri := "" ) {\\n		_resources.set( uri, schema );\\n		self._index_schema( schema, uri );\\n		return self;\\n	}\\n\\n	method _index_subschema ( schema, String base ) {\\n		if ( jschema_is_object(schema) ) {\\n			self._index_schema( schema, base );\\n		}\\n	}\\n\\n	method _index_subschema_array ( value, String base ) {\\n		if ( not( value instanceof Array ) ) {\\n			return;\\n		}\\n		for ( let item in value ) {\\n			self._index_subschema( item, base );\\n		}\\n	}\\n\\n	method _index_subschema_map ( value, String base ) {\\n		if ( not jschema_is_object(value) ) {\\n			return;\\n		}\\n		for ( let entry in jschema_object_entries(value) ) {\\n			self._index_subschema( entry[1], base );\\n		}\\n	}\\n\\n	method _index_schema ( schema, String base ) {\\n		if ( not jschema_is_object(schema) ) {\\n			return;\\n		}\\n		let current_base := base;\\n\\n		if (\\n			jschema_object_has( schema, "$id" )\\n			and jschema_object_get( schema, "$id" ) instanceof String\\n		) {\\n			current_base := jschema_uri_resolve(\\n				current_base,\\n				jschema_object_get( schema, "$id" ),\\n			);\\n			_resources.set( current_base, schema );\\n		}\\n		_schema_bases.push( {\\n			id: ref_id(schema),\\n			base: current_base,\\n		} );\\n		if (\\n			jschema_object_has( schema, "$anchor" )\\n			and jschema_object_get( schema, "$anchor" ) instanceof String\\n		) {\\n			_anchors.set(\\n				current_base _ "#" _ jschema_object_get( schema, "$anchor" ),\\n				schema,\\n			);\\n		}\\n		if (\\n			jschema_object_has( schema, "$dynamicAnchor" )\\n			and jschema_object_get( schema, "$dynamicAnchor" ) instanceof String\\n		) {\\n			_anchors.set(\\n				current_base _ "#" _ jschema_object_get( schema, "$dynamicAnchor" ),\\n				schema,\\n			);\\n			_dynamic_anchors.set(\\n				current_base _ "#" _ jschema_object_get( schema, "$dynamicAnchor" ),\\n				schema,\\n			);\\n		}\\n\\n		self._index_subschema_map( jschema_object_get( schema, "$defs" ), current_base );\\n		self._index_subschema_map( jschema_object_get( schema, "definitions" ), current_base );\\n		self._index_subschema_map( jschema_object_get( schema, "properties" ), current_base );\\n		self._index_subschema_map( jschema_object_get( schema, "patternProperties" ), current_base );\\n		self._index_subschema_map( jschema_object_get( schema, "dependentSchemas" ), current_base );\\n\\n		if ( jschema_is_object( jschema_object_get( schema, "dependencies" ) ) ) {\\n			for ( let entry in jschema_object_entries( jschema_object_get( schema, "dependencies" ) ) ) {\\n				self._index_subschema( entry[1], current_base );\\n			}\\n		}\\n\\n		self._index_subschema_array( jschema_object_get( schema, "allOf" ), current_base );\\n		self._index_subschema_array( jschema_object_get( schema, "anyOf" ), current_base );\\n		self._index_subschema_array( jschema_object_get( schema, "oneOf" ), current_base );\\n		self._index_subschema_array( jschema_object_get( schema, "prefixItems" ), current_base );\\n\\n		self._index_subschema( jschema_object_get( schema, "not" ), current_base );\\n		self._index_subschema( jschema_object_get( schema, "if" ), current_base );\\n		self._index_subschema( jschema_object_get( schema, "then" ), current_base );\\n		self._index_subschema( jschema_object_get( schema, "else" ), current_base );\\n		self._index_subschema( jschema_object_get( schema, "items" ), current_base );\\n		self._index_subschema( jschema_object_get( schema, "contains" ), current_base );\\n		self._index_subschema( jschema_object_get( schema, "additionalProperties" ), current_base );\\n		self._index_subschema( jschema_object_get( schema, "unevaluatedItems" ), current_base );\\n		self._index_subschema( jschema_object_get( schema, "unevaluatedProperties" ), current_base );\\n		self._index_subschema( jschema_object_get( schema, "propertyNames" ), current_base );\\n		self._index_subschema( jschema_object_get( schema, "contentSchema" ), current_base );\\n	}\\n\\n	method _load_resource ( String uri ) {\\n		if ( _loader \\u2261 null ) {\\n			return null;\\n		}\\n\\n		let loaded;\\n		if ( _loader can load ) {\\n			loaded := _loader.load(uri);\\n		}\\n		else {\\n			loaded := _loader(uri);\\n		}\\n		if ( loaded instanceof String ) {\\n			loaded := _json.decode(loaded);\\n		}\\n		else if ( loaded instanceof BinaryString ) {\\n			loaded := _json.decode_binarystring(loaded);\\n		}\\n		self.register( loaded, uri );\\n		return loaded;\\n	}\\n\\n	method resolve_info ( String ref, String base := "" ) {\\n		let absolute_uri := jschema_uri_resolve( base, ref );\\n		let split := jschema_url_split(absolute_uri);\\n		let resource_uri := split{baseurl};\\n		let fragment := split{fragment} \\u2261 null\\n			? null\\n			: jschema_percent_decode(split{fragment});\\n\\n		let resource := _resources.exists(resource_uri)\\n			? _resources.get(resource_uri)\\n			: self._load_resource(resource_uri);\\n		if ( resource \\u2261 null ) {\\n			die `JSON Schema reference not found: ${absolute_uri}`;\\n		}\\n\\n		let target := resource;\\n		if ( fragment \\u2262 null and fragment ne "" ) {\\n			let anchor_uri := resource_uri _ "#" _ fragment;\\n			if ( _anchors.exists(anchor_uri) ) {\\n				target := _anchors.get(anchor_uri);\\n			}\\n			else {\\n				die `JSON Schema reference fragment is not a JSON Pointer: ${absolute_uri}`\\n					unless substr( fragment, 0, 1 ) eq "/";\\n\\n				target := new JSONPointer( path: fragment ).first( resource, null );\\n				die `JSON Schema reference target not found: ${absolute_uri}`\\n					if target \\u2261 null;\\n			}\\n		}\\n\\n		return {\\n			target: target,\\n			absolute_uri: absolute_uri,\\n			resource_uri: resource_uri,\\n			fragment: fragment,\\n		};\\n	}\\n\\n	method resolve ( String ref, String base := "" ) {\\n		return self.resolve_info( ref, base ){target};\\n	}\\n\\n	method dynamic_anchor ( String resource_uri, String name ) {\\n		let key := resource_uri _ "#" _ name;\\n		return _dynamic_anchors.exists(key)\\n			? _dynamic_anchors.get(key)\\n			: null;\\n	}\\n\\n	method has_dynamic_anchor ( String resource_uri, String name ) {\\n		return _dynamic_anchors.exists( resource_uri _ "#" _ name );\\n	}\\n\\n	method schema_base ( schema, fallback := null ) {\\n		let id := ref_id(schema);\\n		for ( let entry in _schema_bases ) {\\n			if ( entry{id} \\u2261 id ) {\\n				return entry{base};\\n			}\\n		}\\n		return fallback;\\n	}\\n}\\n\';\n        virtualFiles["/modules/std/data/json/schema/format.zzm"] = `=encoding utf8\n\n=head1 NAME\n\nstd/data/json/schema/format - JSON Schema format validators.\n\n=head1 SYNOPSIS\n\n  from std/data/json/schema/format import FormatRegistry;\n\n  let formats := new FormatRegistry();\n  formats.register( "slug", fn value -> value ~ /^[a-z0-9-]+$/ );\n\n  say( formats.check( "slug", "release-2026" ) );\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis Pure Zuzu module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nI<std/data/json/schema/format> provides the C<format> registry used by the\nJSON Schema validator. A registry maps format names to callables. A callable\nreceives the instance value and returns true when the value satisfies the\nformat.\n\nThe default registry includes validators for the standard JSON Schema\nformats: C<date-time>, C<date>, C<time>, C<duration>, C<email>,\nC<idn-email>, C<hostname>, C<idn-hostname>, C<ipv4>, C<ipv6>, C<uri>,\nC<uri-reference>, C<iri>, C<iri-reference>, C<uuid>, C<json-pointer>,\nC<relative-json-pointer>, and C<regex>.\n\nFormat checking is controlled by the validator. By default C<format> is\nannotation-only; pass C<< format_assert: true >> to C<JSONSchema> to make it\nassertive.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<FormatRegistry>\n\nRegistry of named format validators.\n\n=over\n\n=item C<< register( name, validator ) >>\n\nRegisters C<validator> under C<name> and returns the registry. The validator\nmay be any callable value.\n\n=item C<< has( name ) >>\n\nReturns true when a validator has been registered for C<name>.\n\n=item C<< check( name, value ) >>\n\nReturns the result of the named validator. Unknown names return C<false>;\nthe higher-level validator decides whether an unknown format is ignored or\nreported as an error.\n\n=back\n\n=back\n\n=head1 PORTABILITY\n\nSome validators rely on the host runtime\'s regular expression engine. The\nvalidators are intentionally conservative and do not attempt full RFC-grade\nparsing for every format.\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/data/json/schema/format >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/internals import to_Regexp_with_flags;\nfrom std/path/jsonpointer import JSONPointer;\nfrom std/data/json/schema/relative_pointer import valid_relative_json_pointer;\nfrom std/string import index, ord, substr, split;\n\nfunction _fmt_ipv4_ok;\nfunction _fmt_ipv6_ok;\nfunction _fmt_uri_reference_ok;\nfunction _fmt_regex_hex;\n\nfunction _fmt_regex ( String pattern ) {\n	return fn value -> value instanceof String\n		and value ~ to_Regexp_with_flags(pattern, "u");\n}\n\nfunction _fmt_date_parts_ok ( String value ) {\n	let m := value ~ /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/;\n	if ( not m ) { return false; }\n	let month := int(m[2]);\n	let day := int(m[3]);\n	if ( month < 1 or month > 12 ) { return false; }\n	let max := 31;\n	if ( month in [ 4, 6, 9, 11 ] ) {\n		max := 30;\n	}\n	else if ( month == 2 ) {\n		let year := int(m[1]);\n		let leap := ( year mod 400 == 0 )\n			or ( year mod 4 == 0 and year mod 100 != 0 );\n		max := leap ? 29 : 28;\n	}\n	return day >= 1 and day <= max;\n}\n\nfunction _fmt_time_ok ( String value ) {\n	let m := value ~ /^([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\\\\.[0-9]+)?(?:[Zz]|([+-])([0-9]{2}):([0-9]{2}))$/;\n	if ( not m ) { return false; }\n	let hour := int(m[1]);\n	let minute := int(m[2]);\n	let second := int(m[3]);\n	let has_offset := m[4] instanceof String and m[4] ne "";\n	if ( hour > 23 or minute > 59 ) { return false; }\n	if ( second > 60 ) { return false; }\n	if ( has_offset ) {\n		if ( int(m[5]) > 23 or int(m[6]) > 59 ) { return false; }\n	}\n	if ( second == 60 and minute != 59 ) { return false; }\n	if ( second == 60 and not has_offset and hour != 23 ) { return false; }\n	return true;\n}\n\nfunction _fmt_date_time_ok ( value ) {\n	if ( not( value instanceof String ) ) { return false; }\n	let m := value ~ /^([0-9]{4}-[0-9]{2}-[0-9]{2})[Tt]([0-9]{2}:[0-9]{2}:[0-9]{2}(?:\\\\.[0-9]+)?(?:[Zz]|[+-][0-9]{2}:[0-9]{2}))$/;\n	return m and _fmt_date_parts_ok(m[1]) and _fmt_time_ok(m[2]);\n}\n\nfunction _fmt_date_ok ( value ) {\n	return value instanceof String and _fmt_date_parts_ok(value);\n}\n\nfunction _fmt_time_value_ok ( value ) {\n	return value instanceof String and _fmt_time_ok(value);\n}\n\nfunction _fmt_duration_ok ( value ) {\n	return value instanceof String\n		and length value > 1\n		and value ~ /^P[0-9YMWDTHS.,+-]+$/;\n}\n\nfunction _fmt_hostname_ok ( value ) {\n	if ( not( value instanceof String ) ) { return false; }\n	if ( length value > 253 ) { return false; }\n	if ( value eq "" ) { return false; }\n	for ( let label in split( value, "." ) ) {\n		if ( label eq "" or length label > 63 ) { return false; }\n		if ( not( label ~ /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/ ) ) {\n			return false;\n		}\n	}\n	return true;\n}\n\nfunction _fmt_email_ok ( value ) {\n	if ( not( value instanceof String ) ) { return false; }\n	let address;\n	try {\n		from std/mail import Address;\n		address := Address.parse(value);\n	}\n	catch {\n		return false;\n	}\n	if ( address.display_name() \\u2262 null ) { return false; }\n	let domain := address.domain();\n	if ( substr( domain, 0, 1 ) eq "[" ) {\n		let inner := substr( domain, 1, length domain - 2 );\n		if ( substr( inner, 0, 5 ) eq "IPv6:" ) {\n			return _fmt_ipv6_ok( substr( inner, 5 ) );\n		}\n		return _fmt_ipv4_ok(inner);\n	}\n	return _fmt_hostname_ok(domain);\n}\n\nfunction _fmt_idn_hostname_ok ( value ) {\n	if ( not( value instanceof String ) ) { return false; }\n	if ( length value > 253 ) { return false; }\n	if ( value eq "" or value ~ /\\\\s/ ) { return false; }\n	for ( let label in split( value, "." ) ) {\n		if ( label eq "" or length label > 63 ) { return false; }\n		if ( substr( label, 0, 1 ) eq "-" ) { return false; }\n		if ( substr( label, length label - 1, 1 ) eq "-" ) { return false; }\n	}\n	return true;\n}\n\nfunction _fmt_idn_email_ok ( value ) {\n	if ( not( value instanceof String ) ) { return false; }\n	let m := value ~ /^([^@\\\\s]+)@([^@\\\\s]+)$/;\n	return m and _fmt_idn_hostname_ok(m[2]);\n}\n\nfunction _fmt_ipv4_ok ( value ) {\n	if ( not( value instanceof String ) ) { return false; }\n	if ( value ~ /[\\\\r\\\\n]/ ) { return false; }\n	if ( value eq "" or substr( value, 0, 1 ) eq "." ) { return false; }\n	if ( substr( value, length value - 1, 1 ) eq "." ) { return false; }\n	let parts := split( value, "." );\n	if ( parts.length() != 4 ) { return false; }\n	for ( let part in parts ) {\n		if ( not( part ~ /^(0|[1-9][0-9]*)$/ ) ) { return false; }\n		let n := int(part);\n		if ( n > 255 ) { return false; }\n	}\n	return true;\n}\n\nfunction _fmt_ipv6_ok ( value ) {\n	if ( not( value instanceof String ) ) { return false; }\n	if ( not( value ~ /^[0-9A-Fa-f:.]+$/ ) ) { return false; }\n	if ( value ~ /::/ ) { return true; }\n	return split( value, ":" ).length() == 8;\n}\n\nfunction _fmt_uri_ok ( value ) {\n	return value instanceof String\n		and value ~ /^[A-Za-z][A-Za-z0-9+.-]*:[^\\\\s]*$/\n		and _fmt_uri_reference_ok(value);\n}\n\nfunction _fmt_uri_chars_ok ( String value, Boolean allow_non_ascii ) {\n	if ( value ~ /[\\\\s\\\\\\\\]/ ) { return false; }\n	let i := 0;\n	while ( i < length value ) {\n		let ch := substr( value, i, 1 );\n		let cp := ord(ch);\n		if ( ch eq "%" ) {\n			if ( not _fmt_regex_hex( value, i + 1, 2 ) ) {\n				return false;\n			}\n			i += 3;\n			next;\n		}\n		if ( not allow_non_ascii and cp > 127 ) {\n			return false;\n		}\n		i++;\n	}\n	return true;\n}\n\nfunction _fmt_uri_reference_ok ( value ) {\n	return value instanceof String and _fmt_uri_chars_ok( value, false );\n}\n\nfunction _fmt_last_index ( String value, String needle ) {\n	let found := -1;\n	let i := 0;\n	while ( i < length value ) {\n		if ( substr( value, i, length needle ) eq needle ) {\n			found := i;\n		}\n		i++;\n	}\n	return found;\n}\n\nfunction _fmt_authority_from_iri ( String value ) {\n	let scheme := index( value, ":" );\n	if ( scheme < 0 or substr( value, scheme + 1, 2 ) ne "//" ) {\n		return null;\n	}\n	let start := scheme + 3;\n	let end := start;\n	while ( end < length value ) {\n		let ch := substr( value, end, 1 );\n		if ( ch eq "/" or ch eq "?" or ch eq "#" ) {\n			last;\n		}\n		end++;\n	}\n	return substr( value, start, end - start );\n}\n\nfunction _fmt_colon_count ( String value ) {\n	let count := 0;\n	let i := 0;\n	while ( i < length value ) {\n		if ( substr( value, i, 1 ) eq ":" ) {\n			count++;\n		}\n		i++;\n	}\n	return count;\n}\n\nfunction _fmt_iri_authority_ok ( String authority ) {\n	if ( authority eq "" or authority ~ /[\\\\s\\\\\\\\]/ ) { return false; }\n	let hostport := authority;\n	let at := _fmt_last_index( authority, "@" );\n	if ( at >= 0 ) {\n		hostport := substr( authority, at + 1 );\n	}\n	if ( hostport eq "" ) { return false; }\n	if ( substr( hostport, 0, 1 ) eq "[" ) {\n		let close := index( hostport, "]" );\n		if ( close < 0 ) { return false; }\n		let literal := substr( hostport, 1, close - 1 );\n		let rest := substr( hostport, close + 1 );\n		if ( not _fmt_ipv6_ok(literal) ) { return false; }\n		return rest eq "" or rest ~ /^:[0-9]+$/;\n	}\n	return _fmt_colon_count(hostport) <= 1;\n}\n\nfunction _fmt_iri_ok ( value ) {\n	if ( not( value instanceof String ) ) { return false; }\n	if ( not _fmt_uri_chars_ok( value, true ) ) { return false; }\n	if ( not( value ~ /^[A-Za-z][A-Za-z0-9+.-]*:/ ) ) { return false; }\n	let authority := _fmt_authority_from_iri(value);\n	return authority \\u2261 null or _fmt_iri_authority_ok(authority);\n}\n\nfunction _fmt_iri_reference_ok ( value ) {\n	if ( not( value instanceof String ) ) { return false; }\n	if ( not _fmt_uri_chars_ok( value, true ) ) { return false; }\n	if ( value ~ /^[A-Za-z][A-Za-z0-9+.-]*:/ ) {\n		return _fmt_iri_ok(value);\n	}\n	if ( substr( value, 0, 2 ) eq "//" ) {\n		let authority := _fmt_authority_from_iri( "x:" _ value );\n		return authority \\u2262 null and _fmt_iri_authority_ok(authority);\n	}\n	return true;\n}\n\nfunction _fmt_regex_hex ( String value, Number start, Number count ) {\n	if ( start + count > length value ) {\n		return false;\n	}\n	let i := start;\n	while ( i < start + count ) {\n		if ( not( substr( value, i, 1 ) ~ /[0-9A-Fa-f]/ ) ) {\n			return false;\n		}\n		i++;\n	}\n	return true;\n}\n\nfunction _fmt_regex_escape_ok ( String value, Number slash, Boolean in_class ) {\n	if ( slash + 1 >= length value ) {\n		return {\n			ok: false,\n			next: slash + 1,\n		};\n	}\n\n	let esc := substr( value, slash + 1, 1 );\n	if ( esc ~ /[fnrtv0bBdDsSwW]/ ) {\n		return {\n			ok: true,\n			next: slash + 2,\n		};\n	}\n	if ( esc eq "c" ) {\n		return {\n			ok: slash + 2 < length value\n				and substr( value, slash + 2, 1 ) ~ /[A-Za-z]/,\n			next: slash + 3,\n		};\n	}\n	if ( esc eq "x" ) {\n		return {\n			ok: _fmt_regex_hex( value, slash + 2, 2 ),\n			next: slash + 4,\n		};\n	}\n	if ( esc eq "u" ) {\n		if ( slash + 2 < length value and substr( value, slash + 2, 1 ) eq "{" ) {\n			let i := slash + 3;\n			let digits := 0;\n			while ( i < length value and substr( value, i, 1 ) ne "}" ) {\n				if ( not( substr( value, i, 1 ) ~ /[0-9A-Fa-f]/ ) ) {\n					return {\n						ok: false,\n						next: i + 1,\n					};\n				}\n				digits++;\n				i++;\n			}\n			return {\n				ok: i < length value and digits > 0,\n				next: i + 1,\n			};\n		}\n		return {\n			ok: _fmt_regex_hex( value, slash + 2, 4 ),\n			next: slash + 6,\n		};\n	}\n	if ( esc eq "p" or esc eq "P" ) {\n		let open := slash + 2;\n		if ( open >= length value or substr( value, open, 1 ) ne "{" ) {\n			return {\n				ok: false,\n				next: open,\n			};\n		}\n		let close := open + 1;\n		while ( close < length value and substr( value, close, 1 ) ne "}" ) {\n			close++;\n		}\n		return {\n			ok: close < length value and close > open + 1,\n			next: close + 1,\n		};\n	}\n	if ( esc ~ /[A-Za-z]/ ) {\n		return {\n			ok: false,\n			next: slash + 2,\n		};\n	}\n\n	return {\n		ok: true,\n		next: slash + 2,\n	};\n}\n\nfunction _fmt_json_pointer_ok ( value ) {\n	if ( not( value instanceof String ) ) { return false; }\n	try {\n		new JSONPointer( path: value );\n		return true;\n	}\n	catch {\n		return false;\n	}\n}\n\nfunction _fmt_regex_ok ( value ) {\n	if ( not( value instanceof String ) ) { return false; }\n	let parens := 0;\n	let in_class := false;\n	let class_items := 0;\n	let i := 0;\n\n	while ( i < length value ) {\n		let ch := substr( value, i, 1 );\n		if ( ch eq "\\\\\\\\" ) {\n			let escaped := _fmt_regex_escape_ok( value, i, in_class );\n			if ( not escaped{ok} ) {\n				return false;\n			}\n			if ( in_class ) {\n				class_items++;\n			}\n			i := escaped{next};\n			next;\n		}\n		if ( in_class ) {\n			if ( ch eq "]" and class_items > 0 ) {\n				in_class := false;\n			}\n			else {\n				class_items++;\n			}\n			i++;\n			next;\n		}\n		if ( ch eq "[" ) {\n			in_class := true;\n			class_items := 0;\n		}\n		else if ( ch eq "]" ) {\n			return false;\n		}\n		else if ( ch eq "(" ) {\n			parens++;\n		}\n		else if ( ch eq ")" ) {\n			if ( parens == 0 ) {\n				return false;\n			}\n			parens--;\n		}\n		i++;\n	}\n\n	if ( in_class or parens != 0 ) {\n		return false;\n	}\n\n	try {\n		to_Regexp_with_flags(value, "u");\n		return true;\n	}\n	catch {\n		return false;\n	}\n}\n\nfunction _fmt_uri_template_ok ( value ) {\n	if ( not( value instanceof String ) ) { return false; }\n	let depth := 0;\n	let expr := "";\n	let i := 0;\n	while ( i < length value ) {\n		let ch := substr( value, i, 1 );\n		if ( ch eq "{" ) {\n			if ( depth != 0 ) { return false; }\n			depth := 1;\n			expr := "";\n		}\n		else if ( ch eq "}" ) {\n			if ( depth != 1 or expr eq "" ) { return false; }\n			if ( not( expr ~ /^[+#./;?&]?[A-Za-z0-9_][A-Za-z0-9_.%]*(?::[1-9][0-9]{0,3})?$/ ) ) {\n				return false;\n			}\n			depth := 0;\n		}\n		else if ( depth == 1 ) {\n			expr _= ch;\n		}\n		i++;\n	}\n	return depth == 0;\n}\n\nclass FormatRegistry {\n	let _validators := {};\n\n	method __build__ () {\n		self.register( "date-time", _fmt_date_time_ok );\n		self.register( "date", _fmt_date_ok );\n		self.register( "time", _fmt_time_value_ok );\n		self.register( "duration", _fmt_duration_ok );\n		self.register( "email", _fmt_email_ok );\n		self.register( "idn-email", _fmt_idn_email_ok );\n		self.register( "hostname", _fmt_hostname_ok );\n		self.register( "idn-hostname", _fmt_idn_hostname_ok );\n		self.register( "ipv4", _fmt_ipv4_ok );\n		self.register( "ipv6", _fmt_ipv6_ok );\n		self.register( "uri", _fmt_uri_ok );\n		self.register( "uri-reference", _fmt_uri_reference_ok );\n		self.register( "iri", _fmt_iri_ok );\n		self.register( "iri-reference", _fmt_iri_reference_ok );\n		self.register( "uuid", _fmt_regex(\n			"^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$",\n		) );\n		self.register( "json-pointer", _fmt_json_pointer_ok );\n		self.register(\n			"relative-json-pointer",\n			fn v -> v instanceof String and valid_relative_json_pointer(v),\n		);\n		self.register( "regex", _fmt_regex_ok );\n		self.register( "uri-template", _fmt_uri_template_ok );\n	}\n\n	method register ( String name, validator ) {\n		_validators.set( name, validator );\n		return self;\n	}\n\n	method has ( String name ) {\n		return _validators.exists(name);\n	}\n\n	method check ( String name, value ) {\n		if ( not self.has(name) ) { return false; }\n		return _validators.get(name)(value);\n	}\n}\n`;\n        virtualFiles["/modules/std/data/json/schema/model.zzm"] = `=encoding utf8\n\n=head1 NAME\n\nstd/data/json/schema/model - JSON value projection helpers.\n\n=head1 SYNOPSIS\n\n  from std/data/json/schema/model import\n    jschema_is_object,\n    jschema_object_get,\n    jschema_type_name;\n\n  if ( jschema_is_object(value) ) {\n    say( jschema_object_get( value, "title", "(untitled)" ) );\n  }\n\n  say( jschema_type_name(value) );\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis Pure Zuzu module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module adapts native Zuzu collection types to the JSON data model used\nby the JSON Schema validator. It is mostly an implementation helper, but its\nfunctions are exported so related schema tools can share the same treatment\nof objects, arrays, and pointer locations.\n\nC<Dict> and C<PairList> are object-like. C<PairList> preserves duplicate\nkeys through C<jschema_object_get_all> and C<jschema_object_entries>. C<Array>\nis ordered array-like. C<Set> and C<Bag> are unordered array-like; they can\nbe used for array keywords where order does not matter.\n\n=head1 EXPORTS\n\n=head2 Functions\n\n=over\n\n=item C<< jschema_is_object( value ) >>\n\nReturns true for C<Dict> and C<PairList>.\n\n=item C<< jschema_is_ordered_array( value ) >>\n\nReturns true for C<Array>.\n\n=item C<< jschema_is_unordered_array( value ) >>\n\nReturns true for C<Set> and C<Bag>.\n\n=item C<< jschema_is_arrayish( value ) >>\n\nReturns true for ordered and unordered array-like values.\n\n=item C<< jschema_type_name( value ) >>\n\nReturns the JSON Schema type name for C<value>: C<null>, C<boolean>,\nC<number>, C<string>, C<array>, C<object>, or C<unknown>.\n\n=item C<< jschema_type_matches( value, expected ) >>\n\nReturns true when C<value> matches the JSON Schema type named by\nC<expected>. C<integer> is accepted for numbers with no fractional part.\n\n=item C<< jschema_object_has( object, key ) >>\n\nReturns true when an object-like value contains C<key>.\n\n=item C<< jschema_object_get( object, key, fallback := null ) >>\n\nReturns the value for C<key>, or C<fallback> when it is missing.\n\n=item C<< jschema_object_get_all( object, key ) >>\n\nReturns all values for C<key>. For C<Dict>, the result has either one value\nor none. For C<PairList>, duplicate keys are preserved.\n\n=item C<< jschema_object_keys( object ) >>\n\nReturns object keys, preserving the underlying collection\'s key behaviour.\n\n=item C<< jschema_object_unique_keys( object ) >>\n\nReturns object keys with duplicates removed.\n\n=item C<< jschema_object_entries( object ) >>\n\nReturns an array of C<[ key, value ]> pairs.\n\n=item C<< jschema_array_items( value ) >>\n\nReturns the array items for an array-like value. Unordered collections are\nconverted with C<to_Array()>.\n\n=item C<< jschema_array_length( value ) >>\n\nReturns the length of an array-like value, or zero for other values.\n\n=item C<< jschema_pointer_escape( token ) >>\n\nEscapes a JSON Pointer token by replacing C<~> and C</>.\n\n=item C<< jschema_pointer_join( base, step ) >>\n\nAppends C<step> to a JSON Pointer path.\n\n=item C<< jschema_deep_equal( left, right ) >>\n\nCompares two values using ZuzuScript equality. The validator uses this for\nC<const>, C<enum>, and uniqueness checks.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/data/json/schema/model >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/string import replace;\n\nfunction jschema_is_object ( value ) {\n	return value instanceof Dict or value instanceof PairList;\n}\n\nfunction jschema_is_ordered_array ( value ) {\n	return value instanceof Array;\n}\n\nfunction jschema_is_unordered_array ( value ) {\n	return value instanceof Set or value instanceof Bag;\n}\n\nfunction jschema_is_arrayish ( value ) {\n	return jschema_is_ordered_array(value)\n		or jschema_is_unordered_array(value);\n}\n\nfunction jschema_type_name ( value ) {\n	if ( value \\u2261 null ) { return "null"; }\n	if ( value instanceof Boolean ) { return "boolean"; }\n	if ( value instanceof Number ) { return "number"; }\n	if ( value instanceof String or value instanceof BinaryString ) {\n		return "string";\n	}\n	if ( jschema_is_arrayish(value) ) { return "array"; }\n	if ( jschema_is_object(value) ) { return "object"; }\n	return "unknown";\n}\n\nfunction jschema_type_matches ( value, String expected ) {\n	switch ( expected : eq ) {\n		case "null":    return value \\u2261 null;\n		case "boolean": return value instanceof Boolean;\n		case "number":  return value instanceof Number;\n		case "integer": return value instanceof Number and floor(value) == value;\n		case "string":\n			return value instanceof String or value instanceof BinaryString;\n		case "array":   return jschema_is_arrayish(value);\n		case "object":  return jschema_is_object(value);\n	}\n	return false;\n}\n\nfunction jschema_object_has ( object, String key ) {\n	if ( object instanceof Dict or object instanceof PairList ) {\n		for ( let existing in object.keys() ) {\n			if ( existing eq key ) { return true; }\n		}\n	}\n	return false;\n}\n\nfunction jschema_object_get ( object, String key, fallback := null ) {\n	if ( object instanceof Dict or object instanceof PairList ) {\n		return jschema_object_has(object, key) ? object.get(key) : fallback;\n	}\n	return fallback;\n}\n\nfunction jschema_object_get_all ( object, String key ) {\n	if ( object instanceof Dict ) {\n		return jschema_object_has(object, key) ? [ object.get(key) ] : [];\n	}\n	if ( object instanceof PairList ) {\n		return object.get_all(key);\n	}\n	return [];\n}\n\nfunction jschema_object_keys ( object ) {\n	if ( object instanceof Dict or object instanceof PairList ) {\n		return object.keys();\n	}\n	return [];\n}\n\nfunction jschema_object_unique_keys ( object ) {\n	let out := [];\n	for ( let key in jschema_object_keys(object) ) {\n		if ( not( key in out ) ) {\n			out.push(key);\n		}\n	}\n	return out;\n}\n\nfunction jschema_object_entries ( object ) {\n	let out := [];\n	if ( object instanceof Dict ) {\n		for ( let key in object.keys() ) {\n			out.push( [ key, object.get(key) ] );\n		}\n	}\n	else if ( object instanceof PairList ) {\n		for ( let pair in object.to_Array() ) {\n			out.push( [ pair.key, pair.value ] );\n		}\n	}\n	return out;\n}\n\nfunction jschema_array_items ( value ) {\n	if ( value instanceof Array ) { return value; }\n	if ( value instanceof Set or value instanceof Bag ) {\n		return value.to_Array();\n	}\n	return [];\n}\n\nfunction jschema_array_length ( value ) {\n	if ( jschema_is_arrayish(value) ) { return value.length(); }\n	return 0;\n}\n\nfunction jschema_pointer_escape ( String token ) {\n	return token\n		\\u25B7 replace( ^^, "~", "~0", "g" )\n		\\u25B7 replace( ^^, "/", "~1", "g" );\n}\n\nfunction jschema_pointer_join ( String base, step ) {\n	return base _ "/" _ jschema_pointer_escape("" _ step);\n}\n\nfunction jschema_deep_equal ( left, right ) {\n	return left == right;\n}\n`;\n        virtualFiles["/modules/std/data/json/schema/output.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/data/json/schema/output - JSON Schema validation output objects.\\n\\n=head1 SYNOPSIS\\n\\n  from std/data/json/schema import\\n    RequiredPropertyError,\\n    TypeMismatchError,\\n    validate;\\n\\n  let result := validate( schema, instance );\\n\\n  if ( not result.valid() ) {\\n    for ( let error in result.errors() ) {\\n      say( error.keywordLocation() _ " " _ error.error() );\\n      if ( error instanceof TypeMismatchError ) {\\n        say( "type problem" );\\n      }\\n    }\\n  }\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nThis module defines the object output model for JSON Schema validation. It\\nis modelled on the Basic output shape from JSON Schema Core, but each error\\nis a real Zuzu object instead of a plain C<Dict>. The class hierarchy lets\\ncallers use C<instanceof> to distinguish broad categories and precise\\nkeyword failures.\\n\\nThe hierarchy starts with C<ValidationError>. Most keyword failures are\\ngrouped under C<MissingValueError>, C<UnexpectedValueError>, or\\nC<WrongValueError>. Applicator keywords can also produce C<SubschemaError>,\\nwhose children are stored as weak links to avoid retaining a whole validation\\ntree only through parent summary errors.\\n\\n=head1 EXPORTS\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<ValidationResult>\\n\\nStructured result returned by C<validate>.\\n\\n=over\\n\\n=item C<valid()>\\n\\nReturns the boolean validation status.\\n\\n=item C<errors()>\\n\\nReturns an array of C<ValidationError> objects.\\n\\n=item C<to_Dict()>\\n\\nReturns a Basic-style C<Dict>. Errors are converted with their own\\nC<to_Dict()> method.\\n\\n=back\\n\\n=item C<ValidationError>\\n\\nBase class for all validation errors.\\n\\nMethods:\\n\\n=over\\n\\n=item C<keywordLocation()>\\n\\nJSON Pointer location of the failing keyword inside the schema.\\n\\n=item C<absoluteKeywordLocation()>\\n\\nAbsolute keyword URI when known, otherwise C<null>.\\n\\n=item C<instanceLocation()>\\n\\nJSON Pointer location of the failing instance value.\\n\\n=item C<error()>\\n\\nHuman-readable error message.\\n\\n=item C<keyword()>\\n\\nThe keyword that produced the error, when known.\\n\\n=item C<details()>\\n\\nKeyword-specific structured detail, when present.\\n\\n=item C<to_Dict()>\\n\\nConverts the error to a Basic-style C<Dict>.\\n\\n=back\\n\\nSnake-case aliases are provided for the location methods:\\nC<keyword_location()>, C<absolute_keyword_location()>, and\\nC<instance_location()>.\\n\\n=item C<MissingValueError>\\n\\nBase class for failures where a required value is absent. Subclasses are\\nC<RequiredPropertyError>, C<DependentRequiredPropertyError>,\\nC<MinItemsError>, C<MinPropertiesError>, and C<MinContainsError>.\\n\\n=item C<UnexpectedValueError>\\n\\nBase class for failures where a value is present but not allowed.\\nSubclasses are C<AdditionalPropertiesError>,\\nC<UnevaluatedPropertiesError>, C<AdditionalItemsError>,\\nC<UnevaluatedItemsError>, C<MaxItemsError>, C<MaxPropertiesError>,\\nC<MaxContainsError>, and C<NotMatchedError>.\\n\\n=item C<WrongValueError>\\n\\nBase class for failures where a value is present but does not meet a\\nconstraint. Subclasses are C<FalseSchemaError>, C<TypeMismatchError>,\\nC<EnumMismatchError>, C<ConstMismatchError>, C<MultipleOfError>,\\nC<MinimumError>, C<MaximumError>, C<ExclusiveMinimumError>,\\nC<ExclusiveMaximumError>, C<MinLengthError>, C<MaxLengthError>,\\nC<PatternError>, C<FormatError>, C<UnknownFormatError>,\\nC<UniqueItemsError>, C<PropertyNamesError>, C<ContentEncodingError>,\\nC<ContentMediaTypeError>, C<AllOfError>, C<AnyOfError>, C<OneOfError>, and\\nC<IfThenElseError>.\\n\\n=item C<SubschemaError>\\n\\nSummary error for the message C<A subschema had errors.>. The\\nC<suberrors()> method returns live child errors that are still reachable.\\nChildren are added with C<add_suberror(error)> and\\nC<add_suberrors(errors)>.\\n\\n=item C<ReferenceResolutionError>\\n\\nError class for failures while resolving C<$ref> or C<$dynamicRef>.\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/data/json/schema/output >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nclass ValidationError {\\n	let String keywordLocation;\\n	let absoluteKeywordLocation := null;\\n	let String instanceLocation;\\n	let String error;\\n	let keyword := null;\\n	let details := null;\\n\\n	method keywordLocation () { return keywordLocation; }\\n	method absoluteKeywordLocation () { return absoluteKeywordLocation; }\\n	method instanceLocation () { return instanceLocation; }\\n	method error () { return error; }\\n	method keyword () { return keyword; }\\n	method details () { return details; }\\n\\n	method keyword_location () { return keywordLocation; }\\n	method absolute_keyword_location () { return absoluteKeywordLocation; }\\n	method instance_location () { return instanceLocation; }\\n\\n	method to_Dict () {\\n		let out := {\\n			keywordLocation: keywordLocation,\\n			instanceLocation: instanceLocation,\\n			error: error,\\n		};\\n		if ( absoluteKeywordLocation \\u2262 null ) {\\n			out{absoluteKeywordLocation} := absoluteKeywordLocation;\\n		}\\n		return out;\\n	}\\n}\\n\\nclass MissingValueError extends ValidationError;\\nclass UnexpectedValueError extends ValidationError;\\nclass WrongValueError extends ValidationError;\\n\\nclass SubschemaError extends ValidationError {\\n	let _suberrors := [];\\n\\n	method add_suberror ( child_error ) {\\n		_suberrors.push_weak(child_error);\\n		return child_error;\\n	}\\n\\n	method add_suberrors ( errors ) {\\n		for ( let child_error in errors ) {\\n			self.add_suberror(child_error);\\n		}\\n		return self;\\n	}\\n\\n	method suberrors () {\\n		return _suberrors.grep( fn e -> e \\u2262 null );\\n	}\\n}\\n\\nclass FalseSchemaError extends WrongValueError;\\n\\nclass RequiredPropertyError extends MissingValueError;\\nclass DependentRequiredPropertyError extends MissingValueError;\\nclass MinItemsError extends MissingValueError;\\nclass MinPropertiesError extends MissingValueError;\\nclass MinContainsError extends MissingValueError;\\n\\nclass AdditionalPropertiesError extends UnexpectedValueError;\\nclass UnevaluatedPropertiesError extends UnexpectedValueError;\\nclass AdditionalItemsError extends UnexpectedValueError;\\nclass UnevaluatedItemsError extends UnexpectedValueError;\\nclass MaxItemsError extends UnexpectedValueError;\\nclass MaxPropertiesError extends UnexpectedValueError;\\nclass MaxContainsError extends UnexpectedValueError;\\nclass NotMatchedError extends UnexpectedValueError;\\n\\nclass TypeMismatchError extends WrongValueError;\\nclass EnumMismatchError extends WrongValueError;\\nclass ConstMismatchError extends WrongValueError;\\nclass MultipleOfError extends WrongValueError;\\nclass MinimumError extends WrongValueError;\\nclass MaximumError extends WrongValueError;\\nclass ExclusiveMinimumError extends WrongValueError;\\nclass ExclusiveMaximumError extends WrongValueError;\\nclass MinLengthError extends WrongValueError;\\nclass MaxLengthError extends WrongValueError;\\nclass PatternError extends WrongValueError;\\nclass FormatError extends WrongValueError;\\nclass UnknownFormatError extends FormatError;\\nclass UniqueItemsError extends WrongValueError;\\nclass PropertyNamesError extends WrongValueError;\\nclass ContentEncodingError extends WrongValueError;\\nclass ContentMediaTypeError extends WrongValueError;\\nclass AllOfError extends WrongValueError;\\nclass AnyOfError extends WrongValueError;\\nclass OneOfError extends WrongValueError;\\nclass IfThenElseError extends WrongValueError;\\n\\nclass ReferenceResolutionError extends ValidationError;\\n\\nclass ValidationResult {\\n	let Boolean valid := true;\\n	let Array errors := [];\\n\\n	method valid () { return valid; }\\n	method errors () { return errors; }\\n\\n	method to_Dict () {\\n		let out := { valid: valid };\\n		if ( not valid ) {\\n			out{errors} := errors.map( fn e -> e.to_Dict() );\\n		}\\n		return out;\\n	}\\n}\\n\';\n        virtualFiles["/modules/std/data/json/schema/relative_pointer.zzm"] = `=encoding utf8\n\n=head1 NAME\n\nstd/data/json/schema/relative_pointer - Relative JSON Pointer parser.\n\n=head1 SYNOPSIS\n\n  from std/data/json/schema/relative_pointer import RelativeJSONPointer;\n\n  let doc := {\n    people: [\n      { name: "Ada" },\n      { name: "Grace" },\n    ],\n  };\n\n  let pointer := new RelativeJSONPointer( path: "1/name" );\n  say( pointer.first( doc, "/people/0/age", "(missing)" ) );\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis Pure Zuzu module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nRelative JSON Pointer describes a target by starting from a context location,\nclimbing zero or more levels, optionally shifting an array index, and then\noptionally applying a normal JSON Pointer suffix. JSON Schema uses the\nsyntax for the C<relative-json-pointer> format.\n\nThis module evaluates relative pointers against a root document and a\ncontext pointer. The context pointer must itself be a JSON Pointer string.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<RelativeJSONPointer>\n\nConstruct with C<< new RelativeJSONPointer( path: "0/foo" ) >>. Invalid\nsyntax throws during construction.\n\nMethods:\n\n=over\n\n=item C<expression()>\n\nReturns the original pointer expression.\n\n=item C<up()>\n\nReturns the number of levels the pointer climbs from the context location.\n\n=item C<index_change()>\n\nReturns the array-index offset, or C<null> when none was supplied.\n\n=item C<pointer()>\n\nReturns the JSON Pointer suffix, or C<null> for a C<#> key request.\n\n=item C<key_request()>\n\nReturns true for C<#> pointers that request the key or array index at the\ntarget location.\n\n=item C<< target_pointer( context_pointer := "" ) >>\n\nReturns the absolute JSON Pointer reached by climbing and applying any index\noffset, before the suffix is applied.\n\n=item C<< evaluate( root, context_pointer := "" ) >>\n\nEvaluates the relative pointer. Normal pointers return the same array of\nmatches as I<std/path/jsonpointer>\'s C<query>. C<#> key requests return the\nkey or index string directly, or C<null> when the request names the document\nroot.\n\n=item C<< get( root, context_pointer := "" ) >>\n\nAlias for C<evaluate>.\n\n=item C<< first( root, context_pointer := "", fallback := null ) >>\n\nReturns the first matched value, or C<fallback> when no value is found. For\nC<#> key requests, C<fallback> is returned only when the key request returns\nC<null>.\n\n=item C<< exists( root, context_pointer := "" ) >>\n\nReturns true when evaluation finds a value. For C<#> key requests, the\ndocument root key is treated as absent.\n\n=back\n\n=back\n\n=head2 Functions\n\n=over\n\n=item C<< valid_relative_json_pointer( text ) >>\n\nReturns true when C<text> parses as a Relative JSON Pointer.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/data/json/schema/relative_pointer >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/path/jsonpointer import JSONPointer;\nfrom std/data/json/schema/model import jschema_pointer_join;\nfrom std/string import replace, split, substr;\n\nfunction _rjp_decode_token ( String raw ) {\n	return raw\n		\\u25B7 replace( ^^, "~1", "/", "g" )\n		\\u25B7 replace( ^^, "~0", "~", "g" );\n}\n\nfunction _rjp_tokens ( String pointer ) {\n	if ( pointer ne "" and substr( pointer, 0, 1 ) ne "/" ) {\n		die "Relative JSON Pointer context path must be a JSON Pointer";\n	}\n	if ( pointer eq "" ) {\n		return [];\n	}\n\n	let raw := split( substr( pointer, 1 ), "/" );\n	let out := [];\n	for ( let token in raw ) {\n		out.push( _rjp_decode_token(token) );\n	}\n	return out;\n}\n\nfunction _rjp_pointer_from_tokens ( Array tokens ) {\n	let out := "";\n	for ( let token in tokens ) {\n		out := jschema_pointer_join( out, token );\n	}\n	return out;\n}\n\nclass RelativeJSONPointer {\n	let String path;\n	let Number up := 0;\n	let index_change := null;\n	let pointer := null;\n	let Boolean key_request := false;\n\n	method __build__ () {\n		let i := 0;\n		let n := length path;\n		if ( n == 0 ) {\n			die "Relative JSON Pointer parse error: empty pointer";\n		}\n		if ( not( substr( path, 0, 1 ) ~ /[0-9]/ ) ) {\n			die "Relative JSON Pointer parse error: missing non-negative integer";\n		}\n		if ( n > 1 and substr( path, 0, 1 ) eq "0" and substr( path, 1, 1 ) ~ /[0-9]/ ) {\n			die "Relative JSON Pointer parse error: leading zero";\n		}\n		while ( i < n and substr( path, i, 1 ) ~ /[0-9]/ ) {\n			i++;\n		}\n		up := int( substr( path, 0, i ) );\n\n		if ( i < n and substr( path, i, 1 ) ~ /[+-]/ ) {\n			let sign := substr( path, i, 1 );\n			i++;\n			let start := i;\n			if ( i >= n or not( substr( path, i, 1 ) ~ /[0-9]/ ) ) {\n				die "Relative JSON Pointer parse error: missing index offset";\n			}\n			while ( i < n and substr( path, i, 1 ) ~ /[0-9]/ ) {\n				i++;\n			}\n			let offset := int( substr( path, start, i - start ) );\n			index_change := sign eq "-" ? 0 - offset : offset;\n		}\n\n		if ( i == n ) {\n			pointer := "";\n			return;\n		}\n\n		if ( substr( path, i, 1 ) eq "#" ) {\n			if ( i + 1 \\u2262 n ) {\n				die "Relative JSON Pointer parse error: trailing text after \'#\'";\n			}\n			key_request := true;\n			return;\n		}\n\n		let rest := substr( path, i );\n		new JSONPointer( path: rest );\n		pointer := rest;\n	}\n\n	method expression () { return path; }\n	method pointer () { return pointer; }\n	method up () { return up; }\n	method index_change () { return index_change; }\n	method key_request () { return key_request; }\n\n	method target_pointer ( String context_pointer := "" ) {\n		let tokens := _rjp_tokens(context_pointer);\n		if ( up > tokens.length() ) {\n			die "Relative JSON Pointer climbs above the document root";\n		}\n\n		let target_len := tokens.length() - up;\n		let target := [];\n		let i := 0;\n		while ( i < target_len ) {\n			target.push(tokens[i]);\n			i++;\n		}\n\n		if ( index_change \\u2262 null ) {\n			if (\n				target.length() == 0\n				or not( target[target.length() - 1] ~ /^(0|[1-9][0-9]*)$/ )\n			) {\n				die "Relative JSON Pointer index manipulation needs an array index";\n			}\n			let idx := int( target[target.length() - 1] ) + index_change;\n			if ( idx < 0 ) {\n				die "Relative JSON Pointer index manipulation produced negative index";\n			}\n			target[target.length() - 1] := "" _ idx;\n		}\n\n		return _rjp_pointer_from_tokens(target);\n	}\n\n	method evaluate ( root, String context_pointer := "" ) {\n		if ( key_request ) {\n			let tokens := _rjp_tokens(context_pointer);\n			if ( up > tokens.length() ) {\n				die "Relative JSON Pointer climbs above the document root";\n			}\n			if ( tokens.length() == up ) {\n				return null;\n			}\n			return tokens[ tokens.length() - up - 1 ];\n		}\n\n		let base := self.target_pointer(context_pointer);\n		let full := base;\n		if ( pointer \\u2262 null and pointer ne "" ) {\n			let suffix := pointer;\n			full := base eq "" ? suffix : base _ suffix;\n		}\n		return new JSONPointer( path: full ).query(root);\n	}\n\n	method get ( root, String context_pointer := "" ) {\n		return self.evaluate( root, context_pointer );\n	}\n\n	method first ( root, String context_pointer := "", fallback := null ) {\n		if ( key_request ) {\n			let key := self.evaluate( root, context_pointer );\n			return key \\u2261 null ? fallback : key;\n		}\n		let out := self.evaluate( root, context_pointer );\n		return out.length() == 0 ? fallback : out[0];\n	}\n\n	method exists ( root, String context_pointer := "" ) {\n		if ( key_request ) {\n			return self.evaluate( root, context_pointer ) \\u2262 null;\n		}\n		return self.evaluate( root, context_pointer ).length() > 0;\n	}\n}\n\nfunction valid_relative_json_pointer ( String text ) {\n	try {\n		new RelativeJSONPointer( path: text );\n		return true;\n	}\n	catch {\n		return false;\n	}\n}\n`;\n        virtualFiles["/modules/std/data/json/schema/validation.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/data/json/schema/validation - JSON Schema 2020-12 evaluator.\\n\\n=head1 SYNOPSIS\\n\\n  from std/data/json/schema/validation import JSONSchema, validate, valid;\\n\\n  let schema := new JSONSchema(\\n    schema: {\\n      type: "array",\\n      items: { type: "integer" },\\n    },\\n  );\\n\\n  say( schema.is_valid([ 1, 2, 3 ]) );\\n\\n  let result := validate( { minimum: 10 }, 4 );\\n  say( result.errors()[0].error() );\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis Pure Zuzu module is supported by all implementations of ZuzuScript.\\nNetwork loading requires C<std/net/http> through\\nI<std/data/json/schema/core>.\\n\\n=head1 DESCRIPTION\\n\\nThis module contains the JSON Schema 2020-12 evaluator. It is normally used\\nthrough the facade module I<std/data/json/schema>, which re-exports the\\npublic API and the error classes.\\n\\nThe evaluator supports boolean schemas, object schemas, references,\\napplicators, object and array validation, numeric and string constraints,\\ndependent keywords, content keywords, and format validation. It validates\\ndecoded Zuzu values and uses I<std/data/json/schema/model> to project native\\nC<PairList>, C<Set>, and C<Bag> values into the JSON data model where that\\nis meaningful.\\n\\n=head1 EXPORTS\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<JSONSchema>\\n\\nCompiled schema wrapper. Construct with C<< new JSONSchema( schema: ... ) >>.\\nPass C<options> as a named field when configuration is needed.\\n\\n=over\\n\\n=item C<< is_valid( instance ) >>\\n\\nReturns C<true> or C<false>. This mode stops after the first failure.\\n\\n=item C<< validate( instance ) >>\\n\\nReturns a C<ValidationResult> and collects independent failures as\\nC<ValidationError> objects.\\n\\n=back\\n\\n=back\\n\\n=head2 Functions\\n\\n=over\\n\\n=item C<< valid( schema, instance, options := {} ) >>\\n\\nConstructs a temporary C<JSONSchema> and returns\\nC<< is_valid(instance) >>.\\n\\n=item C<< validate( schema, instance, options := {} ) >>\\n\\nConstructs a temporary C<JSONSchema> and returns\\nC<< validate(instance) >>.\\n\\n=back\\n\\n=head1 OPTIONS\\n\\nC<options> may be a C<Dict> or C<PairList>.\\n\\n=over\\n\\n=item C<base_uri>\\n\\nBase URI for the root schema.\\n\\n=item C<registry>\\n\\nC<SchemaRegistry> used for references. If omitted, a new registry is\\ncreated and the root schema is registered in it.\\n\\n=item C<loader>\\n\\nCallable or object with C<load(uri)> used to load missing referenced\\nresources. A string result is decoded as JSON.\\n\\n=item C<allow_network>\\n\\nWhen true and C<loader> is not supplied, uses C<HTTPResourceLoader>.\\n\\n=item C<formats> or C<format_registry>\\n\\nC<FormatRegistry> used for C<format> checks.\\n\\n=item C<format_assert>\\n\\nBoolean. Defaults to false. When false, C<format> never makes validation\\nfail.\\n\\n=item C<unknown_format>\\n\\nDefaults to C<ignore>. Use C<fail> to report unknown asserted formats.\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/data/json/schema/validation >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/internals import to_Regexp_with_flags;\\nfrom std/string import join, substr;\\nfrom std/data/json/schema/core import\\n	HTTPResourceLoader,\\n	SchemaRegistry,\\n	jschema_uri_resolve,\\n	jschema_url_split;\\nfrom std/data/json/schema/format import FormatRegistry;\\nfrom std/data/json/schema/model import\\n	jschema_array_items,\\n	jschema_array_length,\\n	jschema_deep_equal,\\n	jschema_is_arrayish,\\n	jschema_is_object,\\n	jschema_is_ordered_array,\\n	jschema_is_unordered_array,\\n	jschema_object_entries,\\n	jschema_object_get,\\n	jschema_object_get_all,\\n	jschema_object_has,\\n	jschema_object_keys,\\n	jschema_object_unique_keys,\\n	jschema_pointer_join,\\n	jschema_type_matches,\\n	jschema_type_name;\\nfrom std/data/json/schema/output import\\n	AdditionalItemsError,\\n	AdditionalPropertiesError,\\n	AllOfError,\\n	AnyOfError,\\n	ConstMismatchError,\\n	ContentEncodingError,\\n	ContentMediaTypeError,\\n	DependentRequiredPropertyError,\\n	EnumMismatchError,\\n	ExclusiveMaximumError,\\n	ExclusiveMinimumError,\\n	FalseSchemaError,\\n	FormatError,\\n	IfThenElseError,\\n	MaxContainsError,\\n	MaximumError,\\n	MaxItemsError,\\n	MaxLengthError,\\n	MaxPropertiesError,\\n	MinContainsError,\\n	MinimumError,\\n	MinItemsError,\\n	MinLengthError,\\n	MinPropertiesError,\\n	MultipleOfError,\\n	NotMatchedError,\\n	OneOfError,\\n	PatternError,\\n	PropertyNamesError,\\n	ReferenceResolutionError,\\n	RequiredPropertyError,\\n	SubschemaError,\\n	TypeMismatchError,\\n	UnevaluatedItemsError,\\n	UnevaluatedPropertiesError,\\n	UnexpectedValueError,\\n	UniqueItemsError,\\n	UnknownFormatError,\\n	ValidationResult;\\n\\nfunction _jschema_opt ( options, String key, fallback := null ) {\\n	if ( options \\u2261 null ) {\\n		return fallback;\\n	}\\n	if ( options instanceof Dict ) {\\n		return options.exists(key) ? options.get(key) : fallback;\\n	}\\n	if ( options instanceof PairList ) {\\n		return options.has(key) ? options.get(key) : fallback;\\n	}\\n	return fallback;\\n}\\n\\nfunction _jschema_add_unique ( Array out, value ) {\\n	if ( not( value in out ) ) {\\n		out.push(value);\\n	}\\n	return out;\\n}\\n\\nfunction _jschema_validation_vocab_enabled ( schema, registry, String base_uri ) {\\n	if (\\n		not jschema_is_object(schema)\\n		or not jschema_object_has( schema, "$schema" )\\n		or not( jschema_object_get( schema, "$schema" ) instanceof String )\\n	) {\\n		return true;\\n	}\\n\\n	let metaschema;\\n	try {\\n		metaschema := registry.resolve(\\n			jschema_object_get( schema, "$schema" ),\\n			base_uri,\\n		);\\n	}\\n	catch {\\n		return true;\\n	}\\n\\n	if (\\n		jschema_is_object(metaschema)\\n		and jschema_object_has( metaschema, "$vocabulary" )\\n		and jschema_is_object( jschema_object_get( metaschema, "$vocabulary" ) )\\n	) {\\n		let vocabulary := jschema_object_get( metaschema, "$vocabulary" );\\n		let validation_uri := "https://json-schema.org/draft/2020-12/vocab/validation";\\n		if (\\n			jschema_object_has( vocabulary, validation_uri )\\n			and jschema_object_get( vocabulary, validation_uri ) instanceof Boolean\\n		) {\\n			return jschema_object_get( vocabulary, validation_uri );\\n		}\\n		return false;\\n	}\\n\\n	return true;\\n}\\n\\nfunction _jschema_format_assertion_vocab_enabled ( schema, registry, String base_uri, Boolean fallback ) {\\n	if (\\n		not jschema_is_object(schema)\\n		or not jschema_object_has( schema, "$schema" )\\n		or not( jschema_object_get( schema, "$schema" ) instanceof String )\\n	) {\\n		return fallback;\\n	}\\n\\n	let metaschema;\\n	try {\\n		metaschema := registry.resolve(\\n			jschema_object_get( schema, "$schema" ),\\n			base_uri,\\n		);\\n	}\\n	catch {\\n		return fallback;\\n	}\\n\\n	if (\\n		jschema_is_object(metaschema)\\n		and jschema_object_has( metaschema, "$vocabulary" )\\n		and jschema_is_object( jschema_object_get( metaschema, "$vocabulary" ) )\\n	) {\\n		let vocabulary := jschema_object_get( metaschema, "$vocabulary" );\\n		let format_assertion_uri := "https://json-schema.org/draft/2020-12/vocab/format-assertion";\\n		if ( jschema_object_has( vocabulary, format_assertion_uri ) ) {\\n			return true;\\n		}\\n	}\\n\\n	return fallback;\\n}\\n\\nclass _EvalResult {\\n	let Boolean valid := true;\\n	let Array errors := [];\\n	let Array evaluatedProperties := [];\\n	let Array evaluatedItems := [];\\n\\n	method add_error ( error ) {\\n		valid := false;\\n		if ( error \\u2262 null ) {\\n			errors.push(error);\\n		}\\n		return error;\\n	}\\n\\n	method merge ( other ) {\\n		if ( not other.valid() ) {\\n			valid := false;\\n		}\\n		for ( let error in other.errors() ) {\\n			errors.push(error);\\n		}\\n		for ( let prop in other.evaluatedProperties() ) {\\n			_jschema_add_unique( evaluatedProperties, prop );\\n		}\\n		for ( let item in other.evaluatedItems() ) {\\n			_jschema_add_unique( evaluatedItems, item );\\n		}\\n		return self;\\n	}\\n\\n	method mark_property ( prop ) {\\n		_jschema_add_unique( evaluatedProperties, prop );\\n	}\\n\\n	method mark_item ( item ) {\\n		_jschema_add_unique( evaluatedItems, item );\\n	}\\n\\n	method valid () { return valid; }\\n	method errors () { return errors; }\\n	method evaluatedProperties () { return evaluatedProperties; }\\n	method evaluatedItems () { return evaluatedItems; }\\n}\\n\\nfunction _jschema_regexp ( String pattern ) {\\n	return to_Regexp_with_flags(pattern, "u");\\n}\\n\\nclass _SchemaEvaluator {\\n	let registry;\\n	let formats;\\n	let Boolean collect := true;\\n	let Boolean format_assert := false;\\n	let String unknown_format := "ignore";\\n	let Boolean validation_enabled := true;\\n	let Array dynamic_scope := [];\\n\\n	method error (\\n		Klass,\\n		String keyword_location,\\n		String instance_location,\\n		String message,\\n		keyword := null,\\n		details := null,\\n	) {\\n		if ( not collect ) {\\n			return null;\\n		}\\n		return new Klass(\\n			keywordLocation: keyword_location,\\n			instanceLocation: instance_location,\\n			error: message,\\n			keyword: keyword,\\n			details: details,\\n		);\\n	}\\n\\n	method _subschema_error (\\n		String keyword_location,\\n		String instance_location,\\n		Array child_errors,\\n		keyword := null,\\n	) {\\n		if ( not collect ) {\\n			return null;\\n		}\\n		return new SubschemaError(\\n			keywordLocation: keyword_location,\\n			instanceLocation: instance_location,\\n			error: "A subschema had errors.",\\n			keyword: keyword,\\n		).add_suberrors(child_errors);\\n	}\\n\\n	method _invalid (\\n		_EvalResult result,\\n		Klass,\\n		String keyword_location,\\n		String instance_location,\\n		String message,\\n		keyword := null,\\n		details := null,\\n	) {\\n		result.add_error(\\n			self.error(\\n				Klass,\\n				keyword_location,\\n				instance_location,\\n				message,\\n				keyword,\\n				details,\\n			),\\n		);\\n		return result;\\n	}\\n\\n	method _child (\\n		schema,\\n		instance,\\n		String keyword_location,\\n		String instance_location,\\n		String base_uri,\\n	) {\\n		return self.evaluate(\\n			schema,\\n			instance,\\n			keyword_location,\\n			instance_location,\\n			base_uri,\\n		);\\n	}\\n\\n	method _finish ( _EvalResult result, Boolean pushed_scope ) {\\n		if ( pushed_scope ) {\\n			dynamic_scope.pop();\\n		}\\n		return result;\\n	}\\n\\n	method _dynamic_target ( ref_info ) {\\n		let fragment := ref_info{fragment};\\n		if (\\n			fragment \\u2261 null\\n			or fragment eq ""\\n			or substr( fragment, 0, 1 ) eq "/"\\n			or not registry.has_dynamic_anchor( ref_info{resource_uri}, fragment )\\n		) {\\n			return ref_info{target};\\n		}\\n\\n		for ( let resource_uri in dynamic_scope ) {\\n			let target := registry.dynamic_anchor( resource_uri, fragment );\\n			if ( target \\u2262 null ) {\\n				return target;\\n			}\\n		}\\n\\n		return ref_info{target};\\n	}\\n\\n	method evaluate (\\n		schema,\\n		instance,\\n		String keyword_location := "",\\n		String instance_location := "",\\n		String base_uri := "",\\n	) {\\n		let result := new _EvalResult();\\n		let current_base_uri := base_uri;\\n\\n		if ( schema instanceof Boolean ) {\\n			if ( schema ) {\\n				return result;\\n			}\\n			return self._invalid(\\n				result,\\n				FalseSchemaError,\\n				keyword_location,\\n				instance_location,\\n				"Boolean false schema does not allow any value.",\\n				"false",\\n			);\\n		}\\n\\n		if ( not jschema_is_object(schema) ) {\\n			return result;\\n		}\\n\\n		let registered_base := registry.schema_base(schema, null);\\n		if ( registered_base \\u2262 null ) {\\n			current_base_uri := registered_base;\\n		}\\n		else if (\\n			jschema_object_has( schema, "$id" )\\n			and jschema_object_get( schema, "$id" ) instanceof String\\n		) {\\n			current_base_uri := jschema_uri_resolve(\\n				current_base_uri,\\n				jschema_object_get( schema, "$id" ),\\n			);\\n		}\\n\\n		let scope_resource := jschema_url_split(current_base_uri){baseurl};\\n		dynamic_scope.push(scope_resource);\\n		let pushed_scope := true;\\n\\n		if ( jschema_object_has( schema, "$ref" ) ) {\\n			let ref := jschema_object_get( schema, "$ref" );\\n			if ( ref instanceof String ) {\\n				try {\\n					let ref_info := registry.resolve_info( ref, current_base_uri );\\n					let child := self._child(\\n						ref_info{target},\\n						instance,\\n						jschema_pointer_join( keyword_location, "$ref" ),\\n						instance_location,\\n						ref_info{resource_uri},\\n					);\\n					result.merge(child);\\n					if ( not child.valid() ) {\\n						result.add_error( self._subschema_error(\\n							jschema_pointer_join( keyword_location, "$ref" ),\\n							instance_location,\\n							child.errors(),\\n							"$ref",\\n						) );\\n						if ( not collect ) { return self._finish( result, pushed_scope ); }\\n					}\\n				}\\n				catch ( Exception e ) {\\n					self._invalid(\\n						result,\\n						ReferenceResolutionError,\\n						jschema_pointer_join( keyword_location, "$ref" ),\\n						instance_location,\\n						e{message},\\n						"$ref",\\n					);\\n					if ( not collect ) { return self._finish( result, pushed_scope ); }\\n				}\\n			}\\n		}\\n\\n		if ( jschema_object_has( schema, "$dynamicRef" ) ) {\\n			let ref := jschema_object_get( schema, "$dynamicRef" );\\n			if ( ref instanceof String ) {\\n				try {\\n					let ref_info := registry.resolve_info( ref, current_base_uri );\\n					let child := self._child(\\n						self._dynamic_target(ref_info),\\n						instance,\\n						jschema_pointer_join( keyword_location, "$dynamicRef" ),\\n						instance_location,\\n						ref_info{resource_uri},\\n					);\\n					result.merge(child);\\n					if ( not child.valid() ) {\\n						result.add_error( self._subschema_error(\\n							jschema_pointer_join( keyword_location, "$dynamicRef" ),\\n							instance_location,\\n							child.errors(),\\n							"$dynamicRef",\\n						) );\\n						if ( not collect ) { return self._finish( result, pushed_scope ); }\\n					}\\n				}\\n				catch ( Exception e ) {\\n					self._invalid(\\n						result,\\n						ReferenceResolutionError,\\n						jschema_pointer_join( keyword_location, "$dynamicRef" ),\\n						instance_location,\\n						e{message},\\n						"$dynamicRef",\\n					);\\n					if ( not collect ) { return self._finish( result, pushed_scope ); }\\n				}\\n			}\\n		}\\n\\n		self._validate_type( result, schema, instance, keyword_location, instance_location );\\n		if ( not result.valid() and not collect ) { return self._finish( result, pushed_scope ); }\\n		self._validate_enum_const( result, schema, instance, keyword_location, instance_location );\\n		if ( not result.valid() and not collect ) { return self._finish( result, pushed_scope ); }\\n		self._validate_numeric( result, schema, instance, keyword_location, instance_location );\\n		if ( not result.valid() and not collect ) { return self._finish( result, pushed_scope ); }\\n		self._validate_string( result, schema, instance, keyword_location, instance_location );\\n		if ( not result.valid() and not collect ) { return self._finish( result, pushed_scope ); }\\n		self._validate_array( result, schema, instance, keyword_location, instance_location, current_base_uri );\\n		if ( not result.valid() and not collect ) { return self._finish( result, pushed_scope ); }\\n		self._validate_object( result, schema, instance, keyword_location, instance_location, current_base_uri );\\n		if ( not result.valid() and not collect ) { return self._finish( result, pushed_scope ); }\\n		self._validate_applicators( result, schema, instance, keyword_location, instance_location, current_base_uri );\\n		if ( not result.valid() and not collect ) { return self._finish( result, pushed_scope ); }\\n		self._validate_unevaluated( result, schema, instance, keyword_location, instance_location, current_base_uri );\\n		return self._finish( result, pushed_scope );\\n	}\\n\\n	method _validate_type ( result, schema, instance, kwloc, instloc ) {\\n		if ( not validation_enabled ) {\\n			return;\\n		}\\n		if ( not jschema_object_has( schema, "type" ) ) {\\n			return;\\n		}\\n		let spec := jschema_object_get( schema, "type" );\\n		let ok := false;\\n		let expected := [];\\n		if ( spec instanceof String ) {\\n			expected := [ spec ];\\n		}\\n		else if ( spec instanceof Array ) {\\n			expected := spec;\\n		}\\n		for ( let t in expected ) {\\n			if ( t instanceof String and jschema_type_matches( instance, t ) ) {\\n				ok := true;\\n			}\\n		}\\n		if ( ok ) {\\n			return;\\n		}\\n		self._invalid(\\n			result,\\n			TypeMismatchError,\\n			jschema_pointer_join( kwloc, "type" ),\\n			instloc,\\n			`Expected ${join( "|", expected )}, got ${jschema_type_name(instance)}.`,\\n			"type",\\n		);\\n	}\\n\\n	method _validate_enum_const ( result, schema, instance, kwloc, instloc ) {\\n		if ( not validation_enabled ) {\\n			return;\\n		}\\n		if ( jschema_object_has( schema, "const" ) ) {\\n			if ( jschema_deep_equal(\\n				instance,\\n				jschema_object_get( schema, "const" ),\\n			) ) {\\n				return;\\n			}\\n			self._invalid(\\n				result,\\n				ConstMismatchError,\\n				jschema_pointer_join( kwloc, "const" ),\\n				instloc,\\n				"Value does not match const.",\\n				"const",\\n			);\\n			if ( not collect ) {\\n				return;\\n			}\\n		}\\n\\n		if ( jschema_object_has( schema, "enum" ) ) {\\n			let allowed := jschema_object_get( schema, "enum" );\\n				if ( allowed instanceof Array ) {\\n					for ( let option in allowed ) {\\n						if ( jschema_deep_equal( instance, option ) ) {\\n							return;\\n						}\\n					}\\n				}\\n			self._invalid(\\n				result,\\n				EnumMismatchError,\\n				jschema_pointer_join( kwloc, "enum" ),\\n				instloc,\\n				"Value is not one of the allowed enum values.",\\n				"enum",\\n			);\\n		}\\n	}\\n\\n	method _validate_numeric ( result, schema, instance, kwloc, instloc ) {\\n		if ( not validation_enabled ) {\\n			return;\\n		}\\n		if ( not( instance instanceof Number ) ) {\\n			return;\\n		}\\n		if ( jschema_object_has( schema, "multipleOf" ) ) {\\n			let n := jschema_object_get( schema, "multipleOf" );\\n			let quotient := n instanceof Number and n != 0\\n				? instance / n\\n				: 0;\\n			if (\\n				n instanceof Number\\n				and n != 0\\n				and (\\n					quotient > 10 ** 300\\n					or quotient < -( 10 ** 300 )\\n					or quotient != floor(quotient)\\n				)\\n			) {\\n				self._invalid(\\n					result,\\n					MultipleOfError,\\n					jschema_pointer_join( kwloc, "multipleOf" ),\\n					instloc,\\n					`Number is not a multiple of ${n}.`,\\n					"multipleOf",\\n				);\\n				if ( not collect ) {\\n					return;\\n				}\\n			}\\n		}\\n		if (\\n			jschema_object_has( schema, "minimum" )\\n			and instance < jschema_object_get( schema, "minimum" )\\n		) {\\n			self._invalid( result, MinimumError, jschema_pointer_join( kwloc, "minimum" ), instloc, "Number is below minimum.", "minimum" );\\n			if ( not collect ) {\\n				return;\\n			}\\n		}\\n		if (\\n			jschema_object_has( schema, "maximum" )\\n			and instance > jschema_object_get( schema, "maximum" )\\n		) {\\n			self._invalid( result, MaximumError, jschema_pointer_join( kwloc, "maximum" ), instloc, "Number is above maximum.", "maximum" );\\n			if ( not collect ) {\\n				return;\\n			}\\n		}\\n		if (\\n			jschema_object_has( schema, "exclusiveMinimum" )\\n			and instance <= jschema_object_get( schema, "exclusiveMinimum" )\\n		) {\\n			self._invalid( result, ExclusiveMinimumError, jschema_pointer_join( kwloc, "exclusiveMinimum" ), instloc, "Number is not above exclusiveMinimum.", "exclusiveMinimum" );\\n			if ( not collect ) {\\n				return;\\n			}\\n		}\\n		if (\\n			jschema_object_has( schema, "exclusiveMaximum" )\\n			and instance >= jschema_object_get( schema, "exclusiveMaximum" )\\n		) {\\n			self._invalid( result, ExclusiveMaximumError, jschema_pointer_join( kwloc, "exclusiveMaximum" ), instloc, "Number is not below exclusiveMaximum.", "exclusiveMaximum" );\\n		}\\n	}\\n\\n	method _validate_string ( result, schema, instance, kwloc, instloc ) {\\n		if ( not( instance instanceof String or instance instanceof BinaryString ) ) {\\n			return;\\n		}\\n		let text := "" _ instance;\\n		if ( validation_enabled ) {\\n			if (\\n				jschema_object_has( schema, "minLength" )\\n				and length text < jschema_object_get( schema, "minLength" )\\n			) {\\n				self._invalid( result, MinLengthError, jschema_pointer_join( kwloc, "minLength" ), instloc, "String is shorter than minLength.", "minLength" );\\n				if ( not collect ) {\\n					return;\\n				}\\n			}\\n			if (\\n				jschema_object_has( schema, "maxLength" )\\n				and length text > jschema_object_get( schema, "maxLength" )\\n			) {\\n				self._invalid( result, MaxLengthError, jschema_pointer_join( kwloc, "maxLength" ), instloc, "String is longer than maxLength.", "maxLength" );\\n				if ( not collect ) {\\n					return;\\n				}\\n			}\\n			if ( jschema_object_has( schema, "pattern" ) ) {\\n				let pattern := jschema_object_get( schema, "pattern" );\\n				if ( pattern instanceof String and not( text ~ _jschema_regexp(pattern) ) ) {\\n					self._invalid( result, PatternError, jschema_pointer_join( kwloc, "pattern" ), instloc, "String does not match pattern.", "pattern" );\\n					if ( not collect ) {\\n						return;\\n					}\\n				}\\n			}\\n		}\\n		if ( format_assert and jschema_object_has( schema, "format" ) ) {\\n			let fmt := jschema_object_get( schema, "format" );\\n			if ( fmt instanceof String ) {\\n				if ( not formats.has(fmt) ) {\\n					if ( unknown_format eq "ignore" ) {\\n						return;\\n					}\\n					self._invalid(\\n						result,\\n						UnknownFormatError,\\n						jschema_pointer_join( kwloc, "format" ),\\n						instloc,\\n						`Unknown format \\\'${fmt}\\\'.`,\\n						"format",\\n					);\\n					if ( not collect ) {\\n						return;\\n					}\\n				}\\n				else if ( not formats.check( fmt, text ) ) {\\n					self._invalid(\\n						result,\\n						FormatError,\\n						jschema_pointer_join( kwloc, "format" ),\\n						instloc,\\n						`String does not match format \\\'${fmt}\\\'.`,\\n						"format",\\n					);\\n				}\\n			}\\n		}\\n		if ( validation_enabled ) {\\n			if ( jschema_object_has( schema, "contentEncoding" ) ) {\\n				/* Validation of decoded content is intentionally conservative. */\\n			}\\n			if ( jschema_object_has( schema, "contentMediaType" ) ) {\\n				/* The media type keyword is annotation unless content is decoded. */\\n			}\\n		}\\n	}\\n\\n	method _validate_array ( result, schema, instance, kwloc, instloc, base_uri ) {\\n		if ( not jschema_is_arrayish(instance) ) {\\n			return;\\n		}\\n		let items := jschema_array_items(instance);\\n		let len := jschema_array_length(instance);\\n		if ( validation_enabled ) {\\n			if (\\n				jschema_object_has( schema, "minItems" )\\n				and len < jschema_object_get( schema, "minItems" )\\n			) {\\n				self._invalid( result, MinItemsError, jschema_pointer_join( kwloc, "minItems" ), instloc, "Array has too few items.", "minItems" );\\n				if ( not collect ) {\\n					return;\\n				}\\n			}\\n			if (\\n				jschema_object_has( schema, "maxItems" )\\n				and len > jschema_object_get( schema, "maxItems" )\\n			) {\\n				self._invalid( result, MaxItemsError, jschema_pointer_join( kwloc, "maxItems" ), instloc, "Array has too many items.", "maxItems" );\\n				if ( not collect ) {\\n					return;\\n				}\\n			}\\n			if ( jschema_object_get( schema, "uniqueItems", false ) ) {\\n				let i := 0;\\n				while ( i < items.length() ) {\\n					let j := i + 1;\\n					while ( j < items.length() ) {\\n						if ( jschema_deep_equal( items[i], items[j] ) ) {\\n							self._invalid( result, UniqueItemsError, jschema_pointer_join( kwloc, "uniqueItems" ), instloc, "Array items are not unique.", "uniqueItems" );\\n							if ( not collect ) {\\n								return;\\n							}\\n						}\\n						j++;\\n					}\\n					i++;\\n				}\\n			}\\n		}\\n\\n		if ( jschema_is_unordered_array(instance) and jschema_object_has( schema, "prefixItems" ) ) {\\n			self._invalid(\\n				result,\\n				AdditionalItemsError,\\n				jschema_pointer_join( kwloc, "prefixItems" ),\\n				instloc,\\n				"prefixItems cannot be applied to an unordered collection.",\\n				"prefixItems",\\n			);\\n			if ( not collect ) {\\n				return;\\n			}\\n		}\\n\\n		let evaluated := [];\\n		if ( jschema_object_has( schema, "prefixItems" ) and jschema_is_ordered_array(instance) ) {\\n			let prefix := jschema_object_get( schema, "prefixItems" );\\n			if ( prefix instanceof Array ) {\\n				let i := 0;\\n				while ( i < prefix.length() and i < items.length() ) {\\n					let child := self._child(\\n						prefix[i],\\n						items[i],\\n						jschema_pointer_join( jschema_pointer_join( kwloc, "prefixItems" ), i ),\\n						jschema_pointer_join( instloc, i ),\\n						base_uri,\\n					);\\n					evaluated.push(i);\\n					result.mark_item( jschema_pointer_join( instloc, i ) );\\n					result.merge(child);\\n					if ( not child.valid() ) {\\n						result.add_error( self._subschema_error(\\n							jschema_pointer_join( jschema_pointer_join( kwloc, "prefixItems" ), i ),\\n							jschema_pointer_join( instloc, i ),\\n							child.errors(),\\n							"prefixItems",\\n						) );\\n						if ( not collect ) {\\n							return result;\\n						}\\n					}\\n					i++;\\n				}\\n			}\\n		}\\n\\n		if ( jschema_object_has( schema, "items" ) ) {\\n			let subschema := jschema_object_get( schema, "items" );\\n			let start := 0;\\n			if (\\n				jschema_object_has( schema, "prefixItems" )\\n				and jschema_object_get( schema, "prefixItems" ) instanceof Array\\n			) {\\n				start := jschema_object_get( schema, "prefixItems" ).length();\\n			}\\n			let i := 0;\\n			while ( i < items.length() ) {\\n				if ( not jschema_is_ordered_array(instance) or i >= start ) {\\n					let child := self._child(\\n						subschema,\\n						items[i],\\n						jschema_pointer_join( kwloc, "items" ),\\n						jschema_pointer_join( instloc, i ),\\n						base_uri,\\n					);\\n					result.mark_item( jschema_pointer_join( instloc, i ) );\\n					result.merge(child);\\n					if ( not child.valid() ) {\\n						result.add_error( self._subschema_error(\\n							jschema_pointer_join( kwloc, "items" ),\\n							jschema_pointer_join( instloc, i ),\\n							child.errors(),\\n							"items",\\n						) );\\n						if ( not collect ) {\\n							return result;\\n						}\\n					}\\n				}\\n				i++;\\n			}\\n		}\\n\\n		if ( jschema_object_has( schema, "contains" ) ) {\\n			let matches := 0;\\n			let i := 0;\\n			while ( i < items.length() ) {\\n				let child := self._child(\\n					jschema_object_get( schema, "contains" ),\\n					items[i],\\n					jschema_pointer_join( kwloc, "contains" ),\\n					jschema_pointer_join( instloc, i ),\\n					base_uri,\\n				);\\n				if ( child.valid() ) {\\n					matches++;\\n					result.mark_item( jschema_pointer_join( instloc, i ) );\\n					result.merge(child);\\n				}\\n				i++;\\n			}\\n			let min := jschema_object_get( schema, "minContains", 1 );\\n			let max := jschema_object_get( schema, "maxContains", null );\\n			if ( validation_enabled and matches < min ) {\\n				self._invalid( result, MinContainsError, jschema_pointer_join( kwloc, "minContains" ), instloc, "Array contains too few matching items.", "minContains" );\\n				if ( not collect ) {\\n					return;\\n				}\\n			}\\n			if ( validation_enabled and max \\u2262 null and matches > max ) {\\n				self._invalid( result, MaxContainsError, jschema_pointer_join( kwloc, "maxContains" ), instloc, "Array contains too many matching items.", "maxContains" );\\n				if ( not collect ) {\\n					return;\\n				}\\n			}\\n		}\\n\\n	}\\n\\n	method _validate_object ( result, schema, instance, kwloc, instloc, base_uri ) {\\n		if ( not jschema_is_object(instance) ) {\\n			return;\\n		}\\n		let keys := jschema_object_keys(instance);\\n		let unique_keys := jschema_object_unique_keys(instance);\\n		if ( validation_enabled ) {\\n			if (\\n				jschema_object_has( schema, "minProperties" )\\n				and keys.length() < jschema_object_get( schema, "minProperties" )\\n			) {\\n				self._invalid( result, MinPropertiesError, jschema_pointer_join( kwloc, "minProperties" ), instloc, "Object has too few properties.", "minProperties" );\\n				if ( not collect ) {\\n					return;\\n				}\\n			}\\n			if (\\n				jschema_object_has( schema, "maxProperties" )\\n				and keys.length() > jschema_object_get( schema, "maxProperties" )\\n			) {\\n				self._invalid( result, MaxPropertiesError, jschema_pointer_join( kwloc, "maxProperties" ), instloc, "Object has too many properties.", "maxProperties" );\\n				if ( not collect ) {\\n					return;\\n				}\\n			}\\n			if ( jschema_object_has( schema, "required" ) ) {\\n				for ( let key in jschema_object_get( schema, "required" ) ) {\\n					if ( not jschema_object_has( instance, key ) ) {\\n						self._invalid(\\n							result,\\n							RequiredPropertyError,\\n							jschema_pointer_join( kwloc, "required" ),\\n							instloc,\\n							`Required property \\\'${key}\\\' is missing.`,\\n							"required",\\n						);\\n						if ( not collect ) {\\n							return;\\n						}\\n					}\\n				}\\n			}\\n			if ( jschema_object_has( schema, "dependentRequired" ) ) {\\n				let deps := jschema_object_get( schema, "dependentRequired" );\\n				if ( jschema_is_object(deps) ) {\\n					for ( let entry in jschema_object_entries(deps) ) {\\n						if ( jschema_object_has( instance, entry[0] ) ) {\\n							for ( let dep in entry[1] ) {\\n								if ( not jschema_object_has( instance, dep ) ) {\\n									self._invalid(\\n										result,\\n										DependentRequiredPropertyError,\\n										jschema_pointer_join( kwloc, "dependentRequired" ),\\n										instloc,\\n										`Dependent property \\\'${dep}\\\' is missing.`,\\n										"dependentRequired",\\n									);\\n									if ( not collect ) {\\n										return;\\n									}\\n								}\\n							}\\n						}\\n					}\\n				}\\n			}\\n			if ( jschema_object_has( schema, "dependencies" ) ) {\\n				let deps := jschema_object_get( schema, "dependencies" );\\n				if ( jschema_is_object(deps) ) {\\n					for ( let entry in jschema_object_entries(deps) ) {\\n						if ( jschema_object_has( instance, entry[0] ) ) {\\n							if ( entry[1] instanceof Array ) {\\n								for ( let dep in entry[1] ) {\\n									if ( not jschema_object_has( instance, dep ) ) {\\n										self._invalid(\\n											result,\\n											DependentRequiredPropertyError,\\n											jschema_pointer_join( kwloc, "dependencies" ),\\n											instloc,\\n											`Dependent property \\\'${dep}\\\' is missing.`,\\n											"dependencies",\\n										);\\n										if ( not collect ) {\\n											return;\\n										}\\n									}\\n								}\\n							}\\n							else {\\n								let child := self._child(\\n									entry[1],\\n									instance,\\n									jschema_pointer_join(\\n										jschema_pointer_join( kwloc, "dependencies" ),\\n										entry[0],\\n									),\\n									instloc,\\n									base_uri,\\n								);\\n								result.merge(child);\\n								if ( not child.valid() ) {\\n									result.add_error( self._subschema_error(\\n										jschema_pointer_join(\\n											jschema_pointer_join( kwloc, "dependencies" ),\\n											entry[0],\\n										),\\n										instloc,\\n										child.errors(),\\n										"dependencies",\\n									) );\\n									if ( not collect ) { return result; }\\n								}\\n							}\\n						}\\n					}\\n				}\\n			}\\n		}\\n\\n		let matched_properties := [];\\n		if ( jschema_object_has( schema, "properties" ) ) {\\n			let props := jschema_object_get( schema, "properties" );\\n			if ( jschema_is_object(props) ) {\\n				for ( let entry in jschema_object_entries(props) ) {\\n					let key := entry[0];\\n					if ( jschema_object_has( instance, key ) ) {\\n						let ix := 0;\\n						for ( let value in jschema_object_get_all( instance, key ) ) {\\n							let child := self._child(\\n								entry[1],\\n								value,\\n								jschema_pointer_join( jschema_pointer_join( kwloc, "properties" ), key ),\\n								jschema_pointer_join( instloc, key ),\\n								base_uri,\\n							);\\n							_jschema_add_unique( matched_properties, key );\\n							result.mark_property( jschema_pointer_join( instloc, key ) );\\n							result.merge(child);\\n							if ( not child.valid() ) {\\n								result.add_error( self._subschema_error(\\n									jschema_pointer_join( jschema_pointer_join( kwloc, "properties" ), key ),\\n									jschema_pointer_join( instloc, key ),\\n									child.errors(),\\n									"properties",\\n								) );\\n								if ( not collect ) { return result; }\\n							}\\n							ix++;\\n						}\\n					}\\n				}\\n			}\\n		}\\n\\n		if ( jschema_object_has( schema, "patternProperties" ) ) {\\n			let patterns := jschema_object_get( schema, "patternProperties" );\\n			if ( jschema_is_object(patterns) ) {\\n				for ( let pentry in jschema_object_entries(patterns) ) {\\n					let pattern := pentry[0];\\n					for ( let entry in jschema_object_entries(instance) ) {\\n						let key := entry[0];\\n						if ( key ~ _jschema_regexp(pattern) ) {\\n							let child := self._child(\\n								pentry[1],\\n								entry[1],\\n								jschema_pointer_join( jschema_pointer_join( kwloc, "patternProperties" ), pattern ),\\n								jschema_pointer_join( instloc, key ),\\n								base_uri,\\n							);\\n							_jschema_add_unique( matched_properties, key );\\n							result.mark_property( jschema_pointer_join( instloc, key ) );\\n							result.merge(child);\\n							if ( not child.valid() ) {\\n								result.add_error( self._subschema_error(\\n									jschema_pointer_join( jschema_pointer_join( kwloc, "patternProperties" ), pattern ),\\n									jschema_pointer_join( instloc, key ),\\n									child.errors(),\\n									"patternProperties",\\n								) );\\n								if ( not collect ) { return result; }\\n							}\\n						}\\n					}\\n				}\\n			}\\n		}\\n\\n		if ( jschema_object_has( schema, "additionalProperties" ) ) {\\n			for ( let entry in jschema_object_entries(instance) ) {\\n				let key := entry[0];\\n				if ( not( key in matched_properties ) ) {\\n					let child := self._child(\\n						jschema_object_get( schema, "additionalProperties" ),\\n						entry[1],\\n						jschema_pointer_join( kwloc, "additionalProperties" ),\\n						jschema_pointer_join( instloc, key ),\\n						base_uri,\\n					);\\n					result.merge(child);\\n					if ( not child.valid() ) {\\n						result.add_error( self.error(\\n							AdditionalPropertiesError,\\n							jschema_pointer_join( kwloc, "additionalProperties" ),\\n							jschema_pointer_join( instloc, key ),\\n							"Additional property is not allowed.",\\n							"additionalProperties",\\n						) );\\n						if ( not collect ) { return result; }\\n					}\\n					result.mark_property( jschema_pointer_join( instloc, key ) );\\n				}\\n			}\\n		}\\n\\n		if ( jschema_object_has( schema, "propertyNames" ) ) {\\n			for ( let key in unique_keys ) {\\n				let child := self._child(\\n					jschema_object_get( schema, "propertyNames" ),\\n					key,\\n					jschema_pointer_join( kwloc, "propertyNames" ),\\n					jschema_pointer_join( instloc, key ),\\n					base_uri,\\n				);\\n				result.merge(child);\\n				if ( not child.valid() ) {\\n					result.add_error( self.error(\\n						PropertyNamesError,\\n						jschema_pointer_join( kwloc, "propertyNames" ),\\n						jschema_pointer_join( instloc, key ),\\n						"Property name does not match schema.",\\n						"propertyNames",\\n					) );\\n					if ( not collect ) { return result; }\\n				}\\n			}\\n		}\\n\\n		if ( jschema_object_has( schema, "dependentSchemas" ) ) {\\n			let deps := jschema_object_get( schema, "dependentSchemas" );\\n			if ( jschema_is_object(deps) ) {\\n				for ( let entry in jschema_object_entries(deps) ) {\\n					if ( jschema_object_has( instance, entry[0] ) ) {\\n						let child := self._child(\\n							entry[1],\\n							instance,\\n							jschema_pointer_join( jschema_pointer_join( kwloc, "dependentSchemas" ), entry[0] ),\\n							instloc,\\n							base_uri,\\n						);\\n						result.merge(child);\\n						if ( not child.valid() ) {\\n							result.add_error( self._subschema_error(\\n								jschema_pointer_join( jschema_pointer_join( kwloc, "dependentSchemas" ), entry[0] ),\\n								instloc,\\n								child.errors(),\\n								"dependentSchemas",\\n							) );\\n							if ( not collect ) { return result; }\\n						}\\n					}\\n				}\\n			}\\n		}\\n\\n	}\\n\\n	method _validate_unevaluated ( result, schema, instance, kwloc, instloc, base_uri ) {\\n		if (\\n			jschema_is_arrayish(instance)\\n			and jschema_object_has( schema, "unevaluatedItems" )\\n		) {\\n			let items := jschema_array_items(instance);\\n			let i := 0;\\n			while ( i < items.length() ) {\\n				if (\\n					not( jschema_pointer_join( instloc, i )\\n						in result.evaluatedItems() )\\n				) {\\n					let child := self._child(\\n						jschema_object_get( schema, "unevaluatedItems" ),\\n						items[i],\\n						jschema_pointer_join( kwloc, "unevaluatedItems" ),\\n						jschema_pointer_join( instloc, i ),\\n						base_uri,\\n					);\\n					result.merge(child);\\n					if ( not child.valid() ) {\\n						result.add_error( self.error(\\n							UnevaluatedItemsError,\\n							jschema_pointer_join( kwloc, "unevaluatedItems" ),\\n							jschema_pointer_join( instloc, i ),\\n							"Unevaluated array item is not allowed.",\\n							"unevaluatedItems",\\n						) );\\n						if ( not collect ) { return result; }\\n					}\\n					result.mark_item( jschema_pointer_join( instloc, i ) );\\n				}\\n				i++;\\n			}\\n		}\\n\\n		if (\\n			jschema_is_object(instance)\\n			and jschema_object_has( schema, "unevaluatedProperties" )\\n		) {\\n			for ( let entry in jschema_object_entries(instance) ) {\\n				let key := entry[0];\\n				if (\\n					not( jschema_pointer_join( instloc, key )\\n						in result.evaluatedProperties() )\\n				) {\\n					let child := self._child(\\n						jschema_object_get( schema, "unevaluatedProperties" ),\\n						entry[1],\\n						jschema_pointer_join( kwloc, "unevaluatedProperties" ),\\n						jschema_pointer_join( instloc, key ),\\n						base_uri,\\n					);\\n					result.merge(child);\\n					if ( not child.valid() ) {\\n						result.add_error( self.error(\\n							UnevaluatedPropertiesError,\\n							jschema_pointer_join( kwloc, "unevaluatedProperties" ),\\n							jschema_pointer_join( instloc, key ),\\n							"Unevaluated property is not allowed.",\\n							"unevaluatedProperties",\\n						) );\\n						if ( not collect ) { return result; }\\n					}\\n					result.mark_property( jschema_pointer_join( instloc, key ) );\\n				}\\n			}\\n		}\\n	}\\n\\n	method _validate_applicators ( result, schema, instance, kwloc, instloc, base_uri ) {\\n		if ( jschema_object_has( schema, "allOf" ) ) {\\n			let arr := jschema_object_get( schema, "allOf" );\\n			if ( arr instanceof Array ) {\\n				let i := 0;\\n				while ( i < arr.length() ) {\\n					let child := self._child( arr[i], instance, jschema_pointer_join( jschema_pointer_join( kwloc, "allOf" ), i ), instloc, base_uri );\\n					if ( child.valid() ) {\\n						result.merge(child);\\n					}\\n					else {\\n						result.merge(child);\\n						result.add_error( self.error( AllOfError, jschema_pointer_join( jschema_pointer_join( kwloc, "allOf" ), i ), instloc, "allOf subschema failed.", "allOf" ) );\\n						if ( not collect ) { return result; }\\n					}\\n					i++;\\n				}\\n			}\\n		}\\n\\n		if ( jschema_object_has( schema, "anyOf" ) ) {\\n			let arr := jschema_object_get( schema, "anyOf" );\\n			if ( arr instanceof Array ) {\\n				let ok := false;\\n				let child_errors := [];\\n				let i := 0;\\n				while ( i < arr.length() ) {\\n					let child := self._child( arr[i], instance, jschema_pointer_join( jschema_pointer_join( kwloc, "anyOf" ), i ), instloc, base_uri );\\n					if ( child.valid() ) {\\n						ok := true;\\n						result.merge(child);\\n					}\\n					else {\\n						for ( let e in child.errors() ) { child_errors.push(e); }\\n					}\\n					i++;\\n				}\\n				if ( not ok ) {\\n					result.add_error( self.error( AnyOfError, jschema_pointer_join( kwloc, "anyOf" ), instloc, "No anyOf subschema matched.", "anyOf" ) );\\n					result.add_error( self._subschema_error( jschema_pointer_join( kwloc, "anyOf" ), instloc, child_errors, "anyOf" ) );\\n					if ( not collect ) { return result; }\\n				}\\n			}\\n		}\\n\\n		if ( jschema_object_has( schema, "oneOf" ) ) {\\n			let arr := jschema_object_get( schema, "oneOf" );\\n			if ( arr instanceof Array ) {\\n				let matches := 0;\\n				let child_errors := [];\\n				let i := 0;\\n				while ( i < arr.length() ) {\\n					let child := self._child( arr[i], instance, jschema_pointer_join( jschema_pointer_join( kwloc, "oneOf" ), i ), instloc, base_uri );\\n					if ( child.valid() ) {\\n						matches++;\\n						result.merge(child);\\n					}\\n					else {\\n						for ( let e in child.errors() ) { child_errors.push(e); }\\n					}\\n					i++;\\n				}\\n				if ( matches != 1 ) {\\n					result.add_error( self.error( OneOfError, jschema_pointer_join( kwloc, "oneOf" ), instloc, "Expected exactly one oneOf subschema to match.", "oneOf" ) );\\n					if ( matches == 0 ) {\\n						result.add_error( self._subschema_error( jschema_pointer_join( kwloc, "oneOf" ), instloc, child_errors, "oneOf" ) );\\n					}\\n					if ( not collect ) { return result; }\\n				}\\n			}\\n		}\\n\\n		if ( jschema_object_has( schema, "not" ) ) {\\n			let child := self._child( jschema_object_get( schema, "not" ), instance, jschema_pointer_join( kwloc, "not" ), instloc, base_uri );\\n			if ( child.valid() ) {\\n				self._invalid( result, NotMatchedError, jschema_pointer_join( kwloc, "not" ), instloc, "Value matched a forbidden subschema.", "not" );\\n				if ( not collect ) { return result; }\\n			}\\n		}\\n\\n		if ( jschema_object_has( schema, "if" ) ) {\\n			let cond := self._child( jschema_object_get( schema, "if" ), instance, jschema_pointer_join( kwloc, "if" ), instloc, base_uri );\\n			if ( cond.valid() ) {\\n				result.merge(cond);\\n			}\\n			if ( cond.valid() and jschema_object_has( schema, "then" ) ) {\\n				let child := self._child( jschema_object_get( schema, "then" ), instance, jschema_pointer_join( kwloc, "then" ), instloc, base_uri );\\n				result.merge(child);\\n				if ( not child.valid() ) {\\n					result.add_error( self.error( IfThenElseError, jschema_pointer_join( kwloc, "then" ), instloc, "then subschema failed.", "then" ) );\\n					if ( not collect ) { return result; }\\n				}\\n			}\\n			else if ( not cond.valid() and jschema_object_has( schema, "else" ) ) {\\n				let child := self._child( jschema_object_get( schema, "else" ), instance, jschema_pointer_join( kwloc, "else" ), instloc, base_uri );\\n				result.merge(child);\\n				if ( not child.valid() ) {\\n					result.add_error( self.error( IfThenElseError, jschema_pointer_join( kwloc, "else" ), instloc, "else subschema failed.", "else" ) );\\n					if ( not collect ) { return result; }\\n				}\\n			}\\n		}\\n	}\\n}\\n\\nclass JSONSchema {\\n	let schema;\\n	let options := {};\\n	let registry;\\n	let formats;\\n	let String base_uri := "";\\n	let Boolean format_assert := false;\\n	let String unknown_format := "ignore";\\n	let Boolean validation_enabled := true;\\n\\n	method __build__ () {\\n		base_uri := _jschema_opt( options, "base_uri", base_uri );\\n		registry := _jschema_opt( options, "registry", null );\\n		if ( registry \\u2261 null ) {\\n			registry := new SchemaRegistry();\\n		}\\n		formats := _jschema_opt( options, "formats", null );\\n		if ( formats \\u2261 null ) {\\n			formats := _jschema_opt( options, "format_registry", null );\\n		}\\n		if ( formats \\u2261 null ) {\\n			formats := new FormatRegistry();\\n		}\\n		let loader := _jschema_opt( options, "loader", null );\\n		if ( loader \\u2261 null and _jschema_opt( options, "allow_network", false ) ) {\\n			loader := new HTTPResourceLoader();\\n		}\\n		if ( loader \\u2262 null ) {\\n			registry.set_loader(loader);\\n		}\\n		unknown_format := _jschema_opt( options, "unknown_format", "ignore" );\\n		validation_enabled := _jschema_opt(\\n			options,\\n			"validation_enabled",\\n			_jschema_validation_vocab_enabled( schema, registry, base_uri ),\\n		);\\n		format_assert := _jschema_format_assertion_vocab_enabled(\\n			schema,\\n			registry,\\n			base_uri,\\n			_jschema_opt( options, "format_assert", false ),\\n		);\\n		registry.register( schema, base_uri );\\n	}\\n\\n	method _evaluator ( Boolean collect ) {\\n		return new _SchemaEvaluator(\\n			registry: registry,\\n			formats: formats,\\n			collect: collect,\\n			format_assert: format_assert,\\n			unknown_format: unknown_format,\\n			validation_enabled: validation_enabled,\\n		);\\n	}\\n\\n	method is_valid ( instance ) {\\n		return self._evaluator(false).evaluate(\\n			schema,\\n			instance,\\n			"",\\n			"",\\n			base_uri,\\n		).valid();\\n	}\\n\\n	method validate ( instance ) {\\n		let ev := self._evaluator(true).evaluate(\\n			schema,\\n			instance,\\n			"",\\n			"",\\n			base_uri,\\n		);\\n		return new ValidationResult(\\n			valid: ev.valid(),\\n			errors: ev.errors(),\\n		);\\n	}\\n}\\n\\nfunction valid ( schema, instance, options := {} ) {\\n	return new JSONSchema( schema: schema, options: options ).is_valid(instance);\\n}\\n\\nfunction validate ( schema, instance, options := {} ) {\\n	return new JSONSchema( schema: schema, options: options ).validate(instance);\\n}\\n\';\n        virtualFiles["/modules/std/mail.zzm"] = `=encoding utf8\n\n=head1 NAME\n\nstd/mail - Pure ZuzuScript mail message object model.\n\n=head1 SYNOPSIS\n\n  from std/mail import Address, Head, Body, Message;\n  let message := new Message(\n    head: new Head(),\n    body: Body.bytes( to_binary("Hello\\\\r\\\\n") )\n  );\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module provides the object model for RFC 5322-style message\nheaders, address objects, MIME-ish bodies, date helpers, a conservative\nparser, and integration with compatible low-level mailers.\n\nThe parser ignores multipart preamble and epilogue bytes in Phase 9.\nWhen either is present, C<Parser.warnings()> records the limitation.\n\nThe serializer can generate missing multipart boundaries on request.\nC<Serializer.serialize()> writes matching C<Content-Type> output for the\ngenerated boundary. C<Serializer.serialize_body()> returns only body bytes,\nso callers using it with a generated boundary must provide the matching\nC<Content-Type> header separately.\n\n=head1 EXPORTS\n\n=head2 Functions\n\n=over\n\n=item C<< parse_datetime(String text) >>\n\nParameters: C<text> is a mail date string. Returns: C<Time>. Parses a\nmail header date into a C<std/time> object.\n\n=item C<< format_datetime(Time time) >>\n\nParameters: C<time> is a C<std/time> object. Returns: C<String>. Formats\na time for use in mail headers.\n\n=back\n\n=head2 Classes\n\n=over\n\n=item C<Address>\n\nMail address object.\n\n=over\n\n=item C<< Address.parse(String text) >>, C<< Address.parse_list(String text) >>\n\nParameters: C<text> is address header text. Returns: C<Address> or\nC<Array>. Parses one address or a comma-separated address list.\n\n=item C<< address.local() >>, C<< address.domain() >>, C<< address.display_name() >>, C<< address.address() >>\n\nParameters: none. Returns: C<String> or C<null>. Returns address\ncomponents.\n\n=item C<< address.to_header() >>, C<< address.to_String() >>\n\nParameters: none. Returns: C<String>. Formats the address.\n\n=item C<< address.to_Dict() >>\n\nParameters: none. Returns: C<Dict>. Converts the address to a\ndictionary.\n\n=back\n\n=item C<Head>\n\nOrdered mail header collection.\n\n=over\n\n=item C<< head.fields() >>, C<< head.to_PairList() >>, C<< head.to_Iterator() >>\n\nParameters: none. Returns: C<PairList> or C<Function>. Returns header\nfields or an iterator.\n\n=item C<< head.raw(String name, fallback := null) >>, C<< head.raw_all(String name) >>, C<< head.decoded(String name, fallback := null) >>, C<< head.decoded_all(String name) >>, C<< head.get(String name, fallback := null) >>, C<< head.get_all(String name) >>\n\nParameters: C<name> is a header name and C<fallback> is optional.\nReturns: C<String>, C<Array>, or fallback. Reads header values.\n\n=item C<< head.set(String name, String value) >>, C<< head.add(String name, String value) >>, C<< head.remove(String name) >>\n\nParameters: C<name> is a header name and C<value> is header text.\nReturns: C<Head>. Mutates header fields.\n\n=item C<< head.has(String name) >>\n\nParameters: C<name> is a header name. Returns: C<Boolean>. Tests whether\na header exists.\n\n=item C<< head.content_type() >>, C<< head.content_transfer_encoding() >>, C<< head.charset() >>, C<< head.boundary() >>, C<< head.message_id() >>, C<< head.date() >>, C<< head.from() >>, C<< head.to() >>, C<< head.cc() >>, C<< head.bcc() >>, C<< head.subject() >>\n\nParameters: none. Returns: header-specific value. Reads common headers.\n\n=back\n\n=item C<Body>\n\nMail body value.\n\n=over\n\n=item C<< Body.bytes(BinaryString raw, ... PairList options) >>\n\nParameters: C<raw> is body bytes and C<options> describe content type,\nencoding, and parts. Returns: C<Body>. Creates a leaf or multipart body.\n\n=item C<< Body.nested(message, ... PairList options) >>\n\nParameters: C<message> is a C<Message>. Returns: C<Body>. Creates a\nnested message body.\n\n=item C<< body.is_multipart() >>, C<< body.is_nested() >>\n\nParameters: none. Returns: C<Boolean>. Reports body shape.\n\n=item C<< body.bytes() >>, C<< body.decoded() >>, C<< body.encoded() >>\n\nParameters: none. Returns: C<BinaryString>. Returns raw, decoded, or\nencoded body bytes.\n\n=item C<< body.parts() >>, C<< body.part(Number index) >>, C<< body.count() >>\n\nParameters: C<index> selects a body part. Returns: C<Array>, C<Body>, or\nC<Number>. Reads multipart body parts.\n\n=item C<< body.nested() >>, C<< body.content_type() >>, C<< body.transfer_encoding() >>, C<< body.to_Dict() >>\n\nParameters: none. Returns: value. Reads body metadata or converts the\nbody to a dictionary.\n\n=back\n\n=item C<Message>\n\nMail message object with C<head> and C<body>.\n\n=over\n\n=item C<< message.head() >>, C<< message.body() >>\n\nParameters: none. Returns: C<Head> or C<Body>. Returns message parts.\n\n=item C<< message.header(String name, fallback := null) >>, C<< message.headers(String name) >>\n\nParameters: C<name> is a header name and C<fallback> is optional.\nReturns: C<String>, C<Array>, or fallback. Reads message headers.\n\n=item C<< message.set_header(String name, String value) >>, C<< message.add_header(String name, String value) >>, C<< message.remove_header(String name) >>\n\nParameters: C<name> is a header name and C<value> is header text.\nReturns: C<Message>. Mutates message headers.\n\n=item C<< message.subject() >>, C<< message.from() >>, C<< message.to() >>, C<< message.cc() >>, C<< message.bcc() >>, C<< message.date() >>, C<< message.message_id() >>\n\nParameters: none. Returns: header-specific value. Reads common message\nheaders.\n\n=item C<< message.is_part() >>, C<< message.container() >>, C<< message.toplevel() >>\n\nParameters: none. Returns: C<Boolean> or C<Message>. Reads containment\nstate.\n\n=item C<< message.send(mailer, ... PairList options) >>\n\nParameters: C<mailer> is a compatible low-level mailer. Returns: value.\nSends the message.\n\n=item C<< message.to_Dict() >>\n\nParameters: none. Returns: C<Dict>. Converts the message to a\ndictionary.\n\n=back\n\n=item C<Parser>\n\nConservative mail parser.\n\n=over\n\n=item C<< parser.warnings() >>\n\nParameters: none. Returns: C<Array>. Returns non-fatal parse warnings.\n\n=item C<< parser.parse(BinaryString bytes) >>\n\nParameters: C<bytes> is raw message bytes. Returns: C<Message>. Parses a\nmail message.\n\n=back\n\n=item C<Serializer>\n\nMail serializer.\n\n=over\n\n=item C<< serializer.serialize_body(Message message, ... PairList options) >>\n\nParameters: C<message> is a mail message and C<options> control output.\nReturns: C<BinaryString>. Serializes only the message body.\n\n=item C<< serializer.serialize(Message message, ... PairList options) >>\n\nParameters: C<message> is a mail message and C<options> control output.\nReturns: C<BinaryString>. Serializes a complete message.\n\n=back\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/mail >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/string import chr, index, join, ord, substr, trim;\n\nfrom std/string/base64 import\n	encode as _base64_encode,\n	decode as _base64_decode;\nfrom std/string/quoted_printable import decode as _qp_decode;\nfrom std/time import Time, TimeZone;\n\nfunction _parse_one_address;\nfunction _parse_address_list;\nfunction _parse_address_header;\nfunction _mail_send_serialize_body;\n\nfunction _has_crlf ( String text ) {\n	return index( text, "\\\\r" ) >= 0 or index( text, "\\\\n" ) >= 0;\n}\n\nfunction _assert_no_crlf ( String text, String context ) {\n	if ( _has_crlf(text) ) {\n		die \\`mail.\\${context}: value must not contain CR or LF\\`;\n	}\n}\n\nfunction _is_ws ( String ch ) {\n	return ch eq " " or ch eq "\\\\t";\n}\n\nfunction _skip_ws ( String text, Number i ) {\n	let pos := i;\n	let n := length text;\n	while ( pos < n and _is_ws( substr( text, pos, 1 ) ) ) {\n		pos++;\n	}\n	return pos;\n}\n\nfunction _div_floor ( Number n, Number d ) {\n	return floor( n / d );\n}\n\nfunction _hex_value ( String ch ) {\n	let v := index( "0123456789ABCDEF", uc(ch) );\n	return v;\n}\n\nfunction _bytes_to_binary ( Array bytes ) {\n	let alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"\n		_ "abcdefghijklmnopqrstuvwxyz0123456789+/";\n	let out := "";\n	let i := 0;\n	let n := bytes.length();\n\n	while ( i < n ) {\n		let b0 := bytes[i];\n		let b1 := null;\n		let b2 := null;\n		if ( i + 1 < n ) {\n			b1 := bytes[i + 1];\n		}\n		if ( i + 2 < n ) {\n			b2 := bytes[i + 2];\n		}\n\n		let c0 := _div_floor( b0, 4 );\n		let c1 := ( b0 mod 4 ) * 16;\n		let c2 := 64;\n		let c3 := 64;\n\n		if ( not( b1 == null ) ) {\n			c1 += _div_floor( b1, 16 );\n			c2 := ( b1 mod 16 ) * 4;\n			if ( not( b2 == null ) ) {\n				c2 += _div_floor( b2, 64 );\n				c3 := b2 mod 64;\n			}\n		}\n\n		out _= substr( alphabet, c0, 1 );\n		out _= substr( alphabet, c1, 1 );\n		out _= c2 == 64 ? "=" : substr( alphabet, c2, 1 );\n		out _= c3 == 64 ? "=" : substr( alphabet, c3, 1 );\n		i += 3;\n	}\n\n	return _base64_decode(out);\n}\n\nfunction _binary_to_bytes ( BinaryString raw ) {\n	let alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"\n		_ "abcdefghijklmnopqrstuvwxyz0123456789+/";\n	let b64 := _base64_encode(raw);\n	let out := [];\n	let i := 0;\n	let n := length b64;\n\n	while ( i < n ) {\n		let c0 := index( alphabet, substr( b64, i, 1 ) );\n		let c1 := index( alphabet, substr( b64, i + 1, 1 ) );\n		let ch2 := substr( b64, i + 2, 1 );\n		let ch3 := substr( b64, i + 3, 1 );\n		let c2 := -1;\n		let c3 := -1;\n		if ( ch2 ne "=" ) {\n			c2 := index( alphabet, ch2 );\n		}\n		if ( ch3 ne "=" ) {\n			c3 := index( alphabet, ch3 );\n		}\n\n		out.push( c0 * 4 + _div_floor( c1, 16 ) );\n		if ( c2 >= 0 ) {\n			out.push( ( c1 mod 16 ) * 16 + _div_floor( c2, 4 ) );\n		}\n		if ( c3 >= 0 ) {\n			out.push( ( c2 mod 4 ) * 64 + c3 );\n		}\n\n		i += 4;\n	}\n\n	return out;\n}\n\nfunction _latin1_to_string ( BinaryString raw ) {\n	let out := "";\n	for ( let b in _binary_to_bytes(raw) ) {\n		out _= chr(b);\n	}\n	return out;\n}\n\nfunction _read_quoted_string ( String text, Number start ) {\n	let n := length text;\n	if ( substr( text, start, 1 ) ne "\\\\"" ) {\n		die "mail.invalid_address: expected quoted string";\n	}\n\n	let out := "";\n	let i := start + 1;\n	while ( i < n ) {\n		let ch := substr( text, i, 1 );\n		if ( ch eq "\\\\"" ) {\n			return { value: out, end: i + 1 };\n		}\n		if ( ch eq "\\\\\\\\" ) {\n			if ( i + 1 >= n ) {\n				die "mail.invalid_address: unterminated quoted string";\n			}\n			out _= substr( text, i + 1, 1 );\n			i += 2;\n			next;\n		}\n		if ( ch eq "\\\\r" or ch eq "\\\\n" ) {\n			die "mail.invalid_address: quoted string must not contain CR or LF";\n		}\n		out _= ch;\n		i++;\n	}\n\n	die "mail.invalid_address: unterminated quoted string";\n}\n\nfunction _quote_string ( String text ) {\n	let out := "\\\\"";\n	let i := 0;\n	let n := length text;\n\n	while ( i < n ) {\n		let ch := substr( text, i, 1 );\n		if ( ch eq "\\\\\\\\" or ch eq "\\\\"" ) {\n			out _= "\\\\\\\\";\n		}\n		out _= ch;\n		i++;\n	}\n\n	return out _ "\\\\"";\n}\n\nfunction _is_alpha ( String ch ) {\n	let cp := ord(ch);\n	return ( cp >= 65 and cp <= 90 ) or ( cp >= 97 and cp <= 122 );\n}\n\nfunction _is_digit ( String ch ) {\n	let cp := ord(ch);\n	return cp >= 48 and cp <= 57;\n}\n\nfunction _is_atext ( String ch ) {\n	if ( _is_alpha(ch) or _is_digit(ch) ) {\n		return true;\n	}\n	return index( "!#$%&\'*+-/=?^_\\`{|}~", ch ) >= 0;\n}\n\nfunction _is_dot_atom ( String text ) {\n	let n := length text;\n	return false if n == 0;\n	return false if substr( text, 0, 1 ) eq ".";\n	return false if substr( text, n - 1, 1 ) eq ".";\n\n	let prev_dot := false;\n	let i := 0;\n	while ( i < n ) {\n		let ch := substr( text, i, 1 );\n		if ( ch eq "." ) {\n			return false if prev_dot;\n			prev_dot := true;\n		}\n		else {\n			return false if not _is_atext(ch);\n			prev_dot := false;\n		}\n		i++;\n	}\n\n	return true;\n}\n\nfunction _is_domain_text ( String text ) {\n	let n := length text;\n	return false if n == 0;\n	return false if substr( text, 0, 1 ) eq ".";\n	return false if substr( text, n - 1, 1 ) eq ".";\n\n	let i := 0;\n	while ( i < n ) {\n		let ch := substr( text, i, 1 );\n		return false if not(\n			_is_alpha(ch)\n			or _is_digit(ch)\n			or ch eq "-"\n			or ch eq "."\n		);\n		i++;\n	}\n\n	return true;\n}\n\nfunction _is_phrase_text ( String text ) {\n	let n := length text;\n	return false if n == 0;\n	return false if text ne trim(text);\n\n	let i := 0;\n	while ( i < n ) {\n		let ch := substr( text, i, 1 );\n		if ( _is_ws(ch) ) {\n			i++;\n			next;\n		}\n		return false if not _is_atext(ch) and ch ne ".";\n		i++;\n	}\n\n	return true;\n}\n\nfunction _find_unquoted (\n	String text,\n	String target,\n	Number start := 0,\n	Boolean ignore_angle := false,\n) {\n	let i := start;\n	let n := length text;\n	let in_quote := false;\n	let escape := false;\n	let in_literal := false;\n	let angle_depth := 0;\n\n	while ( i < n ) {\n		let ch := substr( text, i, 1 );\n\n		if ( escape ) {\n			escape := false;\n			i++;\n			next;\n		}\n		if ( in_quote ) {\n			if ( ch eq "\\\\\\\\" ) {\n				escape := true;\n			}\n			else if ( ch eq "\\\\"" ) {\n				in_quote := false;\n			}\n			i++;\n			next;\n		}\n		if ( in_literal ) {\n			if ( ch eq "]" ) {\n				in_literal := false;\n			}\n			i++;\n			next;\n		}\n\n		if ( ch eq target and ( not ignore_angle or angle_depth == 0 ) ) {\n			return i;\n		}\n		if ( ch eq "\\\\"" ) {\n			in_quote := true;\n		}\n		else if ( ch eq "[" ) {\n			in_literal := true;\n		}\n		else if ( ch eq "<" ) {\n			angle_depth++;\n		}\n		else if ( ch eq ">" and angle_depth > 0 ) {\n			angle_depth--;\n		}\n\n		i++;\n	}\n\n	return -1;\n}\n\nfunction _find_top_level ( String text, String target, Number start := 0 ) {\n	return _find_unquoted( text, target, start, true );\n}\n\nfunction _parse_phrase ( String raw ) {\n	let text := trim(raw);\n	return null if text eq "";\n\n	if ( substr( text, 0, 1 ) eq "\\\\"" ) {\n		let quoted := _read_quoted_string( text, 0 );\n		if ( trim( substr( text, quoted{end} ) ) ne "" ) {\n			die "mail.invalid_address: text follows quoted display name";\n		}\n		return quoted{value};\n	}\n\n	return text;\n}\n\nfunction _parse_addr_spec ( String raw ) {\n	let text := trim(raw);\n	_assert_no_crlf( text, "invalid_address" );\n\n	if ( substr( text, 0, 1 ) eq "@" ) {\n		die "mail.invalid_address: obsolete route syntax is not supported";\n	}\n\n	let at := _find_unquoted( text, "@", 0, false );\n	if ( at < 0 ) {\n		die "mail.invalid_address: mailbox address is missing @";\n	}\n\n	let route := _find_unquoted( text, ":", 0, false );\n	if ( route >= 0 and route < at ) {\n		die "mail.invalid_address: obsolete route syntax is not supported";\n	}\n\n	let local := trim( substr( text, 0, at ) );\n	let domain := trim( substr( text, at + 1 ) );\n	if ( local eq "" or domain eq "" ) {\n		die "mail.invalid_address: mailbox address is incomplete";\n	}\n\n	if ( substr( local, 0, 1 ) eq "\\\\"" ) {\n		let quoted := _read_quoted_string( local, 0 );\n		if ( quoted{end} != length local ) {\n			die "mail.invalid_address: text follows quoted local part";\n		}\n		local := quoted{value};\n	}\n	else if ( not _is_dot_atom(local) ) {\n		die "mail.invalid_address: invalid local part";\n	}\n\n	if ( substr( domain, 0, 1 ) eq "[" ) {\n		if ( substr( domain, ( length domain ) - 1, 1 ) ne "]" ) {\n			die "mail.invalid_address: unterminated domain literal";\n		}\n		if ( _has_crlf(domain) ) {\n			die "mail.invalid_address: invalid domain literal";\n		}\n	}\n	else if ( not _is_domain_text(domain) ) {\n		die "mail.invalid_address: invalid domain";\n	}\n\n	return { local: local, domain: domain };\n}\n\nfunction _decode_q_encoded_word ( String text ) {\n	let bytes := [];\n	let i := 0;\n	let n := length text;\n\n	while ( i < n ) {\n		let ch := substr( text, i, 1 );\n		if ( ch eq "_" ) {\n			bytes.push(32);\n			i++;\n			next;\n		}\n		if ( ch eq "=" ) {\n			if ( i + 2 >= n ) {\n				return null;\n			}\n			let hi := _hex_value( substr( text, i + 1, 1 ) );\n			let lo := _hex_value( substr( text, i + 2, 1 ) );\n			if ( hi < 0 or lo < 0 ) {\n				return null;\n			}\n			bytes.push( hi * 16 + lo );\n			i += 3;\n			next;\n		}\n\n		let cp := ord(ch);\n		return null if cp > 127;\n		bytes.push(cp);\n		i++;\n	}\n\n	return _bytes_to_binary(bytes);\n}\n\nfunction _normal_charset ( String charset ) {\n	let cs := lc(charset);\n	if ( cs in [ "utf-8", "utf8" ] ) {\n		return "utf-8";\n	}\n	if ( cs in [ "us-ascii", "ascii" ] ) {\n		return "us-ascii";\n	}\n	if ( cs in [ "latin1", "latin-1", "iso-8859-1", "iso8859-1" ] ) {\n		return "latin1";\n	}\n	return null;\n}\n\nfunction _decode_charset_bytes ( BinaryString bytes, String charset ) {\n	let cs := _normal_charset(charset);\n	return null if cs == null;\n\n	if ( cs eq "latin1" ) {\n		return _latin1_to_string(bytes);\n	}\n\n	return try {\n		to_string(bytes);\n	}\n	catch {\n		null;\n	};\n}\n\nfunction _parse_encoded_word_at ( String text, Number start ) {\n	if ( substr( text, start, 2 ) ne "=?" ) {\n		return null;\n	}\n\n	let q1 := index( text, "?", start + 2 );\n	return null if q1 < 0;\n	let q2 := index( text, "?", q1 + 1 );\n	return null if q2 < 0;\n	let end := index( text, "?=", q2 + 1 );\n	return null if end < 0;\n\n	let charset := substr( text, start + 2, q1 - start - 2 );\n	let encoding := lc( substr( text, q1 + 1, q2 - q1 - 1 ) );\n	let payload := substr( text, q2 + 1, end - q2 - 1 );\n	let bytes := null;\n\n	if ( charset eq "" or payload eq "" ) {\n		return null;\n	}\n	if ( encoding eq "b" ) {\n		bytes := try {\n			_base64_decode(payload);\n		}\n		catch {\n			null;\n		};\n	}\n	else if ( encoding eq "q" ) {\n		bytes := _decode_q_encoded_word(payload);\n	}\n	else {\n		return null;\n	}\n\n	return null if bytes == null;\n	let decoded := _decode_charset_bytes( bytes, charset );\n	return null if decoded == null;\n\n	return { text: decoded, end: end + 2 };\n}\n\nfunction _decode_rfc2047 ( String raw ) {\n	let out := "";\n	let pending_ws := "";\n	let last_encoded := false;\n	let i := 0;\n	let n := length raw;\n\n	while ( i < n ) {\n		let ch := substr( raw, i, 1 );\n		if ( _is_ws(ch) ) {\n			let start := i;\n			while ( i < n and _is_ws( substr( raw, i, 1 ) ) ) {\n				i++;\n			}\n			pending_ws _= substr( raw, start, i - start );\n			next;\n		}\n\n		if ( substr( raw, i, 2 ) eq "=?" ) {\n			let parsed := _parse_encoded_word_at( raw, i );\n			if ( not( parsed == null ) ) {\n				out _= pending_ws unless last_encoded;\n				pending_ws := "";\n				out _= parsed{text};\n				last_encoded := true;\n				i := parsed{end};\n				next;\n			}\n		}\n\n		out _= pending_ws;\n		pending_ws := "";\n		out _= ch;\n		last_encoded := false;\n		i++;\n	}\n\n	return out _ pending_ws;\n}\n\nfunction _copy_pairlist ( fields ) {\n	let copy := new PairList();\n	if ( fields == null ) {\n		return copy;\n	}\n	if ( not( fields instanceof PairList ) ) {\n		die "mail.invalid_headers: Head fields expects PairList";\n	}\n	for ( let pair in fields.to_Array() ) {\n		copy.add( pair.key, pair.value );\n	}\n	return copy;\n}\n\nfunction _mail_send_recipients_option ( value ) {\n	if ( value instanceof String ) {\n		return [ value ];\n	}\n	if ( not( value instanceof Array ) ) {\n		die "mail.send: envelope_to expects String or Array";\n	}\n\n	let out := [];\n	for ( let item in value ) {\n		if ( not( item instanceof String ) ) {\n			die "mail.send: envelope_to expects String or Array of String";\n		}\n		out.push(item);\n	}\n	if ( out.length() == 0 ) {\n		die "mail.invalid_address: Message.send requires at least one "\n			_ "envelope recipient";\n	}\n	return out;\n}\n\nfunction _mail_send_options ( PairList options ) {\n	let out := {\n		envelope_from: null,\n		envelope_to: null,\n		send_options: new PairList(),\n	};\n\n	for ( let pair in options.to_Array() ) {\n		if ( pair.key eq "envelope_from" ) {\n			if ( not( pair.value instanceof String ) ) {\n				die "mail.send: envelope_from expects String";\n			}\n			out{envelope_from} := pair.value;\n		}\n		else if ( pair.key eq "envelope_to" ) {\n			out{envelope_to} := _mail_send_recipients_option(pair.value);\n		}\n		else if ( pair.key eq "send_options" ) {\n			if ( not( pair.value instanceof Dict )\n				and not( pair.value instanceof PairList ) ) {\n				die "mail.send: send_options expects Dict or PairList";\n			}\n			out{send_options} := pair.value;\n		}\n		else {\n			die "mail.send: unsupported option \'" _ pair.key _ "\'";\n		}\n	}\n\n	return out;\n}\n\nfunction _valid_header_name ( String name ) {\n	let n := length name;\n	return false if n == 0;\n	let i := 0;\n	while ( i < n ) {\n		let cp := ord( substr( name, i, 1 ) );\n		return false if cp < 33 or cp > 126 or cp == 58;\n		i++;\n	}\n	return true;\n}\n\nfunction _check_header_name ( String name ) {\n	if ( not _valid_header_name(name) ) {\n		die "mail.invalid_headers: invalid header name";\n	}\n}\n\nfunction _check_header_value ( value ) {\n	if ( not( value instanceof String ) ) {\n		die "mail.invalid_headers: header value expects String, got "\n			_ typeof value;\n	}\n	_assert_no_crlf( value, "invalid_headers" );\n}\n\nfunction _split_header_segments ( String text, String delimiter ) {\n	let out := [];\n	let start := 0;\n	let i := 0;\n	let n := length text;\n	let in_quote := false;\n	let escape := false;\n\n	while ( i < n ) {\n		let ch := substr( text, i, 1 );\n		if ( escape ) {\n			escape := false;\n		}\n		else if ( in_quote ) {\n			if ( ch eq "\\\\\\\\" ) {\n				escape := true;\n			}\n			else if ( ch eq "\\\\"" ) {\n				in_quote := false;\n			}\n		}\n		else if ( ch eq "\\\\"" ) {\n			in_quote := true;\n		}\n		else if ( ch eq delimiter ) {\n			out.push( substr( text, start, i - start ) );\n			start := i + 1;\n		}\n		i++;\n	}\n	out.push( substr( text, start ) );\n\n	return out;\n}\n\nfunction _unquote_header_param ( String text ) {\n	let value := trim(text);\n	if ( length value >= 2 and substr( value, 0, 1 ) eq "\\\\"" ) {\n		let quoted := _read_quoted_string( value, 0 );\n		if ( trim( substr( value, quoted{end} ) ) eq "" ) {\n			return quoted{value};\n		}\n	}\n	return value;\n}\n\nfunction _header_main_value ( String value ) {\n	let parts := _split_header_segments( value, ";" );\n	return lc( trim( parts[0] ) );\n}\n\nfunction _header_parameter ( String value, String wanted ) {\n	let parts := _split_header_segments( value, ";" );\n	let i := 1;\n	while ( i < parts.length() ) {\n		let part := parts[i];\n		let equals_at := _find_unquoted( part, "=", 0, false );\n		if ( equals_at > 0 ) {\n			let name := lc( trim( substr( part, 0, equals_at ) ) );\n			if ( name eq lc(wanted) ) {\n				return _unquote_header_param( substr( part, equals_at + 1 ) );\n			}\n		}\n		i++;\n	}\n	return null;\n}\n\nfunction _body_options ( PairList options ) {\n	let opts := {\n		content_type: null,\n		transfer_encoding: null,\n		charset: null,\n		boundary: null,\n	};\n\n	for ( let option in options.to_Array() ) {\n		let key := option.key;\n		let value := option.value;\n		if ( key eq "content_type" ) {\n			opts{content_type} := value;\n		}\n		else if ( key eq "transfer_encoding"\n			or key eq "content_transfer_encoding" ) {\n			opts{transfer_encoding} := value;\n		}\n		else if ( key eq "charset" ) {\n			opts{charset} := value;\n		}\n		else if ( key eq "boundary" ) {\n			opts{boundary} := value;\n		}\n		else {\n			die \\`mail.body: unsupported Body option \'\\${key}\'\\`;\n		}\n	}\n\n	return opts;\n}\n\nfunction _copy_array ( Array items ) {\n	let out := [];\n	for ( let item in items ) {\n		out.push(item);\n	}\n	return out;\n}\n\nfunction _bytes_slice ( Array bytes, Number start, count := null ) {\n	let out := [];\n	let end := count == null ? bytes.length() : start + count;\n	end := bytes.length() if end > bytes.length();\n	let i := start;\n\n	while ( i < end ) {\n		out.push(bytes[i]);\n		i++;\n	}\n\n	return out;\n}\n\nfunction _bytes_to_latin1_string ( Array bytes ) {\n	return _latin1_to_string( _bytes_to_binary(bytes) );\n}\n\nfunction _split_message_bytes ( Array bytes ) {\n	let n := bytes.length();\n	let i := 0;\n	let line_start := 0;\n\n	while ( i < n ) {\n		if ( bytes[i] == 10 ) {\n			let content_end := i;\n			if ( content_end > line_start and bytes[content_end - 1] == 13 ) {\n				content_end--;\n			}\n			if ( content_end == line_start ) {\n				return {\n					header_bytes: _bytes_slice( bytes, 0, line_start ),\n					body_bytes: _bytes_slice( bytes, i + 1 ),\n					header_size: line_start,\n					found_separator: true,\n				};\n			}\n			i++;\n			line_start := i;\n			next;\n		}\n		i++;\n	}\n\n	return {\n		header_bytes: _bytes_slice( bytes, 0 ),\n		body_bytes: [],\n		header_size: n,\n		found_separator: false,\n	};\n}\n\nfunction _mail_header_lines ( Array bytes ) {\n	let lines := [];\n	let n := bytes.length();\n	let i := 0;\n	let line_start := 0;\n\n	while ( i < n ) {\n		if ( bytes[i] == 10 ) {\n			let content_end := i;\n			if ( content_end > line_start and bytes[content_end - 1] == 13 ) {\n				content_end--;\n			}\n			lines.push(\n				_bytes_to_latin1_string(\n					_bytes_slice( bytes, line_start, content_end - line_start ),\n				),\n			);\n			i++;\n			line_start := i;\n			next;\n		}\n		i++;\n	}\n\n	if ( line_start < n ) {\n		lines.push( _bytes_to_latin1_string( _bytes_slice( bytes, line_start ) ) );\n	}\n\n	return lines;\n}\n\nfunction _parse_mail_header_fields ( Array header_bytes ) {\n	let fields := new PairList();\n	let current_name := null;\n	let current_value := "";\n\n	for ( let line in _mail_header_lines(header_bytes) ) {\n		next if line eq "";\n\n		if ( _is_ws( substr( line, 0, 1 ) ) ) {\n			if ( current_name == null ) {\n				die "mail.parse: folded header without previous field";\n			}\n			current_value _= " " _ trim(line);\n			next;\n		}\n\n		if ( not( current_name == null ) ) {\n			fields.add( current_name, current_value );\n		}\n\n		let colon := index( line, ":" );\n		if ( colon <= 0 ) {\n			die "mail.parse: malformed header line";\n		}\n\n		current_name := substr( line, 0, colon );\n		if ( not _valid_header_name(current_name) ) {\n			die "mail.parse: invalid header name";\n		}\n		current_value := trim( substr( line, colon + 1 ) );\n	}\n\n	if ( not( current_name == null ) ) {\n		fields.add( current_name, current_value );\n	}\n\n	return fields;\n}\n\nfunction _only_sp_tab ( String text ) {\n	let i := 0;\n	let n := length text;\n\n	while ( i < n ) {\n		return false if not _is_ws( substr( text, i, 1 ) );\n		i++;\n	}\n\n	return true;\n}\n\nfunction _mail_boundary_line_kind ( Array line_bytes, String boundary ) {\n	let line := _bytes_to_latin1_string(line_bytes);\n	let delimiter := "--" _ boundary;\n	let dlen := length delimiter;\n\n	return null if length line < dlen;\n	return null if substr( line, 0, dlen ) ne delimiter;\n\n	let tail := substr( line, dlen );\n	return "open" if _only_sp_tab(tail);\n\n	if ( length tail >= 2 and substr( tail, 0, 2 ) eq "--" ) {\n		return "close" if _only_sp_tab( substr( tail, 2 ) );\n	}\n\n	return null;\n}\n\nfunction _mail_part_end_before_boundary (\n	Array bytes,\n	Number part_start,\n	Number line_start\n) {\n	let end := line_start;\n	if ( end > part_start and bytes[end - 1] == 10 ) {\n		end--;\n		if ( end > part_start and bytes[end - 1] == 13 ) {\n			end--;\n		}\n	}\n	return end;\n}\n\nfunction _scan_multipart_parts ( Array bytes, String boundary ) {\n	let parts := [];\n	let n := bytes.length();\n	let line_start := 0;\n	let opened := false;\n	let closed := false;\n	let part_start := 0;\n	let preamble_size := 0;\n	let epilogue_size := 0;\n\n	while ( line_start < n ) {\n		let line_end := line_start;\n		while ( line_end < n and bytes[line_end] != 10 ) {\n			line_end++;\n		}\n\n		let content_end := line_end;\n		if ( content_end > line_start and bytes[content_end - 1] == 13 ) {\n			content_end--;\n		}\n\n		let after_line := line_end < n ? line_end + 1 : n;\n		let kind := _mail_boundary_line_kind(\n			_bytes_slice( bytes, line_start, content_end - line_start ),\n			boundary,\n		);\n\n		if ( not( kind == null ) ) {\n			if ( not opened ) {\n				opened := true;\n				preamble_size := line_start;\n				part_start := after_line;\n				if ( kind eq "close" ) {\n					closed := true;\n					epilogue_size := n - after_line;\n					return {\n						opened: opened,\n						closed: closed,\n						parts: parts,\n						preamble_size: preamble_size,\n						epilogue_size: epilogue_size,\n					};\n				}\n			}\n			else {\n				let part_end := _mail_part_end_before_boundary(\n					bytes,\n					part_start,\n					line_start,\n				);\n				parts.push(\n					_bytes_slice( bytes, part_start, part_end - part_start ),\n				);\n				part_start := after_line;\n\n				if ( kind eq "close" ) {\n					closed := true;\n					epilogue_size := n - after_line;\n					return {\n						opened: opened,\n						closed: closed,\n						parts: parts,\n						preamble_size: preamble_size,\n						epilogue_size: epilogue_size,\n					};\n				}\n			}\n		}\n\n		line_start := after_line;\n	}\n\n	if ( opened and not closed ) {\n		parts.push( _bytes_slice( bytes, part_start ) );\n	}\n\n	return {\n		opened: opened,\n		closed: closed,\n		parts: parts,\n		preamble_size: preamble_size,\n		epilogue_size: epilogue_size,\n	};\n}\n\nfunction _is_identity_transfer_encoding ( encoding ) {\n	if ( encoding == null or encoding eq "" ) {\n		return true;\n	}\n	return encoding in [ "identity", "7bit", "8bit", "binary" ];\n}\n\nfunction _invalid_datetime ( String message ) {\n	die "mail.invalid_datetime: " _ message;\n}\n\nfunction _numeric_zone_seconds ( String zone ) {\n	return null if not( zone ~ /^[+-][0-9]{4}$/ );\n\n	let sign := substr( zone, 0, 1 ) eq "-" ? -1 : 1;\n	let hours := int( substr( zone, 1, 2 ) );\n	let minutes := int( substr( zone, 3, 2 ) );\n	return null if hours > 23 or minutes > 59;\n	return sign * ( hours * 3600 + minutes * 60 );\n}\n\nfunction _datetime_apply_option ( Dict opts, Dict seen, key, value ) {\n	if ( not( key instanceof String ) ) {\n		_invalid_datetime("format option names must be strings");\n	}\n	if ( seen.exists(key) ) {\n		_invalid_datetime( "conflicting format option \'" _ key _ "\'" );\n	}\n	seen.set( key, true );\n\n	if ( key eq "utc" ) {\n		if ( not( value instanceof Boolean ) ) {\n			_invalid_datetime("format option \'utc\' expects Boolean");\n		}\n		opts{utc} := value;\n		opts{utc_seen} := true;\n		return;\n	}\n	if ( key eq "offset" ) {\n		if ( not( value instanceof String ) ) {\n			_invalid_datetime("format option \'offset\' expects String");\n		}\n		let seconds := _numeric_zone_seconds(value);\n		if ( seconds == null ) {\n			_invalid_datetime("format option \'offset\' expects +HHMM or -HHMM");\n		}\n		opts{offset} := value;\n		opts{offset_seconds} := seconds;\n		opts{offset_seen} := true;\n		return;\n	}\n	if ( key eq "include_weekday" ) {\n		if ( not( value instanceof Boolean ) ) {\n			_invalid_datetime("format option \'include_weekday\' expects Boolean");\n		}\n		opts{include_weekday} := value;\n		return;\n	}\n\n	_invalid_datetime( "unknown format option \'" _ key _ "\'" );\n}\n\nfunction _datetime_options ( options, PairList named_options ) {\n	let opts := {\n		utc: true,\n		utc_seen: false,\n		offset: "+0000",\n		offset_seconds: 0,\n		offset_seen: false,\n		include_weekday: true,\n	};\n	let seen := {};\n\n	if ( options instanceof Dict ) {\n		for ( let key in options.keys() ) {\n			_datetime_apply_option( opts, seen, key, options.get(key) );\n		}\n	}\n	else if ( options instanceof PairList ) {\n		for ( let pair in options.to_Array() ) {\n			_datetime_apply_option( opts, seen, pair.key, pair.value );\n		}\n	}\n	else {\n		_invalid_datetime("format options expects Dict");\n	}\n\n	for ( let pair in named_options.to_Array() ) {\n		_datetime_apply_option( opts, seen, pair.key, pair.value );\n	}\n\n	if ( opts{offset_seen} and not opts{utc_seen} ) {\n		opts{utc} := false;\n	}\n	if ( opts{utc} and opts{offset_seconds} != 0 ) {\n		_invalid_datetime("format options \'utc\' and \'offset\' conflict");\n	}\n	return opts;\n}\n\nfunction _datetime_parse_error_message ( e ) {\n	let message := lc( "" _ e );\n	return "invalid time zone" if index( message, "invalid time zone" ) >= 0;\n	return "invalid time zone" if index( message, "timezone offset" ) >= 0;\n	return "invalid date" if index( message, "invalid date" ) >= 0;\n	return "invalid time" if index( message, "invalid time" ) >= 0;\n	return "invalid month" if index( message, "invalid month" ) >= 0;\n	return "invalid weekday" if index( message, "invalid weekday" ) >= 0;\n	return "invalid year" if index( message, "invalid year" ) >= 0;\n	return "expected RFC 5322 date-time";\n}\n\nfunction parse_datetime ( String text ) {\n	_assert_no_crlf( text, "invalid_datetime" );\n\n	try {\n		return Time.parse( trim(text) );\n	}\n	catch ( Exception e ) {\n		_invalid_datetime( _datetime_parse_error_message(e) );\n	}\n}\n\nfunction format_datetime (\n	time,\n	options := {},\n	... PairList named_options\n) {\n	if ( not( time instanceof Time ) ) {\n		_invalid_datetime("format_datetime expects Time");\n	}\n\n	let opts := _datetime_options( options, named_options );\n	let zoned := opts{utc}\n		? time.with_timezone( TimeZone.utc() )\n		: time.with_timezone( TimeZone.offset(opts{offset_seconds}) );\n	return zoned.to_rfc5322( include_weekday: opts{include_weekday} );\n}\n\nclass Address {\n	let local := null;\n	let domain := null;\n	let display_name := null;\n\n	method __build__ () {\n		if ( not( local instanceof String ) or local eq "" ) {\n			die "mail.invalid_address: local part expects non-empty String";\n		}\n		if ( not( domain instanceof String ) or domain eq "" ) {\n			die "mail.invalid_address: domain expects non-empty String";\n		}\n		if ( not( display_name == null ) and not( display_name instanceof String ) ) {\n			die "mail.invalid_address: display_name expects String or null";\n		}\n\n		_assert_no_crlf( local, "invalid_address" );\n		_assert_no_crlf( domain, "invalid_address" );\n		if ( not( display_name == null ) ) {\n			_assert_no_crlf( display_name, "invalid_address" );\n		}\n	}\n\n	method local () {\n		return local;\n	}\n\n	method domain () {\n		return domain;\n	}\n\n	method display_name () {\n		return display_name;\n	}\n\n	method address () {\n		let lhs := _is_dot_atom(local) ? local : _quote_string(local);\n		return lhs _ "@" _ domain;\n	}\n\n	method to_header () {\n		if ( display_name == null or display_name eq "" ) {\n			return self.address();\n		}\n\n		let name := _is_phrase_text(display_name)\n			? display_name\n			: _quote_string(display_name);\n		return name _ " <" _ self.address() _ ">";\n	}\n\n	method to_String () {\n		return self.to_header();\n	}\n\n	method to_Dict () {\n		return {\n			local: local,\n			domain: domain,\n			display_name: display_name,\n			address: self.address(),\n			header: self.to_header(),\n		};\n	}\n\n	static method parse ( String text ) {\n		return _parse_one_address(text);\n	}\n\n	static method parse_list ( String text ) {\n		return _parse_address_list(text);\n	}\n}\n\nfunction _parse_one_address ( String raw ) {\n	let text := trim(raw);\n	_assert_no_crlf( text, "invalid_address" );\n\n	if ( text eq "" ) {\n		die "mail.invalid_address: empty address";\n	}\n	if ( _find_unquoted( text, "(", 0, false ) >= 0\n		or _find_unquoted( text, ")", 0, false ) >= 0 ) {\n		die "mail.invalid_address: obsolete comment syntax is not supported";\n	}\n\n	let angle_start := _find_unquoted( text, "<", 0, false );\n	if ( angle_start >= 0 ) {\n		let angle_end := _find_unquoted( text, ">", angle_start + 1, false );\n		if ( angle_end < 0 ) {\n			die "mail.invalid_address: unterminated angle address";\n		}\n		if ( trim( substr( text, angle_end + 1 ) ) ne "" ) {\n			die "mail.invalid_address: text follows angle address";\n		}\n\n		let spec := _parse_addr_spec(\n			substr( text, angle_start + 1, angle_end - angle_start - 1 ),\n		);\n		return new Address(\n			local: spec{local},\n			domain: spec{domain},\n			display_name: _parse_phrase( substr( text, 0, angle_start ) ),\n		);\n	}\n\n	let spec := _parse_addr_spec(text);\n	return new Address( local: spec{local}, domain: spec{domain} );\n}\n\nfunction _parse_address_list ( String text ) {\n	_assert_no_crlf( text, "invalid_address" );\n\n	let out := [];\n	let i := 0;\n	let n := length text;\n\n	while ( i < n ) {\n		i := _skip_ws( text, i );\n		if ( i < n and substr( text, i, 1 ) eq "," ) {\n			i++;\n			next;\n		}\n\n		let comma := _find_top_level( text, ",", i );\n		let semi := _find_top_level( text, ";", i );\n		let colon := _find_top_level( text, ":", i );\n		let group_end := semi;\n\n		if ( colon >= 0\n			and ( comma < 0 or colon < comma )\n			and ( semi < 0 or colon < semi ) ) {\n			if ( group_end < 0 ) {\n				die "mail.invalid_address: unterminated address group";\n			}\n			for ( let addr in _parse_address_list(\n				substr( text, colon + 1, group_end - colon - 1 ),\n			) ) {\n				out.push(addr);\n			}\n			i := group_end + 1;\n			next;\n		}\n\n		let end := comma < 0 ? n : comma;\n		if ( semi >= 0 and semi < end ) {\n			end := semi;\n		}\n		let token := trim( substr( text, i, end - i ) );\n		if ( token ne "" ) {\n			out.push( Address.parse(token) );\n		}\n		i := end + 1;\n	}\n\n	return out;\n}\n\nfunction _parse_address_header ( value ) {\n	if ( value == null ) {\n		return [];\n	}\n	return Address.parse_list(value);\n}\n\nfunction _mail_send_addresses_from_headers ( head, Array names ) {\n	let out := [];\n	for ( let name in names ) {\n		for ( let value in head.decoded_all(name) ) {\n			for ( let address in Address.parse_list(value) ) {\n				out.push(address);\n			}\n		}\n	}\n	return out;\n}\n\nfunction _mail_send_envelope_from ( head ) {\n	let senders := _mail_send_addresses_from_headers( head, [ "Sender" ] );\n	if ( senders.length() == 1 ) {\n		return senders[0].address();\n	}\n	if ( senders.length() > 1 ) {\n		die "mail.invalid_address: Message.send requires exactly one "\n			_ "Sender address";\n	}\n\n	let from_addrs := _mail_send_addresses_from_headers( head, [ "From" ] );\n	if ( from_addrs.length() == 1 ) {\n		return from_addrs[0].address();\n	}\n	if ( from_addrs.length() > 1 ) {\n		die "mail.invalid_address: Message.send requires exactly one "\n			_ "From address when Sender is absent";\n	}\n	die "mail.invalid_address: Message.send requires a Sender or From "\n		_ "address";\n}\n\nfunction _mail_send_envelope_to ( head ) {\n	let addresses := _mail_send_addresses_from_headers(\n		head,\n		[ "To", "Cc", "Bcc" ],\n	);\n	let seen := {};\n	let out := [];\n\n	for ( let address in addresses ) {\n		let value := address.address();\n		if ( not( value in seen ) ) {\n			seen{(value)} := true;\n			out.push(value);\n		}\n	}\n	if ( out.length() == 0 ) {\n		die "mail.invalid_address: Message.send requires at least one "\n			_ "envelope recipient";\n	}\n	return out;\n}\n\nfunction _mail_send_headers ( head ) {\n	let out := new PairList();\n	for ( let pair in head.to_PairList().to_Array() ) {\n		if ( lc(pair.key) ne "bcc" ) {\n			out.add( pair.key, pair.value );\n		}\n	}\n	return out;\n}\n\nclass Head {\n	let fields := null;\n\n	method __build__ () {\n		fields := _copy_pairlist(fields);\n		for ( let pair in fields.to_Array() ) {\n			_check_header_name(pair.key);\n			_check_header_value(pair.value);\n		}\n	}\n\n	method fields () {\n		return fields.keys();\n	}\n\n	method raw ( String name, fallback := null ) {\n		_check_header_name(name);\n		let key := lc(name);\n		for ( let pair in fields.to_Array() ) {\n			if ( lc(pair.key) eq key ) {\n				return pair.value;\n			}\n		}\n		return fallback;\n	}\n\n	method raw_all ( String name ) {\n		_check_header_name(name);\n		let key := lc(name);\n		let out := [];\n		for ( let pair in fields.to_Array() ) {\n			if ( lc(pair.key) eq key ) {\n				out.push(pair.value);\n			}\n		}\n		return out;\n	}\n\n	method decoded ( String name, fallback := null ) {\n		let raw := self.raw( name, null );\n		return fallback if raw == null;\n		return _decode_rfc2047(raw);\n	}\n\n	method decoded_all ( String name ) {\n		let out := [];\n		for ( let value in self.raw_all(name) ) {\n			out.push( _decode_rfc2047(value) );\n		}\n		return out;\n	}\n\n	method get ( String name, fallback := null ) {\n		return self.decoded( name, fallback );\n	}\n\n	method get_all ( String name ) {\n		return self.decoded_all(name);\n	}\n\n	method set ( String name, String value ) {\n		self.remove(name);\n		return self.add( name, value );\n	}\n\n	method add ( String name, String value ) {\n		_check_header_name(name);\n		_check_header_value(value);\n		fields.add( name, value );\n		return self;\n	}\n\n	method remove ( String name ) {\n		_check_header_name(name);\n		let key := lc(name);\n		let kept := new PairList();\n		for ( let pair in fields.to_Array() ) {\n			if ( lc(pair.key) ne key ) {\n				kept.add( pair.key, pair.value );\n			}\n		}\n		fields := kept;\n		return self;\n	}\n\n	method has ( String name ) {\n		return not( self.raw( name, null ) == null );\n	}\n\n	method to_PairList () {\n		return _copy_pairlist(fields);\n	}\n\n	method to_Iterator () {\n		let items := fields.to_Array();\n		return items.to_Iterator();\n	}\n\n	method content_type () {\n		let value := self.decoded( "Content-Type", null );\n		return value == null ? null : _header_main_value(value);\n	}\n\n	method content_transfer_encoding () {\n		let value := self.decoded( "Content-Transfer-Encoding", null );\n		return value == null ? null : lc( trim(value) );\n	}\n\n	method charset () {\n		let value := self.decoded( "Content-Type", null );\n		let got := value == null ? null : _header_parameter( value, "charset" );\n		return got == null ? null : lc(got);\n	}\n\n	method boundary () {\n		let value := self.decoded( "Content-Type", null );\n		return value == null ? null : _header_parameter( value, "boundary" );\n	}\n\n	method message_id () {\n		return self.decoded( "Message-ID", null );\n	}\n\n	method date () {\n		return self.decoded( "Date", null );\n	}\n\n	method from () {\n		return _parse_address_header( self.decoded( "From", null ) );\n	}\n\n	method to () {\n		return _parse_address_header( self.decoded( "To", null ) );\n	}\n\n	method cc () {\n		return _parse_address_header( self.decoded( "Cc", null ) );\n	}\n\n	method bcc () {\n		return _parse_address_header( self.decoded( "Bcc", null ) );\n	}\n\n	method subject () {\n		return self.decoded( "Subject", null );\n	}\n}\n\nclass _BodyBase {\n	let kind := "bytes";\n	let _bytes := null;\n	let _parts := null;\n	let _nested := null;\n	let content_type := null;\n	let transfer_encoding := null;\n	let charset := null;\n	let boundary := null;\n	let _owner_message but weak;\n\n	method __build__ () {\n		_bytes := to_binary("") if _bytes == null;\n		_parts := [] if _parts == null;\n		self._refresh_links();\n	}\n\n	method _refresh_links () {\n		if ( kind eq "multipart" ) {\n			for ( let part in _parts ) {\n				part._set_container(self);\n			}\n		}\n		else if ( kind eq "nested" and not( _nested == null ) ) {\n			_nested._set_container(self);\n		}\n		return self;\n	}\n\n	method _set_owner_message ( owner ) {\n		_owner_message := owner but weak;\n		return self;\n	}\n\n	method owner_message () {\n		return _owner_message;\n	}\n\n	method is_multipart () {\n		return kind eq "multipart";\n	}\n\n	method is_nested () {\n		return kind eq "nested";\n	}\n\n	method bytes () {\n		if ( kind ne "bytes" ) {\n			die "mail.body: only leaf bodies expose bytes";\n		}\n		return _bytes;\n	}\n\n	method parts () {\n		return _copy_array(_parts);\n	}\n\n	method part ( Number index ) {\n		if ( kind ne "multipart" ) {\n			die "mail.body: only multipart bodies expose parts";\n		}\n		return _parts[index];\n	}\n\n	method count () {\n		if ( kind eq "multipart" ) {\n			return _parts.length();\n		}\n		return kind eq "nested" ? 1 : 0;\n	}\n\n	method nested () {\n		return kind eq "nested" ? _nested : null;\n	}\n\n	method content_type () {\n		return content_type;\n	}\n\n	method transfer_encoding () {\n		return transfer_encoding == null ? "identity" : lc(transfer_encoding);\n	}\n\n	method decoded () {\n		if ( kind ne "bytes" ) {\n			die "mail.body: multipart/nested decoding is planned for Phase 10";\n		}\n\n		let enc := self.transfer_encoding();\n		if ( enc eq "base64" ) {\n			return _base64_decode( to_string(_bytes) );\n		}\n		if ( enc eq "quoted-printable" ) {\n			return _qp_decode( to_string(_bytes) );\n		}\n		if ( enc in [ "identity", "7bit", "8bit", "binary" ] ) {\n			return _bytes;\n		}\n\n		die \\`mail.body: unsupported transfer encoding \'\\${enc}\'\\`;\n	}\n\n	method encoded () {\n		if ( kind ne "bytes" ) {\n			die "mail.body: multipart/nested encoding is planned for Phase 10";\n		}\n		return _bytes;\n	}\n\n	method to_Dict () {\n		if ( kind eq "multipart" ) {\n			return {\n				kind: kind,\n				content_type: content_type,\n				transfer_encoding: transfer_encoding,\n				charset: charset,\n				boundary: boundary,\n				parts: _parts.map( fn part -> part.to_Dict() ),\n			};\n		}\n		if ( kind eq "nested" ) {\n			return {\n				kind: kind,\n				content_type: content_type,\n				transfer_encoding: transfer_encoding,\n				charset: charset,\n				message: _nested == null ? null : _nested.to_Dict(),\n			};\n		}\n		return {\n			kind: kind,\n			content_type: content_type,\n			transfer_encoding: transfer_encoding,\n			charset: charset,\n			bytes: _bytes,\n		};\n	}\n\n}\n\nclass Body extends _BodyBase {\n	static method bytes ( BinaryString raw, ... PairList options ) {\n		let opts := _body_options(options);\n		return new Body(\n			kind: "bytes",\n			_bytes: raw,\n			content_type: opts{content_type},\n			transfer_encoding: opts{transfer_encoding},\n			charset: opts{charset},\n		);\n	}\n\n	static method multipart (\n		Array parts,\n		String boundary,\n		... PairList options\n	) {\n		_assert_no_crlf( boundary, "body" );\n		let opts := _body_options(options);\n		let ctype := opts{content_type} == null\n			? "multipart/mixed"\n			: opts{content_type};\n		let body := new Body(\n			kind: "multipart",\n			_parts: _copy_array(parts),\n			content_type: ctype,\n			transfer_encoding: opts{transfer_encoding},\n			charset: opts{charset},\n			boundary: boundary,\n		);\n		return body._refresh_links();\n	}\n\n	static method nested ( message, ... PairList options ) {\n		let opts := _body_options(options);\n		let ctype := opts{content_type} == null\n			? "message/rfc822"\n			: opts{content_type};\n		let body := new Body(\n			kind: "nested",\n			_nested: message,\n			content_type: ctype,\n			transfer_encoding: opts{transfer_encoding},\n			charset: opts{charset},\n		);\n		return body._refresh_links();\n	}\n}\n\nclass Message {\n	let head := null;\n	let body := null;\n	let _container but weak;\n\n	method __build__ () {\n		head := new Head() if head == null;\n		body := Body.bytes( to_binary("") ) if body == null;\n		body._set_owner_message(self);\n	}\n\n	method _set_container ( container ) {\n		_container := container but weak;\n		return self;\n	}\n\n	method head () {\n		return head;\n	}\n\n	method body () {\n		return body;\n	}\n\n	method header ( String name, fallback := null ) {\n		return head.get( name, fallback );\n	}\n\n	method headers ( String name ) {\n		return head.get_all(name);\n	}\n\n	method set_header ( String name, String value ) {\n		head.set( name, value );\n		return self;\n	}\n\n	method add_header ( String name, String value ) {\n		head.add( name, value );\n		return self;\n	}\n\n	method remove_header ( String name ) {\n		head.remove(name);\n		return self;\n	}\n\n	method subject () {\n		return head.subject();\n	}\n\n	method from () {\n		return head.from();\n	}\n\n	method to () {\n		return head.to();\n	}\n\n	method cc () {\n		return head.cc();\n	}\n\n	method bcc () {\n		return head.bcc();\n	}\n\n	method date () {\n		return head.date();\n	}\n\n	method message_id () {\n		return head.message_id();\n	}\n\n	method is_part () {\n		return not( _container == null );\n	}\n\n	method container () {\n		return _container;\n	}\n\n	method toplevel () {\n		let current := self;\n		while ( not( current.container() == null ) ) {\n			let owner := current.container().owner_message();\n			return current if owner == null;\n			current := owner;\n		}\n		return current;\n	}\n\n	method send ( mailer, ... PairList options ) {\n		if ( mailer == null or not( mailer can "send" ) ) {\n			die "mail.unsupported: Message.send requires a compatible mailer";\n		}\n\n		let opts := _mail_send_options(options);\n		let envelope_from := opts{envelope_from} == null\n			? _mail_send_envelope_from(head)\n			: opts{envelope_from};\n		let envelope_to := opts{envelope_to} == null\n			? _mail_send_envelope_to(head)\n			: opts{envelope_to};\n		let headers := _mail_send_headers(head);\n		let send_body := _mail_send_serialize_body(self);\n\n		return mailer.send(\n			envelope_from,\n			envelope_to,\n			headers,\n			send_body,\n			opts{send_options},\n		);\n	}\n\n	method to_Dict () {\n		return {\n			head: head.to_PairList(),\n			body: body.to_Dict(),\n			is_part: self.is_part(),\n		};\n	}\n}\n\nclass Parser {\n	let strict := false;\n	let max_header_bytes := 65536;\n	let max_depth := 32;\n	let decode_transfer := false;\n	let _warnings := [];\n\n	method __build__ () {\n		if ( not( strict instanceof Boolean ) ) {\n			die "mail.parse: strict expects Boolean";\n		}\n		if ( not( max_header_bytes instanceof Number ) or max_header_bytes < 0 ) {\n			die "mail.parse: max_header_bytes expects non-negative Number";\n		}\n		if ( not( max_depth instanceof Number ) or max_depth < 0 ) {\n			die "mail.parse: max_depth expects non-negative Number";\n		}\n		if ( not( decode_transfer instanceof Boolean ) ) {\n			die "mail.parse: decode_transfer expects Boolean";\n		}\n\n		_warnings := [];\n	}\n\n	method warnings () {\n		return _copy_array(_warnings);\n	}\n\n	method _warn ( String message ) {\n		_warnings.push( "mail.parse: " _ message );\n		return self;\n	}\n\n	method _fail ( String message ) {\n		die "mail.parse: " _ message;\n	}\n\n	method _enforce_depth ( Number depth ) {\n		if ( depth > max_depth ) {\n			self._fail("max_depth exceeded");\n		}\n	}\n\n	method _parse_head ( Array header_bytes ) {\n		let fields := _parse_mail_header_fields(header_bytes);\n		return new Head( fields: fields );\n	}\n\n	method _header_malformed_message ( BinaryString raw ) {\n		self._warn("malformed header section; preserving original bytes");\n		return new Message(\n			head: new Head(),\n			body: Body.bytes(raw),\n		);\n	}\n\n	method _safe_content_type ( Head head ) {\n		try {\n			return head.content_type();\n		}\n		catch {\n			if ( strict ) {\n				self._fail("malformed Content-Type header");\n			}\n			self._warn("malformed Content-Type header");\n			return null;\n		}\n	}\n\n	method _safe_charset ( Head head ) {\n		try {\n			return head.charset();\n		}\n		catch {\n			if ( strict ) {\n				self._fail("malformed Content-Type charset");\n			}\n			self._warn("malformed Content-Type charset");\n			return null;\n		}\n	}\n\n	method _safe_boundary ( Head head ) {\n		try {\n			return head.boundary();\n		}\n		catch {\n			if ( strict ) {\n				self._fail("malformed multipart boundary");\n			}\n			self._warn("malformed multipart boundary");\n			return null;\n		}\n	}\n\n	method _safe_transfer_encoding ( Head head ) {\n		try {\n			return head.content_transfer_encoding();\n		}\n		catch {\n			if ( strict ) {\n				self._fail("malformed Content-Transfer-Encoding header");\n			}\n			self._warn("malformed Content-Transfer-Encoding header");\n			return null;\n		}\n	}\n\n	method _leaf_body (\n		BinaryString raw,\n		content_type,\n		transfer_encoding,\n		charset\n	) {\n		return Body.bytes(\n			raw,\n			content_type: content_type,\n			transfer_encoding: transfer_encoding,\n			charset: charset,\n		);\n	}\n\n	method _multipart_body (\n		BinaryString raw,\n		Array body_bytes,\n		String content_type,\n		transfer_encoding,\n		charset,\n		boundary,\n		Number depth\n	) {\n		if ( boundary == null or boundary eq "" or _has_crlf(boundary) ) {\n			if ( strict ) {\n				self._fail("multipart body missing boundary");\n			}\n			self._warn("multipart body missing boundary; using leaf body");\n			return self._leaf_body( raw, content_type, transfer_encoding, charset );\n		}\n\n		let scanned := _scan_multipart_parts( body_bytes, boundary );\n		if ( not scanned{opened} ) {\n			if ( strict ) {\n				self._fail("multipart boundary open delimiter not found");\n			}\n			self._warn("multipart boundary open delimiter not found; using leaf body");\n			return self._leaf_body( raw, content_type, transfer_encoding, charset );\n		}\n\n		if ( scanned{preamble_size} > 0 ) {\n			self._warn("multipart preamble ignored");\n		}\n		if ( scanned{epilogue_size} > 0 ) {\n			self._warn("multipart epilogue ignored");\n		}\n		if ( not scanned{closed} ) {\n			if ( strict ) {\n				self._fail("multipart boundary close delimiter not found");\n			}\n			self._warn("multipart boundary close delimiter not found");\n		}\n\n		let messages := [];\n		for ( let part_bytes in scanned{parts} ) {\n			messages.push(\n				self._parse_message( _bytes_to_binary(part_bytes), depth + 1 ),\n			);\n		}\n\n		return Body.multipart(\n			messages,\n			boundary,\n			content_type: content_type,\n			transfer_encoding: transfer_encoding,\n			charset: charset,\n		);\n	}\n\n	method _nested_body (\n		BinaryString raw,\n		String content_type,\n		transfer_encoding,\n		charset,\n		Number depth\n	) {\n		if ( not _is_identity_transfer_encoding(transfer_encoding) ) {\n			if ( strict ) {\n				self._fail("encoded message/rfc822 bodies are not supported");\n			}\n			self._warn("encoded message/rfc822 body kept as leaf body");\n			return self._leaf_body( raw, content_type, transfer_encoding, charset );\n		}\n\n		return Body.nested(\n			self._parse_message( raw, depth + 1 ),\n			content_type: content_type,\n			transfer_encoding: transfer_encoding,\n			charset: charset,\n		);\n	}\n\n	method _parse_message ( BinaryString raw, Number depth ) {\n		self._enforce_depth(depth);\n\n		let bytes := _binary_to_bytes(raw);\n		let split := _split_message_bytes(bytes);\n		if ( split{header_size} > max_header_bytes ) {\n			self._fail("max_header_bytes exceeded");\n		}\n\n		let head;\n		if ( strict ) {\n			head := try {\n				self._parse_head( split{header_bytes} );\n			} catch {\n				self._fail("malformed header section");\n			};\n		}\n		else {\n			let fallback := null;\n			head := try {\n				self._parse_head( split{header_bytes} );\n			} catch {\n				fallback := self._header_malformed_message(raw);\n				null;\n			};\n			return fallback if not( fallback == null );\n		}\n\n		let raw_body := _bytes_to_binary( split{body_bytes} );\n		let content_type := self._safe_content_type(head);\n		let charset := self._safe_charset(head);\n		let boundary := self._safe_boundary(head);\n		let transfer_encoding := self._safe_transfer_encoding(head);\n		let body;\n\n		if ( not( content_type == null ) and index( content_type, "multipart/" ) == 0 ) {\n			body := self._multipart_body(\n				raw_body,\n				split{body_bytes},\n				content_type,\n				transfer_encoding,\n				charset,\n				boundary,\n				depth,\n			);\n		}\n		else if ( content_type eq "message/rfc822" ) {\n			body := self._nested_body(\n				raw_body,\n				content_type,\n				transfer_encoding,\n				charset,\n				depth,\n			);\n		}\n		else {\n			body := self._leaf_body(\n				raw_body,\n				content_type,\n				transfer_encoding,\n				charset,\n			);\n		}\n\n		return new Message( head: head, body: body );\n	}\n\n	method parse ( BinaryString bytes ) {\n		return self._parse_message( bytes, 0 );\n	}\n}\n\nfunction _mail_serialize_fail ( String message ) {\n	die "mail.serialize: " _ message;\n}\n\nfunction _mail_serialize_append_text (\n	Array out,\n	String text,\n	String context\n) {\n	let i := 0;\n	let n := length text;\n\n	while ( i < n ) {\n		let cp := ord( substr( text, i, 1 ) );\n		if ( cp > 255 ) {\n			_mail_serialize_fail(\n				context _ " contains a character outside byte range",\n			);\n		}\n		out.push(cp);\n		i++;\n	}\n\n	return out;\n}\n\nfunction _mail_serialize_append_binary ( Array out, BinaryString bytes ) {\n	for ( let b in _binary_to_bytes(bytes) ) {\n		out.push(b);\n	}\n	return out;\n}\n\nfunction _mail_serialize_header_words ( String value ) {\n	let words := [];\n	let i := 0;\n	let n := length value;\n\n	while ( i < n ) {\n		i := _skip_ws( value, i );\n		last if i >= n;\n\n		let start := i;\n		while ( i < n and not _is_ws( substr( value, i, 1 ) ) ) {\n			i++;\n		}\n		words.push( substr( value, start, i - start ) );\n	}\n\n	return words;\n}\n\nfunction _mail_serialize_folded_header_lines (\n	String name,\n	String value,\n	Number line_length\n) {\n	let unfolded := name _ ": " _ value;\n	return [ unfolded ] if length unfolded <= line_length;\n\n	let words := _mail_serialize_header_words(value);\n	return [ unfolded ] if words.length() <= 1;\n\n	let lines := [];\n	let first_prefix := name _ ": ";\n	let line := first_prefix;\n\n	for ( let word in words ) {\n		let separator := ( line eq first_prefix or line eq "\\\\t" )\n			? ""\n			: " ";\n		let candidate := line _ separator _ word;\n\n		if ( length candidate <= line_length\n			or line eq first_prefix\n			or line eq "\\\\t" ) {\n			line := candidate;\n			next;\n		}\n\n		lines.push(line);\n		line := "\\\\t" _ word;\n	}\n\n	lines.push(line);\n	return lines;\n}\n\nfunction _mail_serialize_quote_boundary ( String boundary ) {\n	return _quote_string(boundary);\n}\n\nclass Serializer {\n	let newline := "\\\\r\\\\n";\n	let fold_headers := true;\n	let line_length := 78;\n	let generate_boundary := false;\n	let _boundary_counter := 0;\n\n	method __build__ () {\n		if ( not( newline instanceof String ) ) {\n			self._fail("newline expects String");\n		}\n		if ( newline ne "\\\\r\\\\n" and newline ne "\\\\n" ) {\n			self._fail("newline must be CRLF or LF");\n		}\n		if ( not( fold_headers instanceof Boolean ) ) {\n			self._fail("fold_headers expects Boolean");\n		}\n		if ( not( line_length instanceof Number ) ) {\n			self._fail("line_length expects Number");\n		}\n		if ( line_length < 1 ) {\n			self._fail("line_length must be positive");\n		}\n		if ( not( generate_boundary instanceof Boolean ) ) {\n			self._fail("generate_boundary expects Boolean");\n		}\n		if ( not( _boundary_counter instanceof Number ) or _boundary_counter < 0 ) {\n			self._fail("_boundary_counter expects non-negative Number");\n		}\n\n		line_length := int(line_length);\n		_boundary_counter := int(_boundary_counter);\n	}\n\n	method _fail ( String message ) {\n		_mail_serialize_fail(message);\n	}\n\n	method _reject_method_options ( PairList options ) {\n		let items := options.to_Array();\n		if ( items.length() > 0 ) {\n			self._fail(\n				"unsupported method option \'" _ items[0].key\n					_ "\'; use constructor named arguments",\n			);\n		}\n	}\n\n	method _validate_header_pair ( pair ) {\n		if ( not( pair.key instanceof String ) or not _valid_header_name(pair.key) ) {\n			self._fail("invalid header name");\n		}\n		if ( not( pair.value instanceof String ) ) {\n			self._fail("header value expects String, got " _ typeof pair.value);\n		}\n		if ( _has_crlf(pair.value) ) {\n			self._fail("header value must not contain CR or LF");\n		}\n	}\n\n	method _append_line ( Array out, String line ) {\n		_mail_serialize_append_text( out, line, "header line" );\n		_mail_serialize_append_text( out, newline, "newline" );\n	}\n\n	method _append_header ( Array out, String name, String value ) {\n		let lines := fold_headers\n			? _mail_serialize_folded_header_lines(\n				name,\n				value,\n				line_length,\n			)\n			: [ name _ ": " _ value ];\n\n		for ( let line in lines ) {\n			self._append_line( out, line );\n		}\n	}\n\n	method _generated_boundary () {\n		_boundary_counter++;\n		return \\`zuzu-boundary-\\${_boundary_counter}\\`;\n	}\n\n	method _validate_boundary ( String boundary ) {\n		if ( boundary eq "" ) {\n			self._fail("multipart body missing boundary");\n		}\n		if ( _has_crlf(boundary) ) {\n			self._fail("multipart boundary must not contain CR or LF");\n		}\n		return boundary;\n	}\n\n	method _header_boundary ( Head head ) {\n		let value := head.raw( "Content-Type", null );\n		return null if value == null;\n\n		let boundary := null;\n		try {\n			boundary := _header_parameter( value, "boundary" );\n		}\n		catch {\n			boundary := null;\n		}\n\n		return boundary;\n	}\n\n	method _body_content_type ( body ) {\n		let data := body.to_Dict();\n		let content_type := data{content_type};\n		return "multipart/mixed" if content_type == null;\n		if ( not( content_type instanceof String ) ) {\n			self._fail("multipart content_type expects String");\n		}\n		return content_type;\n	}\n\n	method _content_type_with_boundary (\n		body,\n		String value,\n		String boundary\n	) {\n		let existing := null;\n		let main := null;\n		try {\n			existing := _header_parameter( value, "boundary" );\n			main := _header_main_value(value);\n		}\n		catch {\n			existing := null;\n			main := null;\n		}\n\n		let quoted := _mail_serialize_quote_boundary(boundary);\n		if ( not( existing == null ) and existing eq "" ) {\n			return self._body_content_type(body) _ "; boundary=" _ quoted;\n		}\n		if ( existing == null ) {\n			if ( main == null or index( main, "multipart/" ) != 0 ) {\n				return self._body_content_type(body) _ "; boundary=" _ quoted;\n			}\n			return value _ "; boundary=" _ quoted;\n		}\n\n		return value;\n	}\n\n	method _generated_content_type ( body, String boundary ) {\n		return self._body_content_type(body)\n			_ "; boundary="\n			_ _mail_serialize_quote_boundary(boundary);\n	}\n\n	method _full_context ( Message message ) {\n		let body := message.body();\n		let data := body.to_Dict();\n		if ( data{kind} ne "multipart" ) {\n			return { multipart: false, boundary: null };\n		}\n\n		let boundary := data{boundary};\n		if ( not( boundary == null ) and not( boundary instanceof String ) ) {\n			self._fail("multipart boundary expects String");\n		}\n		if ( boundary == null or boundary eq "" ) {\n			boundary := self._header_boundary( message.head() );\n		}\n		if ( not( boundary == null ) and not( boundary instanceof String ) ) {\n			self._fail("multipart boundary expects String");\n		}\n		if ( boundary == null or boundary eq "" ) {\n			if ( generate_boundary ) {\n				boundary := self._generated_boundary();\n			}\n			else {\n				return { multipart: true, boundary: null };\n			}\n		}\n\n		return {\n			multipart: true,\n			boundary: self._validate_boundary(boundary),\n		};\n	}\n\n	method _multipart_boundary ( body, boundary_override := null ) {\n		if ( not( boundary_override == null ) ) {\n			return self._validate_boundary(boundary_override);\n		}\n\n		let data := body.to_Dict();\n		let boundary := data{boundary};\n\n		if ( boundary == null or boundary eq "" ) {\n			if ( generate_boundary ) {\n				return self._generated_boundary();\n			}\n			self._fail("multipart body missing boundary");\n		}\n		if ( not( boundary instanceof String ) ) {\n			self._fail("multipart boundary expects String");\n		}\n		return self._validate_boundary(boundary);\n	}\n\n	method _serialize_body ( body, boundary_override := null ) {\n		let data := body.to_Dict();\n		let kind := data{kind};\n\n		if ( kind eq "bytes" ) {\n			return body.encoded();\n		}\n		if ( kind eq "nested" ) {\n			let nested := body.nested();\n			if ( nested == null ) {\n				self._fail("message/rfc822 body missing nested message");\n			}\n			return self.serialize(nested);\n		}\n		if ( kind ne "multipart" ) {\n			self._fail("unsupported body kind \'" _ kind _ "\'");\n		}\n\n		let boundary := self._multipart_boundary( body, boundary_override );\n		let out := [];\n\n		for ( let part in body.parts() ) {\n			_mail_serialize_append_text( out, "--" _ boundary, "boundary" );\n			_mail_serialize_append_text( out, newline, "newline" );\n			_mail_serialize_append_binary( out, self.serialize(part) );\n			_mail_serialize_append_text( out, newline, "newline" );\n		}\n\n		_mail_serialize_append_text( out, "--" _ boundary _ "--", "boundary" );\n		_mail_serialize_append_text( out, newline, "newline" );\n\n		return _bytes_to_binary(out);\n	}\n\n	method serialize_body ( Message message, ... PairList options ) {\n		self._reject_method_options(options);\n		return self._serialize_body( message.body() );\n	}\n\n	method serialize ( Message message, ... PairList options ) {\n		self._reject_method_options(options);\n		let out := [];\n		let context := self._full_context(message);\n		let saw_content_type := false;\n\n		for ( let pair in message.head().to_PairList().to_Array() ) {\n			self._validate_header_pair(pair);\n			let value := pair.value;\n			if ( context{multipart}\n				and lc(pair.key) eq "content-type"\n				and not saw_content_type\n				and not( context{boundary} == null ) ) {\n				value := self._content_type_with_boundary(\n					message.body(),\n					value,\n					context{boundary},\n				);\n				saw_content_type := true;\n			}\n			else if ( lc(pair.key) eq "content-type" ) {\n				saw_content_type := true;\n			}\n			self._append_header( out, pair.key, value );\n		}\n\n		if ( context{multipart}\n			and not saw_content_type\n			and not( context{boundary} == null ) ) {\n			self._append_header(\n				out,\n				"Content-Type",\n				self._generated_content_type(\n					message.body(),\n					context{boundary},\n				),\n			);\n		}\n\n		_mail_serialize_append_text( out, newline, "newline" );\n		_mail_serialize_append_binary(\n			out,\n			self._serialize_body( message.body(), context{boundary} ),\n		);\n\n		return _bytes_to_binary(out);\n	}\n}\n\nfunction _mail_send_serialize_body ( message ) {\n	return ( new Serializer() ).serialize_body(message);\n}\n`;\n        virtualFiles["/modules/std/data/xml/escape.zzm"] = `=encoding utf8\n\n=head1 NAME\n\nstd/data/xml/escape - XML entity escaping helpers.\n\n=head1 SYNOPSIS\n\n  from std/data/xml/escape import\n    escape_xml, unescape_xml;\n\n  let escaped := escape_xml(\n    "<tea attr=\\\\"hot\\\\">& \'biscuits\'</tea>"\n  );\n  let text := unescape_xml(\n    "&lt;tea&gt;&#x41;&#65;&lt;/tea&gt;"\n  );\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module provides lightweight XML entity\nescaping and unescaping helpers.\n\n=head1 EXPORTS\n\n=head2 Functions\n\n=over\n\n=item C<< escape_xml(value) >>\n\nParameters: C<value> is any value. Returns: C<String>. Escapes XML\nspecial characters C<&>, C<< < >>, C<< > >>, C<">, and C<\'>.\n\n=item C<< unescape_xml(value) >>\n\nParameters: C<value> is any value. Returns: C<String>. Unescapes XML\nnamed entities C<&lt;>, C<&gt;>, C<&quot;>, C<&apos;>, and C<&amp;>.\n\nAlso decodes numeric entities in decimal and hexadecimal\nforms, such as C<&#65;> and C<&#x41;>.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/data/xml/escape >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/string import substr, replace, sprint, index;\n\nfunction escape_xml ( value ) {\n	let out := value \\u2261 null ? "" : "" _ value;\n	out := replace( out, "&", "&amp;", "g" );\n	out := replace( out, "<", "&lt;", "g" );\n	out := replace( out, ">", "&gt;", "g" );\n	out := replace( out, "\\\\"", "&quot;", "g" );\n	out := replace( out, "\'", "&apos;", "g" );\n	return out;\n}\n\nfunction _hex_to_number ( String digits ) {\n	let out := 0;\n	let i := 0;\n	let n := length digits;\n\n	while ( i < n ) {\n		let ch := substr( digits, i, 1 );\n		let val := 0;\n\n		if ( ch ~ /[0-9]/ ) {\n			val := 0 + ch;\n		}\n		else {\n			let lower := lc(ch);\n			val := 10 + index( "abcdef", lower );\n		}\n\n		out := out * 16 + val;\n		i++;\n	}\n\n	return out;\n}\n\nfunction _decode_numeric_xml_entities ( text ) {\n	let out := "";\n	let i := 0;\n	let n := length text;\n\n	while ( i < n ) {\n		let ch := substr( text, i, 1 );\n		if ( ch \\u2261 "&" and i + 2 < n and substr( text, i, 2 ) \\u2261 "&#" ) {\n			let j := i + 2;\n			let hex := false;\n\n			if ( j < n ) {\n				let mark := substr( text, j, 1 );\n				if ( mark \\u2261 "x" or mark \\u2261 "X" ) {\n					hex := true;\n					j++;\n				}\n			}\n\n			let digits := "";\n			while ( j < n ) {\n				let d := substr( text, j, 1 );\n				last if d \\u2261 ";";\n\n				if ( hex ) {\n					last unless d ~ /[0-9A-Fa-f]/;\n				}\n				else {\n					last unless d ~ /[0-9]/;\n				}\n\n				digits _= d;\n				j++;\n			}\n\n			if ( digits \\u2262 "" and j < n and substr( text, j, 1 ) \\u2261 ";" ) {\n				let code := hex\n					? _hex_to_number( digits )\n					: 0 + digits;\n				out _= sprint( "%c", code );\n				i := j + 1;\n				next;\n			}\n		}\n\n		out _= ch;\n		i++;\n	}\n\n	return out;\n}\n\nfunction unescape_xml ( value ) {\n	let out := value \\u2261 null ? "" : "" _ value;\n	out := _decode_numeric_xml_entities( out );\n	out := replace( out, "&lt;", "<", "g" );\n	out := replace( out, "&gt;", ">", "g" );\n	out := replace( out, "&quot;", "\\\\"", "g" );\n	out := replace( out, "&apos;", "\'", "g" );\n	out := replace( out, "&amp;", "&", "g" );\n	return out;\n}\n`;\n        virtualFiles["/modules/std/path/simple.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/path/simple - Tiny JSONPath/XPath-like traversal helper.\\n\\n=head1 SYNOPSIS\\n\\n  from std/path/simple import SimplePath;\\n\\n  let data := {\\n    store: {\\n      books: [\\n        { author: "Nigel Rees" },\\n        { author: "J. R. R. Tolkien" },\\n      ],\\n    },\\n  };\\n\\n  let p := new SimplePath( path: "store.books[*].author" );\\n  for ( let name in p.query(data) ) {\\n    say name;\\n  }\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nC<SimplePath> implements only a tiny subset of path traversal:\\n\\n=over\\n\\n=item * C<.something>\\n\\nDict/PairList lookup by key.\\n\\n=item * C<.*>\\n\\nDict/PairList wildcard that yields all values.\\n\\n=item * C<[1]>\\n\\nArray lookup by numeric index.\\n\\n=item * C<[-1]>\\n\\nNegative indexes count from the end of arrays.\\n\\n=item * C<[*]>\\n\\nArray/Bag/Set wildcard that yields all items.\\n\\n=back\\n\\nNo other syntax is supported.\\n\\nThe public API intentionally mirrors key C<std/path/z> methods:\\nC<get>, C<select>, C<query>, C<first>, C<exists>,\\nC<expression>, C<assign_first>, C<assign_all>, C<assign_maybe>,\\nC<ref_first>, C<ref_all>, and C<ref_maybe>.\\n\\nThe path operators C<@>, C<@@>, and C<@?> can be set to use this module\\nin a lexical scope:\\n\\n  from std/path/simple import SimplePath;\\n  SimplePath.use();\\n\\n=head1 EXPORTS\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<< SimplePath({ path: String }) >>\\n\\nConstructs a simple path selector. Returns: C<SimplePath>.\\n\\n=over\\n\\n=item C<< SimplePath.use() >>\\n\\nParameters: none. Returns: C<null>. Makes this path class the lexical\\nimplementation for C<@>, C<@@>, and C<@?>.\\n\\n=item C<< path.expression() >>\\n\\nParameters: none. Returns: C<String>. Returns the original path\\nexpression.\\n\\n=item C<< path.get(value) >>, C<< path.select(value) >>, C<< path.query(value) >>\\n\\nParameters: C<value> is the query root. Returns: C<Array>. Evaluates the\\npath and returns selected values.\\n\\n=item C<< path.first(value, fallback) >>\\n\\nParameters: C<value> is the query root and C<fallback> is returned when\\nthere is no match. Returns: value. Returns the first selected value.\\n\\n=item C<< path.exists(value) >>\\n\\nParameters: C<value> is the query root. Returns: C<Boolean>. Returns\\ntrue when the path selects at least one value.\\n\\n=item C<< path.assign_first(target, value, op := ":=", weak := false) >>\\n\\nParameters: C<target> is the query root, C<value> is the assignment\\nvalue, C<op> is an assignment operator, and C<weak> is accepted for path\\nAPI compatibility. Returns: value. Updates the first selected location.\\n\\n=item C<< path.assign_all(target, value, op := ":=", weak := false) >>\\n\\nParameters: same as C<assign_first>. Returns: value. Updates every\\nselected location.\\n\\n=item C<< path.assign_maybe(target, value, op := ":=", weak := false) >>\\n\\nParameters: same as C<assign_first>. Returns: C<Boolean>. Updates the\\nfirst selected location when one exists.\\n\\n=item C<< path.ref_first(target) >>\\n\\nParameters: C<target> is the query root. Returns: C<Function>. Returns a\\nreference-like getter/setter for the first selected location.\\n\\n=item C<< path.ref_all(target) >>\\n\\nParameters: C<target> is the query root. Returns: C<Array>. Returns\\nreference-like getter/setters for all selected locations.\\n\\n=item C<< path.ref_maybe(target) >>\\n\\nParameters: C<target> is the query root. Returns: C<Function> or\\nC<null>. Returns a reference-like getter/setter for the first selected\\nlocation when one exists.\\n\\n=back\\n\\n=back\\n\\n=cut\\n\\nfrom std/string import substr;\\n\\n\\nclass SimplePath {\\n	let String path;\\n	let Array _steps := [];\\n\\n	static method use () {\\n		from std/internals import setupperprop;\\n		setupperprop( 1, "paths", self );\\n	}\\n\\n	method __build__ () {\\n		_steps := self._parse(path);\\n	}\\n\\n	method expression () {\\n		return path;\\n	}\\n\\n	method _parse ( String raw ) {\\n		let text := raw;\\n		let steps := [];\\n		let i := 0;\\n\\n		while ( i < length text ) {\\n			let ch := substr( text, i, 1 );\\n			if ( ch \\u2261 "." ) {\\n				i++;\\n				die "SimplePath parse error: expected name or * after \\\'.\\\'"\\n					if i >= length text;\\n				let after_dot := substr( text, i, 1 );\\n				if ( after_dot \\u2261 "*" ) {\\n					steps.push( { kind: "dict_wildcard" } );\\n					i++;\\n					next;\\n				}\\n				let start := i;\\n				while ( i < length text ) {\\n					let c := substr( text, i, 1 );\\n					last if c \\u2261 "." or c \\u2261 "[" or c \\u2261 "]";\\n					i++;\\n				}\\n				let key := substr( text, start, i - start );\\n				die "SimplePath parse error: empty key"\\n					if key \\u2261 "";\\n				steps.push( { kind: "key", value: key } );\\n				next;\\n			}\\n\\n			if ( ch \\u2261 "[" ) {\\n				let close := i + 1;\\n				while ( close < length text and substr( text, close, 1 ) \\u2262 "]" ) {\\n					close++;\\n				}\\n				die "SimplePath parse error: missing closing \\\']\\\'"\\n					if close >= length text;\\n				let inner := substr( text, i + 1, close - i - 1 );\\n				if ( inner \\u2261 "*" ) {\\n					steps.push( { kind: "list_wildcard" } );\\n				}\\n				else if ( inner ~ /^-?[0-9]+$/ ) {\\n					steps.push( { kind: "index", value: int(inner) } );\\n				}\\n				else {\\n					die `SimplePath parse error: unsupported bracket token \\\'[${inner}]\\\'`;\\n				}\\n				i := close + 1;\\n				next;\\n			}\\n\\n			let start := i;\\n			while ( i < length text ) {\\n				let c := substr( text, i, 1 );\\n				last if c \\u2261 "." or c \\u2261 "[" or c \\u2261 "]";\\n				i++;\\n			}\\n			let key := substr( text, start, i - start );\\n			die `SimplePath parse error: unexpected token \\\'${ch}\\\'`\\n				if key \\u2261 "";\\n			steps.push( { kind: "key", value: key } );\\n		}\\n\\n		return steps;\\n	}\\n\\n	method _node ( value, parent, key ) {\\n		return {\\n			value: value,\\n			parent: parent,\\n			key: key,\\n		};\\n	}\\n\\n	method _evaluate_nodes ( value ) {\\n		let current := [ self._node( value, null, null ) ];\\n\\n		for ( let step in _steps ) {\\n			let next_nodes := [];\\n\\n			for ( let node in current ) {\\n				let v := node{value};\\n\\n				if ( step{kind} \\u2261 "key" ) {\\n					if ( v instanceof Dict and v.exists( step{value} ) ) {\\n						next_nodes.push( self._node( v.get( step{value} ), node, step{value} ) );\\n					}\\n					else if ( v instanceof PairList ) {\\n						for ( let item in v.get_all( step{value} ) ) {\\n							next_nodes.push( self._node( item, node, step{value} ) );\\n						}\\n					}\\n					next;\\n				}\\n\\n				if ( step{kind} \\u2261 "dict_wildcard" ) {\\n					if ( v instanceof Dict ) {\\n						for ( let k in v.keys() ) {\\n							next_nodes.push( self._node( v.get(k), node, k ) );\\n						}\\n					}\\n					else if ( v instanceof PairList ) {\\n						for ( let pair in v.to_Array() ) {\\n							next_nodes.push( self._node( pair.value, node, pair.key ) );\\n						}\\n					}\\n					next;\\n				}\\n\\n				if ( step{kind} \\u2261 "index" ) {\\n					if ( v instanceof Array ) {\\n						let idx := step{value};\\n						if ( idx < 0 ) {\\n							idx := v.length() + idx;\\n						}\\n						if ( idx >= 0 and idx < v.length() ) {\\n							next_nodes.push( self._node( v[idx], node, idx ) );\\n						}\\n					}\\n					next;\\n				}\\n\\n				if ( step{kind} \\u2261 "list_wildcard" ) {\\n					if ( v instanceof Array ) {\\n						let i := 0;\\n						while ( i < v.length() ) {\\n							next_nodes.push( self._node( v[i], node, i ) );\\n							i++;\\n						}\\n					}\\n					else if ( v instanceof Bag or v instanceof Set ) {\\n						for ( let item in v.to_Array() ) {\\n							next_nodes.push( self._node( item, node, "*" ) );\\n						}\\n					}\\n					next;\\n				}\\n			}\\n\\n			current := next_nodes;\\n		}\\n\\n		return current;\\n	}\\n\\n	method _evaluate ( value ) {\\n		return self._evaluate_nodes(value).map( fn n -> n{value} );\\n	}\\n\\n	method get ( value ) {\\n		return self._evaluate(value);\\n	}\\n\\n	method select ( value ) {\\n		return self._evaluate(value);\\n	}\\n\\n	method query ( value ) {\\n		return self._evaluate(value);\\n	}\\n\\n	method first ( value, fallback ) {\\n		let out := self._evaluate(value);\\n		return out.length() = 0 ? fallback : out[0];\\n	}\\n\\n	method exists ( value ) {\\n		return self._evaluate(value).length() > 0;\\n	}\\n\\n	method _assign_node ( Dict node, value ) {\\n		let parent := node{parent};\\n		die "SimplePath assignment target has no parent node"\\n			if parent \\u2261 null;\\n\\n		let container := parent{value};\\n		let key := node{key};\\n\\n		if ( container instanceof Array ) {\\n			die "SimplePath assignment expects numeric array index"\\n				if not( key instanceof Number );\\n			container[key] := value;\\n			return value;\\n		}\\n\\n		if ( container instanceof Dict ) {\\n			die "SimplePath assignment expects string dict key"\\n				if not( key instanceof String );\\n			container{(key)} := value;\\n			return value;\\n		}\\n\\n		if ( container instanceof PairList ) {\\n			die "SimplePath assignment expects string pairlist key"\\n				if not( key instanceof String );\\n			container.set( key, value );\\n			return value;\\n		}\\n\\n		die `SimplePath assignment target container \\\'${typeof container}\\\' is not assignable`;\\n	}\\n\\n	method _ref_for_node ( Dict node ) {\\n		let parent := node{parent};\\n		die "SimplePath assignment target has no parent node"\\n			if parent \\u2261 null;\\n\\n		let container := parent{value};\\n		let key := node{key};\\n\\n		if ( container instanceof Array ) {\\n			die "SimplePath assignment expects numeric array index"\\n				if not( key instanceof Number );\\n			return \\\\ container[key];\\n		}\\n\\n		if ( container instanceof Dict ) {\\n			die "SimplePath assignment expects string dict key"\\n				if not( key instanceof String );\\n			return \\\\ container{(key)};\\n		}\\n\\n		if ( container instanceof PairList ) {\\n			die "SimplePath assignment expects string pairlist key"\\n				if not( key instanceof String );\\n			return \\\\ container{(key)};\\n		}\\n\\n		die `SimplePath assignment target container \\\'${typeof container}\\\' is not assignable`;\\n	}\\n\\n	method _apply_assignment_ref ( ref, value, op := ":=", weak := false ) {\\n		die "SimplePath weak assignment is not supported"\\n			if weak;\\n\\n		if ( op \\u2261 ":=" ) {\\n			return ref(value);\\n		}\\n\\n		let current := ref();\\n\\n		if ( op \\u2261 "+=" ) {\\n			current += value;\\n		}\\n		else if ( op \\u2261 "-=" ) {\\n			current -= value;\\n		}\\n		else if ( op \\u2261 "*=" or op \\u2261 "\\xD7=" ) {\\n			current *= value;\\n		}\\n		else if ( op \\u2261 "/=" or op \\u2261 "\\xF7=" ) {\\n			current /= value;\\n		}\\n		else if ( op \\u2261 "**=" ) {\\n			current **= value;\\n		}\\n		else if ( op \\u2261 "_=" ) {\\n			current _= value;\\n		}\\n		else if ( op \\u2261 "?:=" ) {\\n			current ?:= value;\\n		}\\n		else if ( op \\u2261 "~=" ) {\\n			current ~= value[0] -> value[1](m);\\n		}\\n		else {\\n			die `Unsupported path assignment operator \\\'${op}\\\'`;\\n		}\\n\\n		ref(current);\\n		return current;\\n	}\\n\\n	method _assign_all_result ( value, op, last_result ) {\\n		return op \\u2261 "~=" ? last_result : value;\\n	}\\n\\n	method assign_first ( target, value, op := ":=", weak := false ) {\\n		let nodes := self._evaluate_nodes(target);\\n		die "SimplePath assignment found no matches"\\n			if nodes.length() \\u2261 0;\\n		return self._apply_assignment_ref(\\n			self._ref_for_node( nodes[0] ),\\n			value,\\n			op,\\n			weak,\\n		);\\n	}\\n\\n	method assign_all ( target, value, op := ":=", weak := false ) {\\n		let nodes := self._evaluate_nodes(target);\\n		if ( nodes.length() \\u2261 0 ) {\\n			return self._assign_all_result( value, op, value );\\n		}\\n\\n		let i := 0;\\n		let last_result := value;\\n		while ( i < nodes.length() ) {\\n			last_result := self._apply_assignment_ref(\\n				self._ref_for_node( nodes[i] ),\\n				value,\\n				op,\\n				weak,\\n			);\\n			i++;\\n		}\\n\\n		return self._assign_all_result( value, op, last_result );\\n	}\\n\\n	method assign_maybe ( target, value, op := ":=", weak := false ) {\\n		let nodes := self._evaluate_nodes(target);\\n		if ( nodes.length() \\u2261 0 ) {\\n			return false;\\n		}\\n\\n		self._apply_assignment_ref(\\n			self._ref_for_node( nodes[0] ),\\n			value,\\n			op,\\n			weak,\\n		);\\n		return true;\\n	}\\n\\n	method ref_first ( target ) {\\n		let nodes := self._evaluate_nodes(target);\\n		die "SimplePath assignment found no matches"\\n			if nodes.length() \\u2261 0;\\n		return self._ref_for_node( nodes[0] );\\n	}\\n\\n	method ref_all ( target ) {\\n		let nodes := self._evaluate_nodes(target);\\n		let out := [];\\n		for ( let node in nodes ) {\\n			out.push( self._ref_for_node(node) );\\n		}\\n		return out;\\n	}\\n\\n	method ref_maybe ( target ) {\\n		let nodes := self._evaluate_nodes(target);\\n		return nodes.length() \\u2261 0 ? null : self._ref_for_node( nodes[0] );\\n	}\\n}\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/path/simple >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\';\n        virtualFiles["/modules/std/path/z.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/path/z - Pure Zuzu implementation of ZPath selectors.\\n\\n=head1 SYNOPSIS\\n\\n  from std/path/z import ZPath;\\n  from std/time import Time;\\n\\n  let data := {\\n    users: [\\n      { name: "Ada", age: 32, updated: new Time() },\\n      { name: "Bob", age: 27 },\\n    ],\\n  };\\n\\n  let names := query( data, "/users/*/name" );\\n  let zp := new ZPath( path: "/users/#0/name" );\\n  say( zp.first( data, "n/a" ) );\\n  say( exists( data, "/users/#9/name" ) );\\n  say( first( data, "/users/#0/updated/@year" ) );\\n  say( zp.assign_first( data, "Adele" ) );\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nNative (pure-Zuzu) path traversal for structured values.\\n\\n=head1 EXPORTS\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<< ZPath({ path: String, ast? }) >>\\n\\nConstructs a compiled ZPath selector. Returns: C<ZPath>.\\n\\n=over\\n\\n=item C<< ZPath.use() >>\\n\\nParameters: none. Returns: C<null>. Makes this path class the lexical\\nimplementation for C<@>, C<@@>, and C<@?>.\\n\\n=item C<< path.get_evaluator() >>\\n\\nParameters: none. Returns: C<Evaluator>. Returns the evaluator used for\\nthis path.\\n\\n=item C<< path.evaluate(raw, meta := {}) >>\\n\\nParameters: C<raw> is the query root and C<meta> is optional evaluation\\nmetadata. Returns: C<Array>. Evaluates the path and returns selected\\nnodes.\\n\\n=item C<< path.get(raw) >>, C<< path.select(raw) >>, C<< path.query(raw) >>\\n\\nParameters: C<raw> is the query root. Returns: C<Array>. Evaluates the\\npath and returns selected primitive values.\\n\\n=item C<< path.first(raw, fallback?) >>\\n\\nParameters: C<raw> is the query root and C<fallback> is optional.\\nReturns: value. Returns the first selected value or C<fallback>/C<null>.\\n\\n=item C<< path.exists(raw) >>\\n\\nParameters: C<raw> is the query root. Returns: C<Boolean>. Returns true\\nwhen the path selects at least one value.\\n\\n=item C<< path.assign_first(raw, value, op := ":=", weak := false) >>\\n\\nParameters: C<raw> is the query root, C<value> is the assignment value,\\nC<op> is an assignment operator, and C<weak> requests weak assignment.\\nReturns: value. Updates the first selected node or throws if none match.\\n\\n=item C<< path.assign_all(raw, value, op := ":=", weak := false) >>\\n\\nParameters: same as C<assign_first>. Returns: value. Updates every\\nselected node.\\n\\n=item C<< path.assign_maybe(raw, value, op := ":=", weak := false) >>\\n\\nParameters: same as C<assign_first>. Returns: C<Boolean>. Updates the\\nfirst selected node when one exists.\\n\\n=item C<< path.ref_first(raw) >>\\n\\nParameters: C<raw> is the query root. Returns: C<Function>. Returns a\\nreference-like getter/setter for the first selected node.\\n\\n=item C<< path.ref_all(raw) >>\\n\\nParameters: C<raw> is the query root. Returns: C<Array>. Returns\\nreference-like getter/setters for all selected nodes.\\n\\n=item C<< path.ref_maybe(raw) >>\\n\\nParameters: C<raw> is the query root. Returns: C<Function> or C<null>.\\nReturns a reference-like getter/setter for the first selected node when\\none exists.\\n\\n=back\\n\\n=back\\n\\n=head1 USE WITH PATH OPERATORS\\n\\nThe path operators C<@>, C<@@>, and C<@?> can be set to use this module\\nin a lexical scope.\\n\\n  from std/path/z import ZPath;\\n\\n  function find_usernames (data) {\\n    ZPath.use();\\n    return data @@ "/users/*/name";\\n  }\\n\\nHowever, for repeatedly used paths it may be more efficient to compile the\\npath once and use many times:\\n\\n  let _usernames_zpath;\\n  function find_usernames (data) {\\n    from std/path/z import ZPath;\\n    _usernames_zpath ?:= new ZPath( path: "/users/*/name" );\\n    return data @@ _usernames_zpath;\\n  }\\n\\n=head1 SUPPORTED TYPES\\n\\n=over\\n\\n=item B<Null>, B<Boolean>, B<Number>, B<String>, B<BinaryString>, B<Regexp>\\n\\nTreated as terminal nodes. These objects cannot have child objects.\\n\\n=item B<Array>\\n\\nArray items can be indexed by number.\\n\\n=item B<Bag>, B<Set>\\n\\nItems cannot be indexed by number, but can be returned by "*".\\n\\n=item B<Dict>\\n\\nValues are named by their key.\\n\\n=item B<PairList>\\n\\nPairs can be indexed by number, named by their key, or use a combination of\\nboth.\\n\\n  {{ foo: 11, bar: -1, foo: 22, foo: 33 }}\\n\\nC<< /#2 >> (0-based index) will retrieve C<< foo: 22 >>.\\nC<< /foo >> will retrieve C<< foo: 11 >>, C<< foo: 22 >>, and C<< foo: 33 >>.\\nC<< /foo#2 >> (0-based index on just values with key "foo") will retrieve C<< foo: 33 >>.\\n\\nNote that rather than just retrieving the value, a Pair object is retrieved.\\nThe selected Pair exposes C<< @key >> and C<< @value >> attributes. Path\\nassignment to a selected Pair, or to its C<< @value >> attribute, replaces\\nthat pair entry\\\'s value while preserving pair order and duplicate keys.\\n\\n=item B<< Pair >>\\n\\nPair objects do not have child objects but do have C<< @key >> and\\nC<< @value >> attributes.\\n\\n  let pairlist := {{ foo: 11, bar: -1, foo: 22, foo: 33 }};\\n  say( first( pairlist, "/#2/@key" ) );     // "foo"\\n  say( first( pairlist, "/#2/@value" ) );   // 22\\n\\n=item B<< Time >>\\n\\nTime is treated as a terminal node with attributes C<< @year >>,\\nC<< @month >>, C<< @day >>, C<< @hour >>, C<< @min >>, and C<< @sec >>.\\n\\nSee C<< std/time >>.\\n\\n=item B<< Path >>\\n\\nPaths representing files are treated as terminal nodes with attributes\\ncorresponding to the values from the C<stat> system call: C<< @dev >>,\\nC<< @ino >>, C<< @mode >>, C<< @nlink >>, C<< @uid >>, C<< @gid >>,\\nC<< @rdev >>, C<< @size >>, C<< @atime >>, C<< @mtime >>, C<< @ctime >>,\\nC<< @blksize >>, and C<< @blocks >>.\\n\\nSee C<< std/io >>.\\n\\n=item B<< XMLDocument >>, B<< XMLNode >>, etc.\\n\\nAre treated roughly how the ZPath specification suggests.\\n\\n  /html/body/table/tbody/tr     // all rows in the tbody\\n  /html/body/table/tbody/tr#0   // the first row in the tbody\\n  /html/body/table/tbody/#0     // the child element in the tbody\\n  /html/body/table[@id]         // all tables that have an id attribute\\n\\nSee C<< std/data/xml >>.\\n\\n=back\\n\\n=head1 SEE ALSO\\n\\nSpecification: L<https://zpath.me>.\\n\\nZPath specification: L<https://zpath.me>.\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/path/z >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/path/z/parser import Parser;\\nfrom std/path/z/evaluate import Evaluator;\\nfrom std/path/z/context import Ctx;\\n\\nlet _cache;\\ndo {\\n	from std/cache/lru try import Cache;\\n	if ( Cache ) {\\n		_cache := new Cache( capacity: 16 );\\n	}\\n};\\n\\nclass ZPath {\\n	let String path;\\n	let ast;\\n	let ev;\\n\\n	static method use () {\\n		from std/internals import setupperprop;\\n		setupperprop( 1, "paths", self );\\n	}\\n\\n	method __build__ () {\\n		ev := self.get_evaluator;\\n		const p := new Parser( allowed_operators: ev.operator_definitions() );\\n		ast ?:= _cache\\n			? _cache.get( path, fn x \\u2192 p.parse_top_level_terms(x) )\\n			: p.parse_top_level_terms(path);\\n	}\\n\\n	method get_evaluator () {\\n		return new Evaluator();\\n	}\\n\\n	method evaluate ( raw, meta := {} ) {\\n\\n		meta.set( "level", 0 ) unless meta.defined( "level" );\\n		const ctx := new Ctx(\\n			root: raw,\\n			nodeset: meta.get( "nodeset", null ),\\n			parentset: meta.get( "parentset", null ),\\n			meta: meta,\\n		);\\n\\n		const short_circuit := ( meta.get( "want", "all" ) in [ "first", "exists" ] );\\n\\n		let results := [];\\n		for ( let term in ast ) {\\n			for ( let node in ev.eval_expr( term, ctx ) ) {\\n				let next_node := ev.maybe_apply_action( node, ctx );\\n				results.push(next_node);\\n				return results if short_circuit;\\n			}\\n		}\\n\\n		return results;\\n	}\\n\\n	method get ( raw ) {\\n		return self.evaluate(raw).map( fn r \\u2192 r.primitive_value );\\n	}\\n\\n	method select ( raw ) {\\n		return self.evaluate(raw).map( fn r \\u2192 r.primitive_value );\\n	}\\n\\n	method query ( raw ) {\\n		return self.evaluate(raw).map( fn r \\u2192 r.primitive_value );\\n	}\\n\\n	method first ( raw, fallback? ) {\\n		let got := self.evaluate( raw, { want: "first" } );\\n		return got.empty ? fallback : got[0].primitive_value;\\n	}\\n\\n	method exists ( raw ) {\\n		let got := self.evaluate( raw, { want: "exists" } );\\n		return not got.empty;\\n	}\\n\\n	method _apply_assignment_ref ( ref, value, op := ":=", weak := false ) {\\n		if ( op \\u2261 ":=" ) {\\n			return weak ? ref( value, true ) : ref(value);\\n		}\\n\\n		let current := ref();\\n\\n		if ( op \\u2261 "+=" ) {\\n			current += value;\\n		}\\n		else if ( op \\u2261 "-=" ) {\\n			current -= value;\\n		}\\n		else if ( op \\u2261 "*=" or op \\u2261 "\\xD7=" ) {\\n			current *= value;\\n		}\\n		else if ( op \\u2261 "/=" or op \\u2261 "\\xF7=" ) {\\n			current /= value;\\n		}\\n		else if ( op \\u2261 "**=" ) {\\n			current **= value;\\n		}\\n		else if ( op \\u2261 "_=" ) {\\n			current _= value;\\n		}\\n		else if ( op \\u2261 "?:=" ) {\\n			current ?:= value;\\n		}\\n		else if ( op \\u2261 "~=" ) {\\n			current ~= value[0] -> value[1](m);\\n		}\\n		else {\\n			die `Unsupported path assignment operator \\\'${op}\\\'`;\\n		}\\n\\n		ref(current);\\n		return current;\\n	}\\n\\n	method _assign_all_result ( value, op, last_result ) {\\n		return op \\u2261 "~=" ? last_result : value;\\n	}\\n\\n	method assign_first ( raw, value, op := ":=", weak := false ) {\\n		let got := self.evaluate( raw, { want: "first" } );\\n		die "Path assignment (@) found no matches" if got.empty;\\n		return self._apply_assignment_ref(\\n			got[0].ref(),\\n			value,\\n			op,\\n			weak,\\n		);\\n	}\\n\\n	method assign_all ( raw, value, op := ":=", weak := false ) {\\n		let got := self.evaluate(raw);\\n		if ( got.empty ) {\\n			return self._assign_all_result( value, op, value );\\n		}\\n\\n		let last_result := value;\\n		for ( let node in got ) {\\n			last_result := self._apply_assignment_ref(\\n				node.ref(),\\n				value,\\n				op,\\n				weak,\\n			);\\n		}\\n\\n		return self._assign_all_result( value, op, last_result );\\n	}\\n\\n	method assign_maybe ( raw, value, op := ":=", weak := false ) {\\n		let got := self.evaluate( raw, { want: "first" } );\\n		if ( got.empty ) {\\n			return false;\\n		}\\n\\n		self._apply_assignment_ref( got[0].ref(), value, op, weak );\\n		return true;\\n	}\\n\\n	method ref_first ( raw ) {\\n		let got := self.evaluate( raw, { want: "first" } );\\n		die "Path assignment (@) found no matches" if got.empty;\\n		return got[0].ref();\\n	}\\n\\n	method ref_all ( raw ) {\\n		return self.evaluate(raw).map( fn n \\u2192 n.ref );\\n	}\\n\\n	method ref_maybe ( raw ) {\\n		let got := self.evaluate( raw, { want: "first" } );\\n		return got.empty ? null : got[0].ref();\\n	}\\n}\\n\';\n        virtualFiles["/modules/std/path/z/context.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/path/z/context - Evaluation context used by std/path/z.\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nThis module provides the pure-Zuzu evaluation context used by ZPath.\\n\\n=head1 EXPORTS\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<< Ctx({ root, nodeset?, parentset?, meta? }) >>\\n\\nConstructs a ZPath evaluation context. Returns: C<Ctx>. Wraps C<root>\\nas a C<std/path/z/node> C<Node> and stores the active node sets.\\n\\n=over\\n\\n=item C<< ctx.with_nodeset(ns, ps) >>\\n\\nParameters: C<ns> is the next node set and C<ps> is the parent set.\\nReturns: C<Ctx>. Returns a copy of the context with different node\\nsets.\\n\\n=item C<< ctx.nested(extras?) >>\\n\\nParameters: C<extras> is optional metadata. Returns: C<Ctx>. Returns a\\nnested context with incremented metadata level.\\n\\n=item C<< ctx.root() >>\\n\\nParameters: none. Returns: C<Node>. Returns the root node.\\n\\n=item C<< ctx.nodeset() >>\\n\\nParameters: none. Returns: C<Array>. Returns the current node set.\\n\\n=item C<< ctx.parentset() >>\\n\\nParameters: none. Returns: C<Array> or C<null>. Returns the parent node\\nset.\\n\\n=item C<< ctx.meta() >>\\n\\nParameters: none. Returns: C<Dict>. Returns context metadata.\\n\\n=back\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/path/z/context >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/path/z/node import Node;\\n\\nclass Ctx {\\n	let root := null;\\n	let nodeset := null;\\n	let parentset := null;\\n	let meta := null;\\n\\n	method __build__ () {\\n		if ( not ( root instanceof Node ) ) {\\n			let root_obj := root;\\n			let node_type := null;\\n\\n			try {\\n				node_type := int( "" _ root_obj.nodeType() );\\n			}\\n			catch {\\n			}\\n\\n			let xml_document := node_type = 9;\\n			if ( not xml_document and root_obj can documentElement ) {\\n				try {\\n					root_obj.documentElement();\\n					xml_document := true;\\n				}\\n				catch {\\n				}\\n			}\\n\\n			if ( xml_document ) {\\n				try {\\n					let de := root_obj.documentElement();\\n					root_obj := de if de \\u2262 null;\\n				}\\n				catch {\\n				}\\n			}\\n\\n			root := Node.wrap( root_obj );\\n		}\\n\\n		nodeset ?:= [ root ];\\n		meta ?:= { level: 0 };\\n	}\\n\\n	method with_nodeset ( ns, ps ) {\\n		return new Ctx(\\n			root: root,\\n			nodeset: ns,\\n			parentset: ps,\\n			meta: meta,\\n		);\\n	}\\n\\n	method nested ( extras? ) {\\n		// Extras is optional metadata; an empty map is still a value.\\n		let extra_meta := extras ?: {};\\n\\n		let next_meta := {\\n			level: meta.get( "level", 0 ) + 1,\\n		};\\n\\n		for ( let pair in extra_meta.enumerate ) {\\n			next_meta.add( pair );\\n		}\\n\\n		return new Ctx(\\n			root: root,\\n			nodeset: nodeset,\\n			parentset: parentset,\\n			meta: next_meta,\\n		);\\n	}\\n\\n	method root () { return root; }\\n	method nodeset () { return nodeset; }\\n	method parentset () { return parentset; }\\n	method meta () { return meta; }\\n}\\n\';\n        virtualFiles["/modules/std/path/z/evaluate.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/path/z/evaluate - Pure Zuzu evaluator for ZPath expressions.\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nThis module provides the pure-Zuzu evaluator used by ZPath.\\n\\n=head1 EXPORTS\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<Evaluator>\\n\\nPure-Zuzu evaluator for parsed ZPath AST values.\\n\\n=over\\n\\n=item C<< evaluator.operator_definitions() >>\\n\\nParameters: none. Returns: C<Array>. Returns the active operator\\ndefinition table.\\n\\n=item C<< evaluator.function_definitions() >>\\n\\nParameters: none. Returns: C<Array>. Returns the active function\\ndefinition table.\\n\\n=item C<< evaluator.eval_expr_wrap(ast, ctx) >>\\n\\nParameters: C<ast> is an AST node and C<ctx> is a C<Ctx>. Returns:\\nC<Array>. Evaluates with optional debug dumping.\\n\\n=item C<< evaluator.eval_expr(ast, ctx) >>\\n\\nParameters: C<ast> is an AST node and C<ctx> is a C<Ctx>. Returns:\\nC<Array>. Evaluates an expression to a node set.\\n\\n=item C<< evaluator.nested_ctx(ctx, ... PairList extras) >>\\n\\nParameters: C<ctx> is a C<Ctx> or C<null> and C<extras> are metadata.\\nReturns: C<Ctx> or C<null>. Creates a nested evaluation context.\\n\\n=item C<< evaluator.eval_binop(ast, ctx) >>, C<< evaluator.eval_unop(ast, ctx) >>\\n\\nParameters: C<ast> is an operator AST node and C<ctx> is a C<Ctx>.\\nReturns: C<Array>. Evaluates a binary or unary operator.\\n\\n=item C<< evaluator.eval_path(path_ast, ctx) >>\\n\\nParameters: C<path_ast> is a path AST node and C<ctx> is a C<Ctx>.\\nReturns: C<Array>. Evaluates a path expression to selected nodes.\\n\\n=item C<< evaluator.maybe_apply_action(node, ctx) >>\\n\\nParameters: C<node> is a C<Node> and C<ctx> is a C<Ctx>. Returns:\\nC<Node>. Applies any pending path action.\\n\\n=item C<< evaluator.eval_fn(fn_ast, ctx) >>\\n\\nParameters: C<fn_ast> is a function-call AST node and C<ctx> is a\\nC<Ctx>. Returns: C<Array>. Evaluates a ZPath function call.\\n\\n=item C<< evaluator.string_replace(string, pattern, replacement) >>\\n\\nParameters: all arguments are strings or regex-like values. Returns:\\nC<String>. Applies ZPath string replacement.\\n\\n=item C<< evaluator.dedup_nodes(nodes) >>\\n\\nParameters: C<nodes> is an array of nodes. Returns: C<Array>. Removes\\nduplicate nodes while preserving order.\\n\\n=item C<< evaluator.truthy(n) >>\\n\\nParameters: C<n> is a node or value. Returns: C<Boolean>. Applies ZPath\\ntruthiness.\\n\\n=item C<< evaluator.to_number(n) >>, C<< evaluator.to_string(n) >>\\n\\nParameters: C<n> is a node or value. Returns: C<Number> or C<String>.\\nCoerces a ZPath value.\\n\\n=item C<< evaluator.equals(a, b) >>\\n\\nParameters: C<a> and C<b> are nodes or values. Returns: C<Boolean>.\\nCompares two ZPath values.\\n\\n=back\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/path/z/evaluate >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/string import replace, index, substr;\\nfrom std/path/z/node import Node;\\nfrom std/path/z/functions import STANDARD_FUNCTIONS;\\nfrom std/path/z/operators import STANDARD_OPERATORS;\\n\\nlet _do_dump := false;\\n\\nclass Evaluator {\\n	let _operator_definitions;\\n	let _function_definitions;\\n\\n	let \\u03B5 := 0.000000001;\\n\\n	method operator_definitions () {\\n		_operator_definitions ?:= STANDARD_OPERATORS;\\n		return _operator_definitions;\\n	}\\n\\n	method function_definitions () {\\n		_function_definitions ?:= STANDARD_FUNCTIONS;\\n		return _function_definitions;\\n	}\\n\\n	method eval_expr_wrap ( ast, ctx ) {\\n		from std/dump import Dumper;\\n		let got := self._real_eval_expr ( ast, ctx );\\n		say `AST ${Dumper.dump(ast)} CTX ${Dumper.dump(ctx)} \\u21D2 GOT ${Dumper.dump(got)}` if _do_dump;\\n		return got;\\n	}\\n\\n	method eval_expr ( ast, ctx ) {\\n\\n		switch ( ast{t} : eq ) {\\n			case "num":\\n				return [ Node.wrap( ast{v} ) ];\\n			case "str":\\n				return [ Node.wrap( ast{v} ) ];\\n			case "path":\\n				return self.eval_path( ast, ctx );\\n			case "fn":\\n				return self.eval_fn( ast, ctx );\\n			case "un":\\n				return self.eval_unop( ast, ctx );\\n			case "bin":\\n				return self.eval_binop( ast, ctx );\\n			case "ternary":\\n				let c  := self.eval_expr( ast{c}, ctx );\\n				let ab := self.truthy( c.get(0) ) ? "a" : "b";\\n				return self.eval_expr( ast{(ab)}, ctx );\\n			case "elvis":\\n				let left := self.eval_expr( ast{c}, ctx );\\n				let first := left.get( 0, null );\\n				return left if first \\u2262 null and first.primitive_value() \\u2262 null;\\n				return self.eval_expr( ast{b}, ctx );\\n			default:\\n				die "Panic! Unknown AST node type!";\\n		}\\n	}\\n\\n	method nested_ctx ( ctx, ... PairList extras ) {\\n		return null if ctx \\u2261 null;\\n		return ctx.nested( extras );\\n	}\\n\\n	method _hold_parent ( node, parent ) {\\n		if ( node \\u2262 null and parent \\u2262 null ) {\\n			node.hold_parent(parent);\\n		}\\n		return node;\\n	}\\n\\n	method _children ( node ) {\\n		let out := [];\\n		for ( let child in node.children() ) {\\n			out.push( self._hold_parent( child, node ) );\\n		}\\n		return out;\\n	}\\n\\n	method _attributes ( node ) {\\n		let out := [];\\n		for ( let attr in node.attributes() ) {\\n			out.push( self._hold_parent( attr, node ) );\\n		}\\n		return out;\\n	}\\n\\n	method _indexed_child ( node, i ) {\\n		return self._hold_parent( node.indexed_child(i), node );\\n	}\\n\\n	method _named_child ( node, name ) {\\n		return self._hold_parent( node.named_child(name), node );\\n	}\\n\\n	method _named_indexed_child ( node, name, i ) {\\n		return self._hold_parent( node.named_indexed_child( name, i ), node );\\n	}\\n\\n	method eval_binop ( ast, ctx ) {\\n		const op := ast{op};\\n		const op_def := self.operator_definitions().first(\\n			fn x \\u2192 x.get_spelling eq op and x.is_binary()\\n		);\\n		if ( op_def and op_def{f} ) {\\n			const implementation := op_def{f};\\n			return implementation( op_def, self, ast, ctx, ast{l}, ast{r} );\\n		}\\n		return [];\\n	}\\n\\n	method eval_unop ( ast, ctx ) {\\n		const op := ast{op};\\n		const op_def := self.operator_definitions().first(\\n			fn x \\u2192 x.get_spelling eq op and x.is_unary()\\n		);\\n		if ( op_def and op_def{f} ) {\\n			const implementation := op_def{f};\\n			return implementation( op_def, self, ast, ctx, ast{e} );\\n		}\\n		return [];\\n	}\\n\\n	method eval_path ( path_ast, ctx ) {\\n		let current := [];\\n		for ( let n in ctx.nodeset() ) {\\n			current.push(n);\\n		}\\n\\n		let parentset := ctx.parentset();\\n\\n		for ( let seg in path_ast{s} ) {\\n			let next_nodes := [];\\n\\n			if ( seg{k} \\u2261 "root" ) {\\n				next_nodes := [ ctx.root() ];\\n			}\\n			else if ( seg{k} \\u2261 "dot" ) {\\n				next_nodes := current;\\n			}\\n			else if ( seg{k} \\u2261 "parent" ) {\\n				for ( let n in current ) {\\n					let p := n.parent();\\n					if ( p \\u2262 null ) {\\n						next_nodes.push(p);\\n					}\\n				}\\n				next_nodes := self.dedup_nodes(next_nodes);\\n			}\\n			else if ( seg{k} \\u2261 "ancestors" ) {\\n				let anc := [];\\n				for ( let n in current ) {\\n					let p := n.parent();\\n					while ( p \\u2262 null ) {\\n						anc.push(p);\\n						p := p.parent();\\n					}\\n				}\\n				next_nodes := self.dedup_nodes(anc);\\n			}\\n			else if ( seg{k} \\u2261 "star" ) {\\n				let kids := [];\\n				for ( let n in current ) {\\n					for ( let child in self._children(n) ) {\\n						if ( child.type() \\u2262 "attr" ) {\\n							kids.push(child);\\n						}\\n					}\\n				}\\n				next_nodes := self.dedup_nodes(kids);\\n			}\\n			else if ( seg{k} \\u2261 "desc" ) {\\n				let acc := [];\\n				let stack := [];\\n				for ( let n in current ) {\\n					stack.push(n);\\n				}\\n\\n				while ( stack.length() > 0 ) {\\n					let n := stack.shift();\\n					acc.push(n);\\n					for ( let child in self._children(n) ) {\\n						if ( child.type() \\u2262 "attr" ) {\\n							stack.push(child);\\n						}\\n					}\\n				}\\n				next_nodes := self.dedup_nodes(acc);\\n			}\\n			else if ( seg{k} \\u2261 "index" ) {\\n				let idx := seg{i};\\n				let kids := [];\\n				for ( let n in current ) {\\n					let c := self._indexed_child( n, idx );\\n					kids.push(c) if c \\u2262 null;\\n				}\\n				next_nodes := self.dedup_nodes(kids);\\n			}\\n			else if ( seg{k} \\u2261 "fnseg" ) {\\n				let out := [];\\n				for ( let n in current ) {\\n					let seg_ctx := ctx.with_nodeset( [ n ], current );\\n					let fn_ast := { t: "fn", n: seg{n}, a: seg{a} };\\n					let res := self.eval_fn( fn_ast, seg_ctx );\\n					for ( let x in res ) {\\n						out.push(x);\\n					}\\n				}\\n				next_nodes := out;\\n			}\\n			else if ( seg{k} \\u2261 "name" ) {\\n				let name := seg{n};\\n\\n				if ( name ~ /^\\\\@/ ) {\\n					if ( name \\u2261 "@*" ) {\\n						let attrs := [];\\n						for ( let n in current ) {\\n							for ( let a in self._attributes(n) ) {\\n								attrs.push(a);\\n							}\\n						}\\n						next_nodes := self.dedup_nodes(attrs);\\n					}\\n					else {\\n						let attrs := [];\\n						for ( let n in current ) {\\n							for ( let a in self._attributes(n) ) {\\n								if ( a.name() \\u2261 name ) {\\n									attrs.push(a);\\n								}\\n							}\\n						}\\n						next_nodes := self.dedup_nodes(attrs);\\n					}\\n				}\\n				else {\\n					let kids := [];\\n					for ( let n in current ) {\\n						if ( n.can_have_named_indexed_children() ) {\\n							let idx := 0;\\n							while ( true ) {\\n								let c := self._named_indexed_child( n, name, idx );\\n								last if c \\u2261 null;\\n								kids.push(c);\\n								idx++;\\n							}\\n						}\\n						else {\\n							let c := self._named_child( n, name );\\n							kids.push(c) if c \\u2262 null;\\n						}\\n					}\\n					next_nodes := self.dedup_nodes(kids);\\n				}\\n\\n				if ( seg.exists("i") and seg{i} \\u2262 null ) {\\n					let idx := seg{i};\\n					let picked := [];\\n					for ( let n in current ) {\\n						let c := self._named_indexed_child( n, name, idx );\\n						picked.push(c) if c \\u2262 null;\\n					}\\n					next_nodes := self.dedup_nodes(picked);\\n				}\\n			}\\n			else {\\n				die "Unknown path segment kind: " _ seg{k};\\n			}\\n\\n			if ( seg.exists("q") and seg{q}.length() > 0 ) {\\n				for ( let q in seg{q} ) {\\n					if ( q.exists("t") and q{t} \\u2261 "num" and q{v} ~ /^\\\\d+$/ ) {\\n						let idx := 0 + q{v};\\n\\n						if ( next_nodes.length() > 0 and self._node_is_xml(next_nodes[0]) ) {\\n							next_nodes := ( idx \\u2265 0 and idx < next_nodes.length() ) ? [ next_nodes[idx] ] : [];\\n						}\\n						else {\\n							let picked := [];\\n							for ( let node in next_nodes ) {\\n								let ch := self._children(node)\\n									.grep( fn c \\u2192 c.type() \\u2262 "attr" );\\n								if ( idx \\u2265 0 and idx < ch.length() ) {\\n									picked.push( ch[idx] );\\n								}\\n							}\\n							next_nodes := picked;\\n						}\\n\\n						next;\\n					}\\n\\n					let filtered := [];\\n					let i := 0;\\n					while ( i < next_nodes.length() ) {\\n						let node := next_nodes[i];\\n						let ns_ctx := ctx.with_nodeset( next_nodes, current );\\n						let filter_ctx := ns_ctx.with_nodeset( [ node ], next_nodes );\\n						let r := self.eval_expr( q, self.nested_ctx( filter_ctx, want: "exists" ) );\\n\\n						let ok := false;\\n						if ( q.exists("t") and q{t} \\u2261 "path" ) {\\n							ok := r.length() > 0;\\n						}\\n						else {\\n							ok := self.truthy( r.length() > 0 ? r[0] : null );\\n						}\\n\\n						if ( ok ) {\\n							filtered.push(node);\\n						}\\n						i++;\\n					}\\n					next_nodes := filtered;\\n				}\\n			}\\n\\n			parentset := current;\\n			current := next_nodes;\\n		}\\n\\n		return current;\\n	}\\n\\n	method maybe_apply_action ( node, ctx ) {\\n		const meta := ctx.meta();\\n		return node if not meta.exists( "action" );\\n		const action := meta{action};\\n		return node if action \\u2261 null;\\n		return node if not action.exists( "op" );\\n		node.do_action(action);\\n		return node;\\n	}\\n\\n	method eval_fn ( fn_ast, ctx ) {\\n		const name := fn_ast{n};\\n		const fn_def := self.function_definitions().first( fn f \\u2192 f.has_name(name) );\\n		// Function-argument ASTs are null or arrays; empty arrays are values.\\n		return fn_def{f}( fn_def, self, fn_ast, ctx, fn_ast{a} ?: [] ) if fn_def;\\n		return [];\\n	}\\n\\n	method string_replace ( string, pattern, replacement ) {\\n		let text := string \\u2261 null ? "" : "" _ string;\\n		let rep := replacement \\u2261 null ? "" : "" _ replacement;\\n\\n		try {\\n			return replace( text, pattern, rep, "g" );\\n		}\\n		catch {\\n			return replace( text, "" _ pattern, rep, "g" );\\n		}\\n	}\\n\\n	method dedup_nodes ( nodes ) {\\n		let seen := {};\\n		let out := [];\\n		for ( let n in nodes ) {\\n			// Node ids are null or stable identifiers; only null needs anon keys.\\n			let key := n.id ?: ( "anon:" _ out.length() _ ":" _ ( "" _ n.raw() ) );\\n			if ( not seen.exists(key) ) {\\n				seen.set( key, true );\\n				out.push(n);\\n			}\\n		}\\n		return out;\\n	}\\n\\n	method truthy ( n ) {\\n		return false if n \\u2261 null;\\n		let pv := n.primitive_value();\\n		return pv ? true : false;\\n	}\\n\\n	method to_number ( n ) {\\n		return null if n \\u2261 null;\\n		return n.number_value();\\n	}\\n\\n	method to_string ( n ) {\\n		return null if n \\u2261 null;\\n		return n.string_value();\\n	}\\n\\n	method equals ( a, b ) {\\n		return false if a \\u2261 null or b \\u2261 null;\\n\\n		let a_type := a.type();\\n		let b_type := b.type();\\n\\n		if ( b_type eq "null" ) {\\n			return a_type eq "null";\\n		}\\n		if ( a_type eq "null" ) {\\n			return b_type eq "null";\\n		}\\n\\n		if ( a_type eq "boolean" and b_type eq "boolean" ) {\\n			let av := a.primitive_value() ? true : false;\\n			let bv := b.primitive_value() ? true : false;\\n			return av \\u2261 bv;\\n		}\\n\\n		if ( a_type \\u2261 "number" and b_type \\u2261 "number" ) {\\n			let av := a.number_value();\\n			let bv := b.number_value();\\n			return false if av \\u2261 null or bv \\u2261 null;\\n\\n			if ( ( "" _ av ) ~ /\\\\./ or ( "" _ bv ) ~ /\\\\./ ) {\\n				return abs( av - bv ) < \\u03B5;\\n			}\\n\\n			return av = bv;\\n		}\\n\\n		let string_like := [ "string", "text", "attr", "comment", "element" ];\\n		if ( a_type in string_like and b_type in string_like ) {\\n			let av := a.string_value();\\n			let bv := b.string_value();\\n			return av eq bv;\\n		}\\n\\n		let aid := a.id();\\n		let bid := b.id();\\n		return false if aid \\u2261 null or bid \\u2261 null;\\n		return aid eq bid;\\n	}\\n\\n	method _node_is_xml ( n ) {\\n		if ( n \\u2261 null ) {\\n			return false;\\n		}\\n		let raw := n.raw();\\n		try {\\n			let node_type := raw.nodeType();\\n			return node_type \\u2262 null;\\n		}\\n		catch {\\n			return false;\\n		}\\n	}\\n}\\n\';\n        virtualFiles["/modules/std/path/z/functions.zzm"] = `=encoding utf8\n\n=head1 NAME\n\nstd/path/z/functions - Function definitions for ZPath.\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by all implementations of ZuzuScript.\n\n=head1 DESCRIPTION\n\nThis module defines the function objects and standard function table used\nby C<std/path/z>.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<< Func({ spelling: String, f: Function }) >>\n\nConstructs a ZPath function definition. Returns: C<Func>.\n\n=over\n\n=item C<< func.has_name(n) >>\n\nParameters: C<n> is a function name. Returns: C<Boolean>. Returns true\nwhen C<n> matches the function spelling.\n\n=back\n\n=back\n\n=head2 Functions\n\n=over\n\n=item C<< replace(haystack, needle, replacement) >>\n\nParameters: C<haystack> is source text, C<needle> is a pattern, and\nC<replacement> is replacement text. Returns: C<String>. Performs ZPath\nreplacement with capture substitutions.\n\n=item C<< mk_single_number_function(String name, Function impl) >>\n\nParameters: C<name> is a ZPath function name and C<impl> maps one\nnumber. Returns: C<Function>. Builds a function wrapper for per-node\nnumeric functions.\n\n=item C<< mk_aggregate_number_function(String name, Function impl) >>\n\nParameters: C<name> is a ZPath function name and C<impl> maps an array\nof numbers. Returns: C<Function>. Builds a function wrapper for\naggregate numeric functions.\n\n=item C<< mk_single_string_function(String name, Function impl) >>\n\nParameters: C<name> is a ZPath function name and C<impl> maps one\nstring. Returns: C<Function>. Builds a function wrapper for per-node\nstring functions.\n\n=item C<< mk_match_function() >>\n\nParameters: none. Returns: C<Function>. Builds the standard ZPath\nC<match> function implementation.\n\n=back\n\n=head2 Constants\n\n=over\n\n=item C<STANDARD_FUNCTIONS>\n\nType: C<Array>. Standard ZPath function definitions.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/path/z/functions >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/path/z/node import KDLNodeNode, KDLValueNode, Node, XmlNodeNode;\nfrom std/path/z/operators import EvalHelpers;\nfrom std/data/xml/escape import escape_xml, unescape_xml;\nfrom std/string import index, rindex, search, sprint, substr, join;\nfrom std/math import Math;\n\n\nclass Func with EvalHelpers {\n	let String spelling with get;\n	let Function f;\n\n	method has_name ( n ) {\n		return true if self.get_spelling eq n;\n		return false;\n	}\n}\n\nfunction replace ( haystack, needle, replacement ) {\n	let copy := haystack;\n\n	if ( replacement ~ /\\\\$[0-9]/ ) {\n		let r := replacement;\n		copy ~= needle \\u2192 do {\n			let matches := m;\n			r ~= /\\\\$([0-9]+)/g \\u2192 matches[ m[1] ];\n			r;\n		};\n	}\n	else {\n		copy ~= needle \\u2192 replacement;\n	}\n\n	return copy;\n}\n\nfunction mk_single_number_function ( String name, Function impl ) {\n	return function ( funk, ev, ast, ctx, args ) {\n		let nodes := [];\n		for ( let a in args ) {\n			const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );\n			for ( let n in got ) {\n				nodes.push( n );\n			}\n		}\n		else {\n			nodes := ctx.nodeset;\n		}\n		return nodes\n			.map( fn x \\u2192 x.number_value )\n			.grep( fn x \\u2192 x instanceof Number )\n			.map( fn x \\u2192 funk.wrap_for_array( impl(x) ) );\n	};\n}\n\nfunction mk_aggregate_number_function ( String name, Function impl ) {\n	return function ( funk, ev, ast, ctx, args ) {\n		let nodes := [];\n		for ( let a in args ) {\n			const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );\n			for ( let n in got ) {\n				nodes.push( n );\n			}\n		}\n		else {\n			nodes := ctx.nodeset;\n		}\n		const nums := nodes\n			.map( fn x \\u2192 x.number_value )\n			.grep( fn x \\u2192 x instanceof Number );\n		return funk.wrap( impl( nums ) );\n	};\n}\n\nfunction mk_single_string_function ( String name, Function impl ) {\n	return function ( funk, ev, ast, ctx, args ) {\n		let nodes := [];\n		for ( let a in args ) {\n			const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );\n			for ( let n in got ) {\n				nodes.push( n );\n			}\n		}\n		else {\n			nodes := ctx.nodeset;\n		}\n		return nodes\n			.map( fn x \\u2192 x.string_value )\n			.grep( fn x \\u2192 x instanceof String )\n			.map( fn x \\u2192 funk.wrap_for_array( impl(x) ) );\n	};\n}\n\nfunction mk_match_function () {\n	return function ( funk, ev, ast, ctx, args ) {\n		let nodes := [];\n		let re;\n\n		if ( args.empty ) {\n			die "Not enough arguments for match()";\n		}\n		else {\n			re := try {\n				ev.eval_expr( args[0], ev.nested_ctx( ctx ) )[0].string_value;\n			} catch {\n				"";\n			};\n		}\n\n		for ( let a in args[1:] ) {\n			const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );\n			for ( let n in got ) {\n				nodes.push( n );\n			}\n		}\n		else {\n			nodes := ctx.nodeset;\n		}\n\n		return nodes\n			.map( fn x \\u2192 x.string_value )\n			.grep( fn x \\u2192 x instanceof String )\n			.map( fn x \\u2192 funk.wrap_for_array( ( x ~ re ) ? true : false ) );\n	}\n}\n\nconst STANDARD_FUNCTIONS := [\n	new Func(\n		spelling: "true",\n		f: function ( funk, ev, ast, ctx, args ) {\n			die "Too many arguments for true()" unless args.empty;\n			return funk.wrap( true );\n		},\n	),\n\n	new Func(\n		spelling: "false",\n		f: function ( funk, ev, ast, ctx, args ) {\n			die "Too many arguments for false()" unless args.empty;\n			return funk.wrap( false );\n		},\n	),\n\n	new Func(\n		spelling: "null",\n		f: function ( funk, ev, ast, ctx, args ) {\n			die "Too many arguments for null()" unless args.empty;\n			return funk.wrap( null );\n		},\n	),\n\n	new Func(\n		spelling: "die",\n		f: function ( funk, ev, ast, ctx, args ) {\n			die "Called \'die\' function in zpath";\n		},\n	),\n\n	new Func(\n		spelling: "count",\n		f: function ( funk, ev, ast, ctx, args ) {\n			let n := 0;\n			for ( let a in args ) {\n				const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );\n				n += got.length;\n			}\n			else {\n				// Parentset can be an empty array; only null falls back.\n				const cur := ctx.parentset ?: ctx.nodeset;\n				n := cur.length;\n			}\n			return funk.wrap( n );\n		},\n	),\n\n	new Func(\n		spelling: "index",\n		f: function ( funk, ev, ast, ctx, args ) {\n			if ( args.length = 0 ) {\n				const cur := ctx.nodeset.get( 0, null );\n				return funk.wrap( cur ? cur.ix : null );\n			}\n			else if ( args.length = 1 ) {\n				const got := ev.eval_expr( args[0], ev.nested_ctx( ctx ) );\n				return got.map( fn x \\u2192 funk.wrap_for_array(x.ix) );\n			}\n			die "Too many arguments for index()";\n		},\n	),\n\n	new Func(\n		spelling: "key",\n		f: function ( funk, ev, ast, ctx, args ) {\n			if ( args.length = 0 ) {\n				const cur := ctx.nodeset.get( 0, null );\n				return funk.wrap( cur ? cur.key : null );\n			}\n			else if ( args.length = 1 ) {\n				const got := ev.eval_expr( args[0], ev.nested_ctx( ctx ) );\n				return got.map(\n					fn x \\u2192 funk.wrap_for_array(\n						x \\u2261 null ? null : x.key\n					)\n				);\n			}\n			die "Too many arguments for key()";\n		},\n	),\n\n	new Func(\n		spelling: "type",\n		f: function ( funk, ev, ast, ctx, args ) {\n			if ( args.length = 0 ) {\n				const cur := ctx.nodeset.get( 0, null );\n				return funk.wrap( cur ? cur.type : "undefined" );\n			}\n			else if ( args.length = 1 ) {\n				const got := ev.eval_expr( args[0], ev.nested_ctx( ctx ) ).get( 0, null );\n				return funk.wrap( got ? got.type : "undefined" );\n			}\n			die "Too many arguments for type()";\n		},\n	),\n\n	new Func(\n		spelling: "union",\n		f: function ( funk, ev, ast, ctx, args ) {\n			let out := [];\n			for ( let arg in args ) {\n				const got := ev.eval_expr( arg, ev.nested_ctx( ctx ) );\n				for ( let n in got ) {\n					out.push( n );\n				}\n			}\n			return ev.dedup_nodes( out );\n		},\n	),\n\n	new Func(\n		spelling: "intersection",\n		f: function ( funk, ev, ast, ctx, args ) {\n			return [] if args.empty;\n\n			let out := ev.eval_expr( args[0], ev.nested_ctx( ctx ) );\n			out := ev.dedup_nodes( out );\n\n			let i := 1;\n			while ( i < args.length() ) {\n				let got := ev.eval_expr( args[i], ev.nested_ctx( ctx ) );\n				got := ev.dedup_nodes( got );\n\n				let seen := {};\n				for ( let n in got ) {\n					let key := n.id();\n					if ( key \\u2261 null ) {\n						key := "anon:" _ ( "" _ n.raw() );\n					}\n					seen.set( key, true );\n				}\n\n				let next_out := [];\n				for ( let n in out ) {\n					let key := n.id();\n					if ( key \\u2261 null ) {\n						key := "anon:" _ ( "" _ n.raw() );\n					}\n					if ( seen.exists(key) ) {\n						next_out.push(n);\n					}\n				}\n\n				out := next_out;\n				last if out.empty;\n				i++;\n			}\n\n			return ev.dedup_nodes( out );\n		},\n	),\n\n	new Func(\n		spelling: "is-first",\n		f: function ( funk, ev, ast, ctx, args ) {\n			if ( args.length = 0 ) {\n				const cur := ctx.nodeset.get( 0, null );\n				return [] unless cur and cur.parent;\n				return funk.wrap( cur.ix = 0 );\n			}\n			die "Too many arguments for is-first()";\n		},\n	),\n\n	new Func(\n		spelling: "is-last",\n		f: function ( funk, ev, ast, ctx, args ) {\n			if ( args.length = 0 ) {\n				const cur := ctx.nodeset.get( 0, null );\n				return [] unless cur and cur.parent and cur.ix \\u2262 null;\n				const siblings := cur.parent.children\n					.grep( fn kid \\u2192 kid.key \\u2261 cur.key );\n				return [] if siblings.empty;\n				let pos := 0;\n				while ( pos < siblings.length ) {\n					const kid := siblings[pos];\n					last if kid.id() \\u2261 cur.id();\n					pos++;\n				}\n				return [] if pos \\u2265 siblings.length;\n				return funk.wrap( pos = siblings.length - 1 );\n			}\n			die "Too many arguments for is-last()";\n		},\n	),\n\n	new Func(\n		spelling: "next",\n		f: function ( funk, ev, ast, ctx, args ) {\n			if ( args.length = 0 ) {\n				const cur := ctx.nodeset.get( 0, null );\n				return [ cur.next_sibling ];\n			}\n			else {\n				let out := [];\n				for ( let arg in args ) {\n					const got := ev.eval_expr( arg, ev.nested_ctx( ctx ) );\n					for ( let n in got ) {\n						out.push( n.next_sibling );\n					}\n				}\n				return out;\n			}\n		},\n	),\n\n	new Func(\n		spelling: "prev",\n		f: function ( funk, ev, ast, ctx, args ) {\n			if ( args.length = 0 ) {\n				const cur := ctx.nodeset.get( 0, null );\n				return [ cur.prev_sibling ];\n			}\n			else {\n				let out := [];\n				for ( let arg in args ) {\n					const got := ev.eval_expr( arg, ev.nested_ctx( ctx ) );\n					for ( let n in got ) {\n						out.push( n.prev_sibling );\n					}\n				}\n				return out;\n			}\n		},\n	),\n\n	new Func(\n		spelling: "string",\n		f: function ( funk, ev, ast, ctx, args ) {\n			if ( args.length = 0 ) {\n				const cur := ctx.nodeset.get( 0, null );\n				return [] unless cur;\n				return funk.wrap( cur.string_value );\n			}\n			else {\n				let out := [];\n				for ( let arg in args ) {\n					const got := ev.eval_expr( arg, ev.nested_ctx( ctx ) );\n					for ( let n in got ) {\n						out.push( n );\n					}\n				}\n				return out.map( fn x \\u2192 funk.wrap_for_array( x.string_value ) );\n			}\n		},\n	),\n\n	new Func(\n		spelling: "number",\n		f: function ( funk, ev, ast, ctx, args ) {\n			if ( args.length = 0 ) {\n				const cur := ctx.nodeset.get( 0, null );\n				return [] unless cur;\n				return funk.wrap( cur.number_value );\n			}\n			else {\n				let out := [];\n				for ( let arg in args ) {\n					const got := ev.eval_expr( arg, ev.nested_ctx( ctx ) );\n					for ( let n in got ) {\n						out.push( n );\n					}\n				}\n				return out.map( fn x \\u2192 funk.wrap_for_array( x.number_value ) );\n			}\n		},\n	),\n\n	new Func(\n		spelling: "value",\n		f: function ( funk, ev, ast, ctx, args ) {\n			if ( args.length = 0 ) {\n				const cur := ctx.nodeset.get( 0, null );\n				return [] unless cur;\n				return funk.wrap( cur.primitive_value );\n			}\n			else {\n				let out := [];\n				for ( let arg in args ) {\n					const got := ev.eval_expr( arg, ev.nested_ctx( ctx ) );\n					for ( let n in got ) {\n						out.push( n );\n					}\n				}\n				return out.map( fn x \\u2192 funk.wrap_for_array( x.primitive_value ) );\n			}\n		},\n	),\n\n	new Func(\n		spelling: "ceil",\n		f: mk_single_number_function( "ceil", fn n \\u2192 ceil n ),\n	),\n\n	new Func(\n		spelling: "floor",\n		f: mk_single_number_function( "floor", fn n \\u2192 floor n ),\n	),\n\n	new Func(\n		spelling: "round",\n		f: mk_single_number_function( "round", fn n \\u2192 round n ),\n	),\n\n	new Func(\n		spelling: "sum",\n		f: mk_aggregate_number_function( "sum", fn nums \\u2192 Math.sum(nums) ),\n	),\n\n	new Func(\n		spelling: "min",\n		f: mk_aggregate_number_function( "min", fn nums \\u2192 Math.min(nums) ),\n	),\n\n	new Func(\n		spelling: "max",\n		f: mk_aggregate_number_function( "max", fn nums \\u2192 Math.max(nums) ),\n	),\n\n	new Func(\n		spelling: "escape",\n		f: mk_single_string_function( "escape", fn s \\u2192 escape_xml(s) ),\n	),\n\n	new Func(\n		spelling: "unescape",\n		f: mk_single_string_function( "unescape", fn s \\u2192 unescape_xml(s) ),\n	),\n\n	new Func(\n		spelling: "upper-case",\n		f: mk_single_string_function( "upper-case", fn s \\u2192 uc s ),\n	),\n\n	new Func(\n		spelling: "lower-case",\n		f: mk_single_string_function( "lower-case", fn s \\u2192 lc s ),\n	),\n\n	new Func(\n		spelling: "index-of",\n		f: function ( funk, ev, ast, ctx, args ) {\n			let nodes := [];\n			let search;\n\n			if ( args.empty ) {\n				die "Not enough arguments for index-of()";\n			}\n			else {\n				search := try {\n					ev.eval_expr( args[0], ev.nested_ctx( ctx ) )[0].string_value;\n				} catch {\n					"";\n				};\n			}\n\n			for ( let a in args[1:] ) {\n				const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );\n				for ( let n in got ) {\n					nodes.push( n );\n				}\n			}\n			else {\n				nodes := ctx.nodeset;\n			}\n\n			return nodes\n				.map( fn x \\u2192 x.string_value )\n				.grep( fn x \\u2192 x instanceof String )\n				.map( fn x \\u2192 funk.wrap_for_array( index(x, search) ) );\n		}\n	),\n\n	new Func(\n		spelling: "last-index-of",\n		f: function ( funk, ev, ast, ctx, args ) {\n			let nodes := [];\n			let search;\n\n			if ( args.empty ) {\n				die "Not enough arguments for last-index-of()";\n			}\n			else {\n				search := try {\n					ev.eval_expr( args[0], ev.nested_ctx( ctx ) )[0].string_value;\n				} catch {\n					"";\n				};\n			}\n\n			for ( let a in args[1:] ) {\n				const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );\n				for ( let n in got ) {\n					nodes.push( n );\n				}\n			}\n			else {\n				nodes := ctx.nodeset;\n			}\n\n			return nodes\n				.map( fn x \\u2192 x.string_value )\n				.grep( fn x \\u2192 x instanceof String )\n				.map( fn x \\u2192 funk.wrap_for_array( rindex(x, search) ) );\n		}\n	),\n\n	new Func(\n		spelling: "substring",\n		f: function ( funk, ev, ast, ctx, args ) {\n\n			let nodes := [];\n			let start;\n			let len;\n\n			if ( args.length < 2 ) {\n				die "Not enough arguments for substring()";\n			}\n			else {\n				start := try {\n					ev.eval_expr( args[-2], ev.nested_ctx( ctx ) )[0].number_value;\n				} catch {\n					0;\n				};\n				len := try {\n					ev.eval_expr( args[-1], ev.nested_ctx( ctx ) )[0].number_value;\n				} catch {\n					0;\n				};\n			}\n\n			for ( let a in args[0:-2] ) {\n				const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );\n				for ( let n in got ) {\n					nodes.push( n );\n				}\n			}\n			else {\n				nodes := ctx.nodeset;\n			}\n\n			return nodes\n				.map( fn x \\u2192 x.string_value )\n				.grep( fn x \\u2192 x instanceof String )\n				.map( fn x \\u2192 funk.wrap_for_array( substr(x, start, len) ) );\n		}\n	),\n\n	new Func(\n		spelling: "format",\n		f: function ( funk, ev, ast, ctx, args ) {\n			let nodes := [];\n			let fmt;\n\n			if ( args.empty ) {\n				die "Not enough arguments for format()";\n			}\n			else {\n				fmt := try {\n					ev.eval_expr( args[0], ev.nested_ctx( ctx ) )[0].string_value;\n				} catch {\n					"";\n				};\n			}\n\n			for ( let a in args[1:] ) {\n				const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );\n				for ( let n in got ) {\n					nodes.push( n );\n				}\n			}\n			else {\n				nodes := ctx.nodeset;\n			}\n\n			return nodes\n				.map( fn x \\u2192 x.string_value )\n				.grep( fn x \\u2192 x instanceof String )\n				.map( fn x \\u2192 funk.wrap_for_array( sprint(fmt, x) ) );\n		}\n	),\n\n	new Func(\n		spelling: "string-length",\n		f: mk_single_string_function( "string-length", fn s \\u2192 length s ),\n	),\n\n	new Func(\n		spelling: "match",\n		f: mk_match_function(),\n	),\n\n	new Func(\n		spelling: "matches",\n		f: mk_match_function(),\n	),\n\n	new Func(\n		spelling: "replace",\n		f: function ( funk, ev, ast, ctx, args ) {\n			let nodes := [];\n			let pattern;\n			let replacement;\n\n			if ( args.length < 2 ) {\n				die "Not enough arguments for replace()";\n			}\n			else {\n				pattern := try {\n					ev.eval_expr( args[0], ev.nested_ctx( ctx ) )[0].string_value;\n				} catch {\n					"";\n				};\n				replacement := try {\n					ev.eval_expr( args[1], ev.nested_ctx( ctx ) )[0].string_value;\n				} catch {\n					"";\n				};\n			}\n\n			for ( let a in args[2:] ) {\n				const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );\n				for ( let n in got ) {\n					nodes.push( n );\n				}\n			}\n			else {\n				nodes := ctx.nodeset;\n			}\n\n			return nodes\n				.map( fn x \\u2192 x.string_value )\n				.grep( fn x \\u2192 x instanceof String )\n				.map( fn x \\u2192 funk.wrap_for_array( replace( x, pattern, replacement ) ) );\n		}\n	),\n\n	new Func(\n		spelling: "join",\n		f: function ( funk, ev, ast, ctx, args ) {\n			let nodes := [];\n			let joiner;\n\n			if ( args.empty ) {\n				die "Not enough arguments for format()";\n			}\n			else {\n				joiner := try {\n					ev.eval_expr( args[0], ev.nested_ctx( ctx ) )[0].string_value;\n				} catch {\n					"";\n				};\n			}\n\n			for ( let a in args[1:] ) {\n				const got := ev.eval_expr( a, ev.nested_ctx( ctx ) );\n				for ( let n in got ) {\n					nodes.push( n );\n				}\n			}\n			else {\n				nodes := ctx.nodeset;\n			}\n\n			const strings := nodes\n				.map( fn x \\u2192 x.string_value )\n				.grep( fn x \\u2192 x instanceof String );\n			return funk.wrap( join( joiner, strings ) );\n		}\n	),\n\n	new Func(\n		spelling: "url",\n		f: function ( funk, ev, ast, ctx, args ) {\n			if ( args.length = 0 ) {\n				const cur := ctx.nodeset.get( 0, null );\n				return [] unless cur;\n				return funk.wrap( cur instanceof XmlNodeNode ? cur.raw.namespaceURI() : null );\n			}\n			else if ( args.length = 1 ) {\n				const got := ev.eval_expr( args[0], ev.nested_ctx( ctx ) );\n				return got.map(\n					fn x \\u2192 funk.wrap_for_array(\n						x instanceof XmlNodeNode ? x.raw.namespaceURI() : null\n					)\n				);\n			}\n			die "Too many arguments for url()";\n		},\n	),\n\n	new Func(\n		spelling: "local-name",\n		f: function ( funk, ev, ast, ctx, args ) {\n			if ( args.length = 0 ) {\n				const cur := ctx.nodeset.get( 0, null );\n				return [] unless cur;\n				return funk.wrap(\n					cur instanceof XmlNodeNode ? cur.raw.localName()\n						: cur instanceof KDLNodeNode ? cur.name()\n						: null\n				);\n			}\n			else if ( args.length = 1 ) {\n				const got := ev.eval_expr( args[0], ev.nested_ctx( ctx ) );\n				return got.map(\n					fn x \\u2192 funk.wrap_for_array(\n						x instanceof XmlNodeNode ? x.raw.localName()\n							: x instanceof KDLNodeNode ? x.name()\n							: null\n					)\n				);\n			}\n			die "Too many arguments for local-name()";\n		},\n	),\n\n	new Func(\n		spelling: "tag",\n		f: function ( funk, ev, ast, ctx, args ) {\n			if ( args.length = 0 ) {\n				const cur := ctx.nodeset.get( 0, null );\n				return [] unless cur;\n				if ( cur instanceof KDLNodeNode ) {\n					let ann := cur.raw().type_annotation();\n					return funk.wrap( ann \\u2261 null ? null : "" _ ann );\n				}\n				if ( cur instanceof KDLValueNode ) {\n					let ann := cur.raw().type_annotation();\n					return funk.wrap( ann \\u2261 null ? null : "" _ ann );\n				}\n				return funk.wrap( cur.has_tagged ? cur.tagged{tag} : null );\n			}\n			else if ( args.length = 1 ) {\n				const got := ev.eval_expr( args[0], ev.nested_ctx( ctx ) );\n				return got.map(\n					fn x \\u2192 funk.wrap_for_array(\n						x instanceof KDLNodeNode\n							? (\n								x.raw().type_annotation() \\u2261 null\n									? null\n									: "" _ x.raw().type_annotation()\n							)\n							: x instanceof KDLValueNode\n							? (\n								x.raw().type_annotation() \\u2261 null\n									? null\n									: "" _ x.raw().type_annotation()\n							)\n							: x can has_tagged ? x.tagged{tag} : null\n					)\n				);\n			}\n			die "Too many arguments for tag()";\n		},\n	),\n];\n`;\n        virtualFiles["/modules/std/path/z/lexer.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/path/z/lexer - Pure Zuzu lexer for ZPath expressions.\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nThis module provides the pure-Zuzu lexer used by ZPath.\\n\\n=head1 EXPORTS\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<< Lexer({ src: String, allowed_operators: Array }) >>\\n\\nConstructs a ZPath lexer. Returns: C<Lexer>. Tokenizes C<src> using the\\nallowed operator table.\\n\\n=over\\n\\n=item C<< lexer.peek() >>\\n\\nParameters: none. Returns: C<Dict>. Returns the current token without\\nadvancing.\\n\\n=item C<< lexer.peek_n(n) >>\\n\\nParameters: C<n> is a zero-based lookahead offset. Returns: C<Dict>.\\nReturns a token ahead of the current position.\\n\\n=item C<< lexer.peek_kind() >>\\n\\nParameters: none. Returns: C<String>. Returns the current token kind.\\n\\n=item C<< lexer.peek_kind_n(n) >>\\n\\nParameters: C<n> is a zero-based lookahead offset. Returns: C<String>.\\nReturns a token kind ahead of the current position.\\n\\n=item C<< lexer.next_tok() >>\\n\\nParameters: none. Returns: C<Dict>. Consumes and returns the current\\ntoken.\\n\\n=item C<< lexer.expect(k) >>\\n\\nParameters: C<k> is the expected token kind. Returns: C<Dict>. Consumes\\nand returns the current token, throwing when it has a different kind.\\n\\n=item C<< lexer.known_operators() >>\\n\\nParameters: none. Returns: C<Array>. Returns the allowed operator\\ndefinitions.\\n\\n=back\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/path/z/lexer >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/string import substr;\\n\\nclass Lexer {\\n	let src := "";\\n	let scan_i := 0;\\n	let toks := [];\\n	let pos := 0;\\n	let allowed_operators;\\n\\n	method __build__ () {\\n		die "Expected some operators" unless allowed_operators;\\n		toks := self._tokenize(src);\\n	}\\n\\n	method peek () {\\n		return toks[pos];\\n	}\\n\\n	method peek_n ( n ) {\\n		return toks[pos + n];\\n	}\\n\\n	method peek_kind () {\\n		return toks[pos]{k};\\n	}\\n\\n	method peek_kind_n ( n ) {\\n		return toks[pos + n]{k};\\n	}\\n\\n	method next_tok () {\\n		let tok := toks[pos];\\n		pos++;\\n		return tok;\\n	}\\n\\n	method expect ( k ) {\\n		let t := self.next_tok();\\n		die `Expected ${k}, got ${t{k}}` if t{k} \\u2262 k;\\n		return t;\\n	}\\n\\n	method _is_ws ( c ) {\\n		return c \\u2262 null and c ~ /\\\\s/;\\n	}\\n\\n	method _prev_sig ( chars, idx ) {\\n		let j := idx - 1;\\n		while ( j >= 0 ) {\\n			if ( chars[j] ~ /\\\\s/ ) {\\n				j--;\\n				next;\\n			}\\n			return chars[j];\\n		}\\n		return null;\\n	}\\n\\n	method _next_sig ( chars, idx, n ) {\\n		let j := idx + 1;\\n		while ( j < n ) {\\n			if ( chars[j] ~ /\\\\s/ ) {\\n				j++;\\n				next;\\n			}\\n			return chars[j];\\n		}\\n		return null;\\n	}\\n\\n	method _is_path_ctx_prev ( c ) {\\n		return c \\u2261 "[" or c \\u2261 "(" or c \\u2261 "," or c \\u2261 ":" or c \\u2261 "?" or c \\u2261 "/";\\n	}\\n\\n	method _is_path_ctx_next ( c ) {\\n		return c \\u2261 "]" or c \\u2261 ")" or c \\u2261 "," or c \\u2261 ":" or c \\u2261 "?" or c \\u2261 "/";\\n	}\\n\\n	method _ws_on_both ( left, right ) {\\n		return self._is_ws(left) and self._is_ws(right);\\n	}\\n\\n	method known_operators () {\\n		return allowed_operators;\\n	}\\n\\n	method _sorted_operators () {\\n		return self.known_operators()\\n			.grep( fn o \\u2192 not o.lexer_should_ignore )\\n			.sort( fn ( x, y ) \\u2192 y.char_length <=> x.char_length );\\n	}\\n\\n	method _operator_at ( chars, i, n, ops ) {\\n		let oi := 0;\\n		while ( oi < ops.length ) {\\n			let op := ops[oi];\\n			let spell := op{spelling};\\n			let m := length spell;\\n			if ( i + m <= n ) {\\n				let got := "";\\n				let j := 0;\\n				while ( j < m ) {\\n					got _= chars[i + j];\\n					j++;\\n				}\\n				if ( got \\u2261 spell ) {\\n					return op;\\n				}\\n			}\\n			oi++;\\n		}\\n		return null;\\n	}\\n\\n	method _is_name_char ( c ) {\\n		return c ~ /[A-Za-z0-9_\\\\-]/;\\n	}\\n\\n	method _allows_operator_kind ( kind ) {\\n		return allowed_operators.first( fn op \\u2192 op.get_kind() \\u2261 kind )\\n			? true\\n			: false;\\n	}\\n\\n	method _tokenize ( String source ) {\\n		let t := [];\\n		let chars := [];\\n		let n := length source;\\n		let ops := self._sorted_operators();\\n		let z := 0;\\n		while ( z < n ) {\\n			chars.push( substr( source, z, 1 ) );\\n			z++;\\n		}\\n\\n		let i := 0;\\n		while ( i < n ) {\\n			let ch := chars[i];\\n\\n			if ( ch ~ /\\\\s/ ) {\\n				i++;\\n				next;\\n			}\\n\\n			let prev := i > 0 ? chars[i - 1] : null;\\n			let nxt := i + 1 < n ? chars[i + 1] : null;\\n\\n			let prev_nonws := self._prev_sig( chars, i );\\n			let next_nonws := self._next_sig( chars, i, n );\\n\\n			function push_token ( tok ) {\\n				tok{ws_before} := self._is_ws(prev) ? true : false;\\n				tok{ws_after}  := self._is_ws(nxt)  ? true : false;\\n				t.push( tok );\\n			}\\n\\n			function push_sized_token ( tok, after ) {\\n				tok{ws_before} := self._is_ws(prev) ? true : false;\\n				tok{ws_after}  := self._is_ws(after) ? true : false;\\n				t.push( tok );\\n			}\\n\\n			if ( ch \\u2261 "/" ) {\\n				if (\\n					self._ws_on_both( prev, nxt )\\n					and prev_nonws \\u2262 null and next_nonws \\u2262 null\\n					and not self._is_path_ctx_prev(prev_nonws)\\n					and not self._is_path_ctx_next(next_nonws)\\n				) {\\n					push_token( { k: "SLASH", v: "/" } );\\n					i++;\\n					next;\\n				}\\n				if (\\n					( self._is_ws(prev) xor self._is_ws(nxt) )\\n					and prev_nonws \\u2262 null and next_nonws \\u2262 null\\n					and not self._is_path_ctx_prev(prev_nonws)\\n					and not self._is_path_ctx_next(next_nonws)\\n				) {\\n					die `Binary operator \\\'/\\\' requires whitespace around it`;\\n				}\\n				t.push( { k: "SLASH_PATH", v: "/" } );\\n				i++;\\n				next;\\n			}\\n\\n			let op := self._operator_at( chars, i, n, ops );\\n			if ( op \\u2262 null ) {\\n				let spell := op.get_spelling();\\n				let need_ws := op.requires_whitespace();\\n				let m := length spell;\\n				let op_prev := i > 0 ? chars[i - 1] : null;\\n				let op_next := i + m < n ? chars[i + m] : null;\\n				let path_ambiguous_star :=\\n					( spell \\u2261 "*" or spell \\u2261 "**" )\\n					and not self._ws_on_both( op_prev, op_next );\\n\\n				let left_name := false;\\n				let right_name := false;\\n				if ( spell ~ /^[A-Za-z_]/ ) {\\n					left_name := op_prev \\u2262 null and self._is_name_char(op_prev);\\n					right_name := op_next \\u2262 null and self._is_name_char(op_next);\\n				}\\n\\n				if (\\n					not path_ambiguous_star\\n					and not left_name\\n					and not right_name\\n				) {\\n					if ( need_ws ) {\\n						if ( self._ws_on_both( op_prev, op_next ) ) {\\n							push_sized_token( { k: op.get_kind(), v: spell }, op_next );\\n							i := i + m;\\n							next;\\n						}\\n						die `Binary operator \\\'${spell}\\\' requires whitespace around it`;\\n					}\\n					push_sized_token( { k: op.get_kind(), v: spell }, op_next );\\n					i := i + m;\\n					next;\\n				}\\n			}\\n\\n			if ( ch \\u2261 "(" ) { t.push( { k: "LPAREN", v: "(" } ); i++; next; }\\n			if ( ch \\u2261 ")" ) { t.push( { k: "RPAREN", v: ")" } ); i++; next; }\\n			if ( ch \\u2261 "[" ) { t.push( { k: "LBRACK", v: "[" } ); i++; next; }\\n			if ( ch \\u2261 "]" ) { t.push( { k: "RBRACK", v: "]" } ); i++; next; }\\n			if ( ch \\u2261 "," ) { t.push( { k: "COMMA", v: "," } ); i++; next; }\\n\\n			if ( ch \\u2261 "." ) {\\n				if ( i + 2 < n and chars[i + 1] \\u2261 "." and chars[i + 2] \\u2261 "*" ) {\\n					push_token( { k: "DOTDOTSTAR", v: "..*" } );\\n					i := i + 3;\\n					next;\\n				}\\n				if ( i + 1 < n and chars[i + 1] \\u2261 "." ) {\\n					push_token( { k: "DOTDOT", v: ".." } );\\n					i := i + 2;\\n					next;\\n				}\\n				push_token( { k: "DOT", v: "." } );\\n				i++;\\n				next;\\n			}\\n\\n			if ( ch \\u2261 "*" and self._ws_on_both( prev, nxt ) ) {\\n				push_token( { k: "STAR", v: "*" } );\\n				i++;\\n				next;\\n			}\\n\\n			if ( ch \\u2261 "*" ) {\\n				if ( i + 1 < n and chars[i + 1] \\u2261 "*" ) {\\n					push_token( { k: "STARSTAR", v: "**" } );\\n					i := i + 2;\\n					next;\\n				}\\n				push_token( { k: "STAR_PATH", v: "*" } );\\n				i++;\\n				next;\\n			}\\n\\n			if ( self._allows_operator_kind( "ELVIS" ) and ch \\u2261 "?" and nxt \\u2261 ":" ) {\\n				let op_next := i + 2 < n ? chars[i + 2] : null;\\n				if ( self._ws_on_both( prev, op_next ) ) {\\n					t.push( {\\n						k: "ELVIS",\\n						v: "?:",\\n						ws_before: self._is_ws(prev) ? true : false,\\n						ws_after: self._is_ws(op_next) ? true : false,\\n					} );\\n					i := i + 2;\\n					next;\\n				}\\n				die "Elvis operator \\\'?:\\\' requires whitespace around it";\\n			}\\n\\n			if ( ch \\u2261 "?" or ch \\u2261 ":" ) {\\n				if ( self._ws_on_both( prev, nxt ) ) {\\n					push_token( { k: ch \\u2261 "?" ? "QMARK" : "COLON", v: ch } );\\n					i++;\\n					next;\\n				}\\n				die `Ternary operator \\\'${ch}\\\' requires whitespace around it`;\\n			}\\n\\n			if ( ch \\u2261 "\\\\"" or ch \\u2261 "\\\'" ) {\\n				let quote := ch;\\n				i++;\\n				let s := "";\\n				let esc := false;\\n				while ( i < n ) {\\n					let cc := chars[i];\\n					i++;\\n					if ( esc ) {\\n						if ( cc \\u2261 "\\\\\\\\" or cc \\u2261 quote or cc \\u2261 "\\\\"" or cc \\u2261 "\\\'" ) {\\n							s _= cc;\\n						}\\n						else {\\n							s _= self._unescape_char(cc);\\n						}\\n						esc := false;\\n						next;\\n					}\\n					if ( cc \\u2261 "\\\\\\\\" ) { esc := true; next; }\\n					last if cc \\u2261 quote;\\n					s _= cc;\\n				}\\n				push_token( { k: "STRING", v: s, q: quote } );\\n				next;\\n			}\\n\\n			if ( ch \\u2261 "#" ) {\\n				let j := i + 1;\\n				let neg := false;\\n				if ( j < n and chars[j] \\u2261 "-" ) {\\n					neg := true;\\n					j++;\\n				}\\n				die "Invalid index \\\'#\\\'" if j >= n or not( chars[j] ~ /\\\\d/ );\\n				let num := "";\\n				while ( j < n and chars[j] ~ /\\\\d/ ) {\\n					num _= chars[j];\\n					j++;\\n				}\\n				let parsed := 0 + num;\\n				parsed := 0 - parsed if neg;\\n				push_token( { k: "INDEX", v: parsed } );\\n				i := j;\\n				next;\\n			}\\n\\n			if ( ch ~ /[0-9]/ ) {\\n				let j := i;\\n				let num := "";\\n				while ( j < n and chars[j] ~ /[0-9.]/ ) {\\n					num _= chars[j];\\n					j++;\\n				}\\n				push_token( { k: "NUMBER", v: 0 + num } );\\n				i := j;\\n				next;\\n			}\\n\\n			let name := self._read_name( chars, i );\\n			if ( name{v} \\u2262 "" ) {\\n				push_token( { k: "NAME", v: name{v} } );\\n				i := name{i};\\n				next;\\n			}\\n\\n			die `Unexpected character \\\'${ch}\\\' at position ${i}`;\\n		}\\n\\n		t.push( { k: "EOF", v: "" } );\\n		return t;\\n	}\\n\\n	method _unescape_char ( c ) {\\n		return "\\\\n" if c \\u2261 "n";\\n		return "\\\\r" if c \\u2261 "r";\\n		return "\\\\t" if c \\u2261 "t";\\n		return c;\\n	}\\n\\n	method _read_name ( chars, start_i ) {\\n		let n := chars.length();\\n		let delim := {\\n			"\\\\n": true,\\n			"\\\\r": true,\\n			"\\\\t": true,\\n			"(": true,\\n			")": true,\\n			"[": true,\\n			"]": true,\\n			"/": true,\\n			",": true,\\n			"=": true,\\n			"&": true,\\n			"|": true,\\n			"!": true,\\n			"<": true,\\n			">": true,\\n			"#": true,\\n			" ": true,\\n		};\\n		let buf := "";\\n		let esc := false;\\n		let i := start_i;\\n\\n		while ( i < n ) {\\n			let c := chars[i];\\n			if ( esc ) {\\n				buf _= c;\\n				esc := false;\\n				i++;\\n				next;\\n			}\\n\\n			if ( c \\u2261 "\\\\\\\\" ) {\\n				esc := true;\\n				i++;\\n				next;\\n			}\\n\\n			last if delim.exists(c);\\n			last if c ~ /\\\\s/;\\n			buf _= c;\\n			i++;\\n		}\\n\\n		return { v: "", i: start_i } if buf \\u2261 "";\\n		return { v: buf, i: i };\\n	}\\n}\\n\';\n        virtualFiles["/modules/std/path/z/node.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/path/z/node - Node wrapper used by std/path/z.\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nObjects of this class wrap underlying values and provide traversal and\\ncoercion helpers used while evaluating ZPath expressions.\\n\\n=head1 EXPORTS\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<Node>\\n\\nBase wrapper for values traversed by ZPath.\\n\\n=over\\n\\n=item C<< Node.from_root(obj) >>\\n\\nParameters: C<obj> is any query root. Returns: C<Node>. Wraps a root\\nvalue for traversal.\\n\\n=item C<< Node.wrap(obj, parent?, key?, ix?) >>\\n\\nParameters: C<obj> is any value, with optional parent, key, and index\\nmetadata. Returns: C<Node>. Wraps a value in the appropriate node\\nsubclass.\\n\\n=item C<< node.hold_parent(owner) >>\\n\\nParameters: C<owner> is a parent node. Returns: C<Node>. Retains parent\\nmetadata on the node.\\n\\n=item C<< node.raw() >>, C<< node.value() >>, C<< node.primitive_value() >>\\n\\nParameters: none. Returns: value. Returns the wrapped raw, node, or\\nprimitive value.\\n\\n=item C<< node.parent() >>\\n\\nParameters: none. Returns: C<Node> or C<null>. Returns the parent node.\\n\\n=item C<< node.key() >>, C<< node.ix() >>, C<< node.index() >>, C<< node.id() >>\\n\\nParameters: none. Returns: value. Returns traversal key, index, or\\nstable node id metadata.\\n\\n=item C<< node.type() >>, C<< node.name() >>\\n\\nParameters: none. Returns: C<String> or C<null>. Returns the node type\\nor name.\\n\\n=item C<< node.tagged() >>\\n\\nParameters: none. Returns: C<String> or C<null>. Returns a KDL value\\ntag when present.\\n\\n=item C<< node.has_tagged() >>\\n\\nParameters: none. Returns: C<Boolean>. Returns true when tag metadata is\\navailable.\\n\\n=item C<< node.string_value() >>, C<< node.number_value() >>\\n\\nParameters: none. Returns: C<String>, C<Number>, or C<null>. Coerces the\\nnode for string or numeric ZPath operations.\\n\\n=item C<< node.can_have_named_children() >>, C<< node.can_have_indexed_children() >>, C<< node.can_have_named_indexed_children() >>\\n\\nParameters: none. Returns: C<Boolean>. Reports supported child lookup\\nmodes.\\n\\n=item C<< node.named_child(name) >>, C<< node.indexed_child(i) >>, C<< node.named_indexed_child(name, i) >>\\n\\nParameters: C<name> is a child name and C<i> is an index. Returns:\\nC<Node> or C<null>. Looks up child nodes.\\n\\n=item C<< node.next_child(child) >>, C<< node.prev_child(child) >>, C<< node.next_sibling() >>, C<< node.prev_sibling() >>\\n\\nParameters: C<child> is a child node where required. Returns: C<Node> or\\nC<null>. Traverses adjacent nodes.\\n\\n=item C<< node.named_attribute(name) >>\\n\\nParameters: C<name> is an attribute name. Returns: C<Node> or C<null>.\\nLooks up one attribute node.\\n\\n=item C<< node.children() >>, C<< node.attributes() >>\\n\\nParameters: none. Returns: C<Array>. Returns child or attribute nodes.\\n\\n=item C<< node.dump() >>\\n\\nParameters: none. Returns: C<String>. Returns a diagnostic rendering of\\nthe node.\\n\\n=item C<< node.find(zpath) >>\\n\\nParameters: C<zpath> is a C<ZPath> object or subclass, such as C<ZZPath>.\\nReturns: C<Array>. Evaluates a nested path from this node and returns\\nselected node objects.\\n\\n=item C<< node.do_action(action) >>, C<< node.do_action_on_child(child, action) >>\\n\\nParameters: C<action> is a path action and C<child> is a child node.\\nReturns: value. Applies path mutation actions.\\n\\n=item C<< node.ref() >>, C<< node.ref_on_child(child) >>\\n\\nParameters: C<child> is a child node where required. Returns:\\nC<Function>. Returns a reference-like getter/setter.\\n\\n=back\\n\\n=item C<SimpleNode>, C<StringNode>, C<NumberNode>, C<BooleanNode>, C<NullNode>\\n\\nScalar node wrappers. They inherit the C<Node> API and override\\nC<type>, C<string_value>, or C<number_value> where appropriate.\\n\\n=item C<ArrayNode>, C<SetNode>, C<BagNode>, C<DictNode>, C<PairListNode>, C<PairNode>\\n\\nCollection node wrappers. They inherit the C<Node> API and override\\nchild, attribute, assignment, and reference methods appropriate to their\\ncollection type. PairList children are C<PairNode> objects in pair order;\\nC<indexed_child> uses global pair index, while C<named_indexed_child> uses\\nthe occurrence index among pairs with the same key.\\n\\n=item C<KDLDocumentNode>, C<KDLNodeNode>, C<KDLValueNode>\\n\\nKDL node wrappers. They inherit the C<Node> API and expose KDL children,\\nattributes, names, value tags, and scalar coercions.\\n\\n=item C<XmlNodeNode>\\n\\nXML node wrapper. It inherits the C<Node> API and exposes XML names,\\nchildren, attributes, sibling traversal, and scalar text values.\\n\\n=item C<TimeNode>\\n\\nC<std/time> wrapper. It inherits the C<Node> API and exposes time\\nattributes plus string and numeric values.\\n\\n=item C<PathNode>\\n\\nC<std/io> path wrapper. It inherits the C<Node> API and exposes path\\nattributes plus string values.\\n\\n=item C<WidgetNode>\\n\\nC<std/gui/objects> widget wrapper. It inherits the C<Node> API and\\nexposes widget children by widget class name and index, plus public\\nwidget properties as assignable attributes.\\n\\n=back\\n\\n=head2 Variables\\n\\n=over\\n\\n=item C<determine_class>\\n\\nType: C<Function>. Chooses the concrete node wrapper class for a raw\\nvalue.\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/path/z/node >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/data/cbor import TaggedValue;\\nfrom std/data/kdl import KDLDocument, KDLNode, KDLValue;\\nfrom std/internals import class_name, load_module, ref_id;\\nfrom std/io try import Path;\\nfrom std/math import Math;\\nfrom std/string import substr;\\nfrom std/time import Time;\\n\\n\\nfunction determine_class;\\nlet _widget_class_loaded := false;\\nlet _widget_class := null;\\n\\nconst _WIDGET_ATTRS := [\\n	{ name: "id", getter: "id", setter: "set_id" },\\n	{ name: "enabled", getter: "enabled", setter: "set_enabled" },\\n	{ name: "visible", getter: "visible", setter: "set_visible" },\\n	{ name: "width", getter: "width", accessor: true },\\n	{ name: "height", getter: "height", accessor: true },\\n	{ name: "minwidth", getter: "minwidth", accessor: true },\\n	{ name: "minheight", getter: "minheight", accessor: true },\\n	{ name: "maxwidth", getter: "maxwidth", accessor: true },\\n	{ name: "maxheight", getter: "maxheight", accessor: true },\\n	{ name: "classes", getter: "classes" },\\n	{ name: "title", getter: "title", setter: "set_title", accessor: true },\\n	{ name: "text", getter: "text", setter: "set_text", accessor: true },\\n	{ name: "value", getter: "value", setter: "set_value", accessor: true },\\n	{ name: "placeholder", getter: "placeholder", setter: "set_placeholder", accessor: true },\\n	{ name: "for", getter: "for_id", setter: "set_for_id", accessor: true },\\n	{ name: "align", getter: "align", accessor: true },\\n	{ name: "gap", getter: "gap", accessor: true },\\n	{ name: "padding", getter: "padding", accessor: true },\\n	{ name: "label", getter: "label", accessor: true },\\n	{ name: "collapsible", getter: "collapsible", accessor: true },\\n	{ name: "collapsed", getter: "collapsed", accessor: true },\\n	{ name: "wrap", getter: "wrap", accessor: true },\\n	{ name: "readonly", getter: "readonly", accessor: true },\\n	{ name: "multiline", getter: "multiline", accessor: true },\\n	{ name: "password", getter: "password", accessor: true },\\n	{ name: "required", getter: "required", accessor: true },\\n	{ name: "src", getter: "src", accessor: true },\\n	{ name: "alt", getter: "alt", accessor: true },\\n	{ name: "fit", getter: "fit", accessor: true },\\n	{ name: "checked", getter: "checked", accessor: true },\\n	{ name: "indeterminate", getter: "indeterminate", accessor: true },\\n	{ name: "name", getter: "name", accessor: true },\\n	{ name: "disabled", getter: "disabled", accessor: true },\\n	{ name: "group", getter: "group", accessor: true },\\n	{ name: "multiple", getter: "multiple", accessor: true },\\n	{ name: "min", getter: "min", accessor: true },\\n	{ name: "max", getter: "max", accessor: true },\\n	{ name: "first_day_of_week", getter: "first_day_of_week", accessor: true },\\n	{ name: "orientation", getter: "orientation", accessor: true },\\n	{ name: "step", getter: "step", accessor: true },\\n	{ name: "show_text", getter: "show_text", accessor: true },\\n	{ name: "selected", getter: "selected", accessor: true },\\n	{ name: "placement", getter: "placement", accessor: true },\\n	{ name: "icon", getter: "icon", setter: "set_icon", accessor: true },\\n	{ name: "closable", getter: "closable", accessor: true },\\n	{ name: "selected_index", getter: "selected_index", accessor: true },\\n	{ name: "selected_path", getter: "selected_path", accessor: true },\\n	{ name: "variant", getter: "variant", accessor: true },\\n];\\n\\nfunction _zpath_widget_class () {\\n	if ( not _widget_class_loaded ) {\\n		_widget_class_loaded := true;\\n		try {\\n			_widget_class := load_module( "std/gui/objects", "Widget" );\\n		}\\n		catch {\\n			_widget_class := null;\\n		}\\n	}\\n	return _widget_class;\\n}\\n\\nfunction _zpath_is_widget ( obj ) {\\n	let Widget := _zpath_widget_class();\\n	return Widget \\u2262 null and obj instanceof Widget;\\n}\\n\\nfunction _zpath_xml_node_type ( obj ) {\\n	return null if not( obj can nodeType );\\n	try {\\n		return int( "" _ obj.nodeType() );\\n	}\\n	catch {\\n	}\\n	return null;\\n}\\n\\nfunction _zpath_is_xml_document ( obj ) {\\n	return true if _zpath_xml_node_type(obj) = 9;\\n	return false if not( obj can documentElement );\\n	try {\\n		obj.documentElement();\\n		return true;\\n	}\\n	catch {\\n	}\\n	return false;\\n}\\n\\nfunction _zpath_is_xml_node ( obj ) {\\n	return true if _zpath_xml_node_type(obj) \\u2262 null;\\n	return _zpath_is_xml_document(obj);\\n}\\n\\nfunction _zpath_widget_attr_name ( name ) {\\n	return ( name ~ /^@/ ) ? substr( name, 1 ) : name;\\n}\\n\\nfunction _zpath_widget_attr_spec ( name ) {\\n	let attr := _zpath_widget_attr_name(name);\\n	return _WIDGET_ATTRS.first( fn spec \\u2192 spec{name} \\u2261 attr );\\n}\\n\\nfunction _zpath_widget_attr_applies ( widget, spec ) {\\n	let attr := spec{name};\\n	if ( attr in [\\n		"id",\\n		"enabled",\\n		"visible",\\n		"width",\\n		"height",\\n		"minwidth",\\n		"minheight",\\n		"maxwidth",\\n		"maxheight",\\n		"classes",\\n	] ) {\\n		return true;\\n	}\\n\\n	switch ( class_name(widget) : eq ) {\\n		case "Window":\\n			return attr in [ "title" ];\\n		case "VBox", "HBox":\\n			return attr in [ "align", "gap", "padding" ];\\n		case "Frame":\\n			return attr in [ "label", "collapsible", "collapsed" ];\\n		case "Label":\\n			return attr in [ "text", "for" ];\\n		case "Text":\\n			return attr in [ "value", "multiline", "readonly", "wrap" ];\\n		case "RichText":\\n			return attr in [ "value", "multiline", "readonly" ];\\n		case "Image":\\n			return attr in [ "src", "alt", "fit" ];\\n		case "Input":\\n			return attr in [\\n				"value",\\n				"placeholder",\\n				"multiline",\\n				"readonly",\\n				"password",\\n				"required",\\n			];\\n		case "DatePicker":\\n			return attr in [ "value", "min", "max", "first_day_of_week" ];\\n		case "Checkbox":\\n			return attr in [ "label", "checked", "indeterminate" ];\\n		case "Radio":\\n			return attr in [ "label", "value", "group", "checked" ];\\n		case "RadioGroup":\\n			return attr in [ "name", "value" ];\\n		case "Select":\\n			return attr in [ "value", "multiple" ];\\n		case "Menu":\\n			return attr in [ "text" ];\\n		case "MenuItem":\\n			return attr in [ "text", "disabled" ];\\n		case "Button":\\n			return attr in [ "text", "variant" ];\\n		case "Separator":\\n			return attr in [ "orientation" ];\\n		case "Slider":\\n			return attr in [ "value", "min", "max", "step", "orientation", "readonly" ];\\n		case "Progress":\\n			return attr in [ "value", "min", "max", "indeterminate", "show_text" ];\\n		case "Tabs":\\n			return attr in [ "selected", "placement" ];\\n		case "Tab":\\n			return attr in [ "title", "value", "icon", "selected", "closable" ];\\n		case "ListView":\\n			return attr in [ "selected_index", "multiple" ];\\n		case "TreeView":\\n			return attr in [ "selected_path", "multiple" ];\\n	}\\n\\n	return false;\\n}\\n\\nfunction _zpath_widget_get_attr ( widget, spec ) {\\n	let getter := spec{getter};\\n	return widget.(getter)();\\n}\\n\\nfunction _zpath_widget_set_attr ( widget, spec, value ) {\\n	let setter := spec.get( "setter", null );\\n	if ( setter \\u2262 null ) {\\n		try {\\n			return widget.(setter)(value);\\n		}\\n		catch {\\n		}\\n	}\\n\\n	let getter := spec{getter};\\n	if ( spec.get( "accessor", false ) ) {\\n		try {\\n			return widget.(getter)(value);\\n		}\\n		catch {\\n		}\\n	}\\n\\n	die `Widget attribute @${spec{name}} is not assignable`;\\n}\\n\\nclass Node {\\n	let raw with set := null;\\n	let parent but weak := null;\\n	let _parent_keepalive := null;\\n	let key := null;\\n	let id := null;\\n	let ix := null;\\n	let tagged with set, has := null;\\n\\n	static method _xml_node_type_code ( value ) {\\n		try {\\n			return int( "" _ value.nodeType() );\\n		}\\n		catch {\\n			return null;\\n		}\\n	}\\n\\n	static method from_root ( obj ) {\\n		return self.wrap(obj);\\n	}\\n\\n	static method wrap ( _obj, parent?, key?, ix? ) {\\n\\n		let obj := _obj;\\n\\n		if ( obj instanceof Node ) {\\n			return obj;\\n		}\\n\\n		let Klass := determine_class( obj );\\n\\n		let n := new Klass(\\n			raw: obj,\\n			parent: parent,\\n			key: key,\\n			ix: ix,\\n		);\\n\\n		if ( obj instanceof TaggedValue ) {\\n			n.set_tagged(obj);\\n			while ( obj instanceof TaggedValue ) {\\n				obj := obj{value}\\n			}\\n			n.set_raw(obj);\\n		}\\n\\n		n._build_id_with_parent(parent);\\n\\n		return n;\\n	}\\n\\n	method hold_parent ( owner ) {\\n		_parent_keepalive := owner;\\n		return self;\\n	}\\n\\n	method _use_ref_as_id () {\\n		return false;\\n	}\\n\\n	method _build_id () {\\n		id := self._generate_id;\\n	}\\n\\n	method _build_id_with_parent ( owner ) {\\n		id := self._generate_id_with_parent(owner);\\n	}\\n\\n	method _generate_id () {\\n		return self._generate_id_with_parent(parent);\\n	}\\n\\n	method _generate_id_with_parent ( owner ) {\\n\\n		if ( self._use_ref_as_id ) {\\n			return "ref:" _ ref_id(raw);\\n		}\\n\\n		if ( owner \\u2261 null ) {\\n			return "root";\\n		}\\n\\n		if ( ix \\u2262 null ) {\\n			if ( key \\u2262 null ) {\\n				return owner.id _ "/" _ key _ "#" _ ix;\\n			}\\n			return owner.id _ "/#" _ ix;\\n		}\\n\\n		if ( key \\u2262 null ) {\\n			return owner.id _ "/" _ key;\\n		}\\n\\n		return "rand:" _ floor( 1000 * 1000 * 1000 * Math.rand() );\\n	}\\n\\n	method raw ()    { return raw; }\\n	method parent () { return parent; }\\n	method key ()    { return key; }\\n	method id ()     { return id; }\\n	method ix ()     { return ix; }\\n	method index ()  { return ix; }\\n	method tagged () { return tagged; }\\n\\n	method type () {\\n		return typeof raw;\\n	}\\n\\n	method value () {\\n		return raw;\\n	}\\n\\n	method primitive_value () {\\n		return raw;\\n	}\\n\\n	method string_value () {\\n		let p := self.primitive_value;\\n		return p \\u2261 null ? null : "" _ p;\\n	}\\n\\n	method number_value () {\\n		let v := self.primitive_value();\\n		return 0 + v if v ~ /^-?(?:[0-9]+(?:\\\\.[0-9]+)?|\\\\.[0-9]+)$/;\\n		return null;\\n	}\\n\\n	method can_have_named_children () {\\n		return false;\\n	}\\n\\n	method can_have_indexed_children () {\\n		return false;\\n	}\\n\\n	method can_have_named_indexed_children () {\\n		return false;\\n	}\\n\\n	method named_child ( name ) {\\n		self.children.first( fn kid \\u2192 kid.key \\u2261 name );\\n	}\\n\\n	method indexed_child ( i ) {\\n		self.children.first( fn kid \\u2192 kid.ix \\u2261 i );\\n	}\\n\\n	method named_indexed_child ( name, i ) {\\n		self.children.first( fn kid \\u2192 kid.ix \\u2261 i and kid.key \\u2261 name );\\n	}\\n\\n	method next_child ( child ) {\\n		let i := child.ix;\\n		return null if i \\u2261 null;\\n		return self.indexed_child( i + 1 );\\n	}\\n\\n	method prev_child ( child ) {\\n		let i := child.ix;\\n		return null if i \\u2261 null;\\n		return null if i = 0;\\n		return self.indexed_child( i - 1 );\\n	}\\n\\n	method next_sibling () {\\n		return self.parent.next_child( self );\\n	}\\n\\n	method prev_sibling () {\\n		return self.parent.prev_child( self );\\n	}\\n\\n	method named_attribute ( name ) {\\n		let attrname := ( name ~ /^@/ ) ? name : `@${name}`;\\n		self.attributes.first( fn kid \\u2192 kid.name \\u2261 attrname );\\n	}\\n\\n	method children () {\\n		return [];\\n	}\\n\\n	method attributes () {\\n		return [];\\n	}\\n\\n	method name () {\\n		return key;\\n	}\\n\\n	method dump () {\\n		return {\\n			"@type": self.type(),\\n			"@id": self.id(),\\n			"@key": self.key(),\\n			"@index": self.index(),\\n			"@value": self.primitive_value(),\\n			children: self.children().map( fn c -> c.dump() ),\\n			attributes: self.attributes().map( fn a -> a.dump() ),\\n		};\\n	}\\n\\n	method find ( zpath ) {\\n		from std/path/z import ZPath;\\n\\n		die "Node.find expects a ZPath object"\\n			unless zpath instanceof ZPath;\\n\\n		return zpath.evaluate(self);\\n	}\\n\\n	method do_action ( action ) {\\n		const container_node := self.parent();\\n		die "Path assignment target has no parent node"\\n			if container_node \\u2261 null;\\n		return container_node.do_action_on_child( self, action );\\n	}\\n\\n	method ref () {\\n		const container_node := self.parent();\\n		die "Path assignment target has no parent node"\\n			if container_node \\u2261 null;\\n		return container_node.ref_on_child(self);\\n	}\\n\\n	method do_action_on_child ( child, action ) {\\n		die `Path assignment target container \\\'${self.type()}\\\' is not assignable`;\\n	}\\n\\n	method ref_on_child ( child ) {\\n		die `Path assignment target container \\\'${self.type()}\\\' is not assignable`;\\n	}\\n}\\n\\nclass SimpleNode extends Node {\\n}\\n\\nclass StringNode extends SimpleNode {\\n\\n	method string_value () {\\n		let raw := self.raw;\\n		if ( raw instanceof BinaryString ) {\\n			return to_string( raw );\\n		}\\n		return raw;\\n	}\\n\\n	method type () {\\n		return "string";\\n	}\\n}\\n\\nclass NumberNode extends SimpleNode {\\n	method number_value () {\\n		let raw := self.raw;\\n		return raw;\\n	}\\n\\n	method type () {\\n		return "number";\\n	}\\n}\\n\\nclass BooleanNode extends SimpleNode {\\n	method type () {\\n		return "boolean";\\n	}\\n}\\n\\nclass NullNode extends SimpleNode {\\n	method type () {\\n		return "null";\\n	}\\n}\\n\\nclass ArrayNode extends Node {\\n\\n	method _use_ref_as_id () {\\n		return true;\\n	}\\n\\n	method type () {\\n		return "list";\\n	}\\n\\n	method children () {\\n		let raw := self.raw;\\n		let out := [];\\n		let i := 0;\\n		while ( i < raw.length ) {\\n			let child := Node.wrap( raw[i], self, null, i );\\n			out.push(child);\\n			i++;\\n		}\\n		return out;\\n	}\\n\\n	method can_have_indexed_children () {\\n		return false;\\n	}\\n\\n	method do_action_on_child ( child, action ) {\\n		return super( child, action ) if action{op} ne ":=";\\n\\n		const ix := child.ix();\\n		die "Path assignment expects numeric array index" if ix \\u2261 null;\\n		let container := self.raw();\\n		container[ix] := action{value};\\n		return action{value};\\n	}\\n\\n	method ref_on_child ( child ) {\\n		const ix := child.ix();\\n		die "Path assignment expects numeric array index" if ix \\u2261 null;\\n		let container := self.raw();\\n		return \\\\ container[ix];\\n	}\\n}\\n\\nclass SetNode extends Node {\\n\\n	method _use_ref_as_id () {\\n		return true;\\n	}\\n\\n	method children () {\\n		let raw := self.raw;\\n		let out := [];\\n		let i := 0;\\n		while ( i < raw.length ) {\\n			let child := Node.wrap( raw[i], self, null, null );\\n			out.push(child);\\n			i++;\\n		}\\n		return out;\\n	}\\n}\\n\\nclass BagNode extends Node {\\n\\n	method _use_ref_as_id () {\\n		return true;\\n	}\\n\\n	method children () {\\n		let raw := self.raw;\\n		let out := [];\\n		let i := 0;\\n		while ( i < raw.length ) {\\n			let child := Node.wrap( raw[i], self, null, null );\\n			out.push(child);\\n			i++;\\n		}\\n		return out;\\n	}\\n}\\n\\nclass DictNode extends Node {\\n\\n	method _use_ref_as_id () {\\n		return true;\\n	}\\n\\n	method type () {\\n		return "map";\\n	}\\n\\n	method children () {\\n		let raw := self.raw;\\n		let out := [];\\n		for ( let k in raw.keys() ) {\\n			let child := Node.wrap( raw.get(k), self, k );\\n			out.push(child);\\n		}\\n		return out;\\n	}\\n\\n	method can_have_named_children () {\\n		return true;\\n	}\\n\\n	method do_action_on_child ( child, action ) {\\n		return super( child, action ) if action{op} ne ":=";\\n\\n		const key := child.key();\\n		die "Path assignment expects string dict key" if key \\u2261 null;\\n		let container := self.raw();\\n		container{(key)} := action{value};\\n		return action{value};\\n	}\\n\\n	method ref_on_child ( child ) {\\n		const key := child.key();\\n		die "Path assignment expects string dict key" if key \\u2261 null;\\n		let container := self.raw();\\n		return \\\\ container{(key)};\\n	}\\n}\\n\\nclass PairListNode extends Node {\\n\\n	method _use_ref_as_id () {\\n		return true;\\n	}\\n\\n	method children () {\\n		let raw := self.raw;\\n		let pairs := raw.to_Array();\\n		let out := [];\\n		let i := 0;\\n		while ( i < pairs.length() ) {\\n			let pair := pairs[i];\\n			out.push( Node.wrap( pair, self, pair.key, i ) );\\n			i++;\\n		}\\n		return out;\\n	}\\n\\n	method can_have_named_children () {\\n		return true;\\n	}\\n\\n	method can_have_indexed_children () {\\n		return true;\\n	}\\n\\n	method can_have_named_indexed_children () {\\n		return true;\\n	}\\n\\n	method named_child ( name ) {\\n		return self.named_indexed_child( name, 0 );\\n	}\\n\\n	method indexed_child ( i ) {\\n		let pairs := self.raw().to_Array();\\n		return null if i < 0 or i >= pairs.length();\\n		let pair := pairs[i];\\n		return Node.wrap( pair, self, pair.key, i );\\n	}\\n\\n	method named_indexed_child ( name, i ) {\\n		let pairs := self.raw().to_Array();\\n		let seen := 0;\\n		let pos := 0;\\n		while ( pos < pairs.length() ) {\\n			let pair := pairs[pos];\\n			if ( pair.key \\u2261 name ) {\\n				if ( seen = i ) {\\n					return Node.wrap( pair, self, pair.key, pos );\\n				}\\n				seen++;\\n			}\\n			pos++;\\n		}\\n		return null;\\n	}\\n\\n	method _replace_value_at ( pair_ix, value ) {\\n		let container := self.raw();\\n		let pairs := container.to_Array();\\n		die "Path assignment expects numeric pairlist index"\\n			if pair_ix \\u2261 null or pair_ix < 0 or pair_ix >= pairs.length();\\n\\n		container.clear();\\n		let i := 0;\\n		while ( i < pairs.length() ) {\\n			let pair := pairs[i];\\n			container.add( pair.key, i = pair_ix ? value : pair.value );\\n			i++;\\n		}\\n		return value;\\n	}\\n\\n	method do_action_on_child ( child, action ) {\\n		return super( child, action ) if action{op} ne ":=";\\n\\n		return self._replace_value_at( child.ix(), action{value} );\\n	}\\n\\n	method ref_on_child ( child ) {\\n		let pair_ix := child.ix();\\n		return function ( ... args ) {\\n			let current := self.indexed_child(pair_ix);\\n			die "Path assignment target pairlist entry no longer exists"\\n				if current \\u2261 null;\\n			return current.raw().value if args.length() = 0;\\n			return self._replace_value_at( pair_ix, args[0] );\\n		};\\n	}\\n}\\n\\nclass PairNode extends Node {\\n\\n	method attributes () {\\n		let raw := self.raw;\\n		return [ "key", "value" ]\\n			.map( fn a \\u2192 Node.wrap( raw.(a)(), self, `@${a}` ) );\\n	}\\n\\n	method do_action_on_child ( child, action ) {\\n		return super( child, action ) if action{op} ne ":=";\\n		return super( child, action ) if child.key() ne "@value";\\n\\n		let container := self.parent();\\n		return super( child, action )\\n			if container \\u2261 null or not ( container instanceof PairListNode );\\n		return container.do_action_on_child( self, action );\\n	}\\n\\n	method ref_on_child ( child ) {\\n		return super(child) if child.key() ne "@value";\\n\\n		let container := self.parent();\\n		return super(child)\\n			if container \\u2261 null or not ( container instanceof PairListNode );\\n		return container.ref_on_child(self);\\n	}\\n}\\n\\nclass KDLDocumentNode extends Node {\\n\\n	method _use_ref_as_id () {\\n		return true;\\n	}\\n\\n	method type () {\\n		return "document";\\n	}\\n\\n	method children () {\\n		let raw := self.raw;\\n		let out := [];\\n		let i := 0;\\n		while ( i < raw.nodes().length() ) {\\n			let child := raw.nodes()[i];\\n			out.push( Node.wrap( child, self, child.name(), i ) );\\n			i++;\\n		}\\n		return out;\\n	}\\n\\n	method can_have_named_children () {\\n		return true;\\n	}\\n\\n	method can_have_indexed_children () {\\n		return true;\\n	}\\n\\n	method can_have_named_indexed_children () {\\n		return true;\\n	}\\n\\n	method indexed_child ( i ) {\\n		return self.children().get( i, null );\\n	}\\n\\n	method named_indexed_child ( name, i ) {\\n		let n := 0;\\n		for ( let child in self.children() ) {\\n			if ( child.key() \\u2261 name ) {\\n				return child if n \\u2261 i;\\n				n++;\\n			}\\n		}\\n		return null;\\n	}\\n}\\n\\nclass KDLNodeNode extends Node {\\n\\n	method _use_ref_as_id () {\\n		return true;\\n	}\\n\\n	method type () {\\n		return "element";\\n	}\\n\\n	method name () {\\n		return self.raw().name();\\n	}\\n\\n	method children () {\\n		let raw := self.raw;\\n		let out := [];\\n		let i := 0;\\n		for ( let arg in raw.args() ) {\\n			out.push( Node.wrap( arg, self, null, i ) );\\n			i++;\\n		}\\n		for ( let child in raw.children() ) {\\n			out.push( Node.wrap( child, self, child.name(), i ) );\\n			i++;\\n		}\\n		return out;\\n	}\\n\\n	method attributes () {\\n		let raw := self.raw;\\n		let out := [];\\n		let i := 0;\\n		for ( let pair in raw.props().to_Array() ) {\\n			out.push( Node.wrap( pair.value, self, "@" _ pair.key, i ) );\\n			i++;\\n		}\\n		return out;\\n	}\\n\\n	method can_have_named_children () {\\n		return true;\\n	}\\n\\n	method can_have_indexed_children () {\\n		return true;\\n	}\\n\\n	method can_have_named_indexed_children () {\\n		return true;\\n	}\\n\\n	method indexed_child ( i ) {\\n		return self.children().get( i, null );\\n	}\\n\\n	method named_indexed_child ( name, i ) {\\n		let n := 0;\\n		for ( let child in self.children() ) {\\n			if ( child.key() \\u2261 name ) {\\n				return child if n \\u2261 i;\\n				n++;\\n			}\\n		}\\n		return null;\\n	}\\n}\\n\\nclass KDLValueNode extends Node {\\n\\n	method type () {\\n		return self.raw().type();\\n	}\\n\\n	method value () {\\n		return self.raw().native_value();\\n	}\\n\\n	method primitive_value () {\\n		return self.raw().native_value();\\n	}\\n\\n	method string_value () {\\n		return self.raw().to_String();\\n	}\\n\\n	method number_value () {\\n		try {\\n			return self.raw().to_Number();\\n		}\\n		catch {\\n			return null;\\n		}\\n	}\\n\\n	method has_tagged () {\\n		return true;\\n	}\\n\\n	method tagged () {\\n		let ann := self.raw().type_annotation();\\n		return {\\n			tag: ann \\u2261 null ? null : "" _ ann,\\n			value: self.raw().native_value(),\\n		};\\n	}\\n}\\n\\nclass XmlNodeNode extends Node {\\n\\n	method _generate_id () {\\n		return\\n			try {\\n				let i := self.raw.unique_id;\\n				i \\u2261 null ? super() : `xml:${i}`;\\n			}\\n			catch {\\n				super();\\n			};\\n	}\\n\\n	method type () {\\n		let raw := self.raw;\\n		if ( _zpath_is_xml_document(raw) ) {\\n			return "document";\\n		}\\n		switch ( Node._xml_node_type_code(raw) ) {\\n			case 1:\\n				return "element";\\n			case 2, 18:\\n				return "attr";\\n			case 3, 4:\\n				return "text";\\n			case 8:\\n				return "comment";\\n			case 9:\\n				return "document";\\n		}\\n\\n		return super();\\n	}\\n\\n	method name () {\\n		let raw := self.raw;\\n		switch ( Node._xml_node_type_code(raw) ) {\\n			case 1:\\n				return raw.nodeName();\\n			case 2, 18:\\n				return "@" _ raw.nodeName();\\n			case 3, 4:\\n				return "#text";\\n		}\\n\\n		return super();\\n	}\\n\\n	method next_child ( child ) {\\n		return child.next_sibling;\\n	}\\n\\n	method prev_child ( child ) {\\n		return child.prev_sibling;\\n	}\\n\\n	method next_sibling () {\\n		let x := self.raw.nextSibling;\\n		return null if x \\u2261 null;\\n		return Node.wrap( x, self.parent, x.nodeName );\\n	}\\n\\n	method prev_sibling () {\\n		let x := self.raw.previousSibling;\\n		return null if x \\u2261 null;\\n		return Node.wrap( x, self.parent, x.nodeName );\\n	}\\n\\n	method primitive_value () {\\n		let raw := self.raw;\\n		if ( _zpath_is_xml_document(raw) ) {\\n			let de := raw.documentElement();\\n			return de \\u2261 null ? null : de.textContent();\\n		}\\n		switch ( Node._xml_node_type_code(raw) ) {\\n			case 1:\\n				return raw.textContent;\\n			case 2, 18:\\n				return raw.nodeValue();\\n			case 3, 4, 8:\\n				return raw.data;\\n			case 9:\\n				let de := raw.documentElement();\\n				return de \\u2261 null ? null : de.textContent();\\n		}\\n\\n		return super();\\n	}\\n\\n	method string_value () {\\n		let raw := self.raw;\\n		if ( _zpath_is_xml_document(raw) ) {\\n			let de := raw.documentElement();\\n			return de \\u2261 null ? null : de.textContent();\\n		}\\n		switch ( Node._xml_node_type_code(raw) ) {\\n			case 1:\\n				return raw.textContent;\\n			case 2, 18:\\n				return raw.nodeValue();\\n			case 3, 4, 8:\\n				return raw.data;\\n			case 9:\\n				let de := raw.documentElement();\\n				return de \\u2261 null ? null : de.textContent();\\n		}\\n\\n		return super();\\n	}\\n\\n	method can_have_named_children () {\\n		return true;\\n	}\\n\\n	method can_have_indexed_children () {\\n		return true;\\n	}\\n\\n	method can_have_named_indexed_children () {\\n		return true;\\n	}\\n\\n	method children () {\\n		let raw := self.raw;\\n		if ( _zpath_is_xml_document(raw) ) {\\n			let de := raw.documentElement();\\n			return de \\u2261 null ? []\\n				: [ Node.wrap( de, self, de.nodeName(), 0 ) ];\\n		}\\n		let node_type := Node._xml_node_type_code(raw);\\n		if ( node_type = 9 ) {\\n			let de := raw.documentElement();\\n			return de \\u2261 null ? []\\n				: [ Node.wrap( de, self, de.nodeName(), 0 ) ];\\n		}\\n\\n		if ( node_type = 1 ) {\\n			let kids := [];\\n			let count := {};\\n			for ( let child in raw.childNodes() ) {\\n				let nm := child.nodeName();\\n				let n := count.exists(nm) ? count.get( nm ) : 0;\\n				count.set( nm, n + 1 );\\n				kids.push( Node.wrap( child, self, nm, n ) );\\n			}\\n			return kids;\\n		}\\n\\n		return [];\\n	}\\n\\n	method attributes () {\\n		let raw := self.raw;\\n		let out := super();\\n		if ( Node._xml_node_type_code(raw) \\u2261 1 ) {\\n			for ( let attr in raw.attributes() ) {\\n				let n := Node.wrap( attr, self, "@" _ attr.nodeName() );\\n				out.push(n);\\n			}\\n		}\\n		return out;\\n	}\\n}\\n\\nclass TimeNode extends Node {\\n\\n	method string_value () {\\n		let raw := self.raw;\\n		return raw.datetime;\\n	}\\n\\n	method number_value () {\\n		let raw := self.raw;\\n		return raw.epoch;\\n	}\\n\\n	method attributes () {\\n		let raw := self.raw;\\n		return [ "year", "month", "day", "hour", "min", "sec" ]\\n			.map( fn a \\u2192 Node.wrap( raw.(a)(), self, `@${a}` ) );\\n	}\\n}\\n\\nclass PathNode extends Node {\\n\\n	method string_value () {\\n		let raw := self.raw;\\n		return raw.to_String;\\n	}\\n\\n	method attributes () {\\n		let raw := self.raw;\\n		if ( raw.is_file ) {\\n			const stat := raw.stat;\\n			return stat.keys.map( fn a \\u2192 Node.wrap( stat{a}, self, `@${a}` ) );\\n		}\\n\\n		return super();\\n	}\\n}\\n\\nclass WidgetNode extends Node {\\n\\n	method _use_ref_as_id () {\\n		return true;\\n	}\\n\\n	method type () {\\n		return "widget";\\n	}\\n\\n	method name () {\\n		return class_name( self.raw() ) or? "Widget";\\n	}\\n\\n	method can_have_named_children () {\\n		return true;\\n	}\\n\\n	method can_have_indexed_children () {\\n		return true;\\n	}\\n\\n	method can_have_named_indexed_children () {\\n		return true;\\n	}\\n\\n	method children () {\\n		let out := [];\\n		let i := 0;\\n		for ( let child in self.raw().children() ) {\\n			let nm := class_name(child) or? "Widget";\\n			out.push( Node.wrap( child, self, nm, i ) );\\n			i++;\\n		}\\n		return out;\\n	}\\n\\n	method indexed_child ( i ) {\\n		return self.children().get( i, null );\\n	}\\n\\n	method named_indexed_child ( name, i ) {\\n		let n := 0;\\n		for ( let child in self.children() ) {\\n			if ( child.key() \\u2261 name ) {\\n				return child if n \\u2261 i;\\n				n++;\\n			}\\n		}\\n		return null;\\n	}\\n\\n	method attributes () {\\n		let raw := self.raw();\\n		let out := [];\\n		let i := 0;\\n		for ( let spec in _WIDGET_ATTRS ) {\\n			next unless _zpath_widget_attr_applies( raw, spec );\\n			try {\\n				let value := _zpath_widget_get_attr( raw, spec );\\n				out.push( Node.wrap( value, self, "@" _ spec{name}, i ) );\\n				i++;\\n			}\\n			catch {\\n			}\\n		}\\n		return out;\\n	}\\n\\n	method do_action_on_child ( child, action ) {\\n		return super( child, action ) if action{op} ne ":=";\\n\\n		let spec := _zpath_widget_attr_spec( child.key() );\\n		return super( child, action ) if spec \\u2261 null;\\n\\n		_zpath_widget_set_attr( self.raw(), spec, action{value} );\\n		return action{value};\\n	}\\n\\n	method ref_on_child ( child ) {\\n		let spec := _zpath_widget_attr_spec( child.key() );\\n		return super(child) if spec \\u2261 null;\\n\\n		let widget := self.raw();\\n		return function ( ... args ) {\\n			if ( args.length() = 0 ) {\\n				return _zpath_widget_get_attr( widget, spec );\\n			}\\n			_zpath_widget_set_attr( widget, spec, args[0] );\\n			return args[0];\\n		};\\n	}\\n}\\n\\n// Need to define the body of this function late so it can refer back to\\n// classes that have been declared.\\n\\nfunction determine_class ( obj ) {\\n	let Klass;\\n\\n	let real_obj := obj;\\n	while ( real_obj instanceof TaggedValue ) {\\n		real_obj := real_obj{value};\\n	}\\n\\n	if ( real_obj instanceof Null ) {\\n		Klass := NullNode;\\n	}\\n	else if ( real_obj instanceof Boolean ) {\\n		Klass := BooleanNode;\\n	}\\n	else if ( real_obj instanceof Number ) {\\n		Klass := NumberNode;\\n	}\\n	else if ( real_obj instanceof String or real_obj instanceof BinaryString ) {\\n		Klass := StringNode;\\n	}\\n	else if ( real_obj instanceof Array ) {\\n		Klass := ArrayNode;\\n	}\\n	else if ( real_obj instanceof Bag ) {\\n		Klass := BagNode;\\n	}\\n	else if ( real_obj instanceof Set ) {\\n		Klass := SetNode;\\n	}\\n	else if ( real_obj instanceof Dict ) {\\n		Klass := DictNode;\\n	}\\n	else if ( real_obj instanceof PairList ) {\\n		Klass := PairListNode;\\n	}\\n	else if ( real_obj instanceof Pair ) {\\n		Klass := PairNode;\\n	}\\n	else if ( real_obj instanceof KDLDocument ) {\\n		Klass := KDLDocumentNode;\\n	}\\n	else if ( real_obj instanceof KDLNode ) {\\n		Klass := KDLNodeNode;\\n	}\\n	else if ( real_obj instanceof KDLValue ) {\\n		Klass := KDLValueNode;\\n	}\\n	else if ( _zpath_is_xml_node(real_obj) ) {\\n		Klass := XmlNodeNode;\\n	}\\n	else if ( real_obj instanceof Time ) {\\n		Klass := TimeNode;\\n	}\\n	else if ( Path and ( real_obj instanceof Path ) ) {\\n		Klass := PathNode;\\n	}\\n	else if ( real_obj instanceof Object ) {\\n		if ( real_obj can __zpath_node_class__ ) {\\n			Klass = real_obj.__zpath_node_class__;\\n		}\\n	}\\n\\n	if ( Klass \\u2261 null and _zpath_is_widget(real_obj) ) {\\n		Klass := WidgetNode;\\n	}\\n\\n	if ( Klass \\u2261 null ) {\\n		Klass := XmlNodeNode if _zpath_is_xml_node(real_obj);\\n	}\\n\\n	// The dispatch probe returns a class object or null.\\n	return Klass ?: Node;\\n}\\n\';\n        virtualFiles["/modules/std/path/z/operators.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/path/z/operators - Operator definitions for ZPath.\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nThis module defines the base ZPath operator model and the standard\\noperator table used by C<std/path/z>.\\n\\n=head1 EXPORTS\\n\\n=head2 Traits\\n\\n=over\\n\\n=item C<EvalHelpers>\\n\\nShared helpers for operator and function definitions.\\n\\n=over\\n\\n=item C<< helper.wrap(value) >>\\n\\nParameters: C<value> is any value. Returns: C<Array>. Wraps C<value> as\\na one-item ZPath node array.\\n\\n=item C<< helper.wrap_for_array(value) >>\\n\\nParameters: C<value> is any value. Returns: C<Node>. Wraps C<value> as a\\nZPath node for array results.\\n\\n=back\\n\\n=back\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<< Operator({ spelling: String, kind: String, precedence: Number, ... }) >>\\n\\nConstructs an operator definition. Returns: C<Operator>.\\n\\n=over\\n\\n=item C<< operator.is_unary() >>, C<< operator.is_binary() >>\\n\\nParameters: none. Returns: C<Boolean>. Reports whether the operator is\\nunary or binary.\\n\\n=item C<< operator.requires_whitespace() >>\\n\\nParameters: none. Returns: C<Boolean>. Reports whether the lexer\\nrequires whitespace around the operator.\\n\\n=item C<< operator.lexer_should_ignore() >>\\n\\nParameters: none. Returns: C<Boolean>. Reports whether the lexer should\\nignore this operator definition.\\n\\n=item C<< operator.is_right_associative() >>\\n\\nParameters: none. Returns: C<Boolean>. Reports whether the operator is\\nright associative.\\n\\n=item C<< operator.char_length() >>\\n\\nParameters: none. Returns: C<Number>. Returns the operator spelling\\nlength.\\n\\n=item C<< operator.precedence_is(lvl) >>\\n\\nParameters: C<lvl> is a precedence level. Returns: C<Boolean>. Returns\\ntrue when the operator has that precedence.\\n\\n=back\\n\\n=back\\n\\n=head2 Constants\\n\\n=over\\n\\n=item C<STANDARD_OPERATORS>\\n\\nType: C<Array>. Standard ZPath operator definitions.\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/path/z/operators >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/path/z/node import Node;\\n\\nfunction _floaty_modulus ( ln, rn ) {\\n	let count := floor( ln / rn ); //\\n	return ln - ( count * rn );\\n}\\n\\ntrait EvalHelpers {\\n	method _handle_numeric_operand ( ev, ctx, expr ) {\\n		const result := ev.eval_expr( expr, ev.nested_ctx( ctx ) );\\n		return 0 unless result.length;\\n		return ev.to_number( result[0] );\\n	}\\n\\n	method _handle_stringy_operand ( ev, ctx, expr ) {\\n		const result := ev.eval_expr( expr, ev.nested_ctx( ctx ) );\\n		return 0 unless result.length;\\n		return ev.to_number( result[0] );\\n	}\\n\\n	method wrap ( value ) {\\n		return [ Node.wrap( value ) ];\\n	}\\n\\n	method wrap_for_array ( value ) {\\n		return Node.wrap( value );\\n	}\\n}\\n\\nclass Operator with EvalHelpers {\\n	let String spelling with get;\\n	let String alias with get, has;\\n	let String kind with get;\\n	let Number precedence with get;\\n	let Boolean unary      := false;\\n	let Boolean require_ws := false;\\n	let Boolean lex_ignore := false;\\n	let Boolean right_assoc := false;\\n	let Function f;\\n\\n	method is_unary () {\\n		return unary;\\n	}\\n\\n	method is_binary () {\\n		return not unary;\\n	}\\n\\n	method requires_whitespace () {\\n		return require_ws;\\n	}\\n\\n	method lexer_should_ignore () {\\n		return lex_ignore;\\n	}\\n\\n	method is_right_associative () {\\n		return right_assoc;\\n	}\\n\\n	method char_length () {\\n		return length spelling;\\n	}\\n\\n	method precedence_is ( lvl ) {\\n		return precedence = lvl;\\n	}\\n}\\n\\nconst STANDARD_OPERATORS := [\\n	new Operator(\\n		spelling: "||",\\n		kind: "OROR",\\n		precedence: 2,\\n		f: function ( op, ev, ast, ctx, left, right ) {\\n			const left_val := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n			if ( left_val.length and ev.truthy( left_val[0] ) ) {\\n				return op.wrap( true );\\n			}\\n			const right_val := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n			if ( right_val.length and ev.truthy( right_val[0] ) ) {\\n				return op.wrap( true );\\n			}\\n			return op.wrap( false );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "&&",\\n		kind: "ANDAND",\\n		precedence: 4,\\n		f: function ( op, ev, ast, ctx, left, right ) {\\n			const left_val := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n			if ( left_val.length and ev.truthy( left_val[0] ) ) {\\n				const right_val := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n				if ( right_val.length and ev.truthy( right_val[0] ) ) {\\n					return op.wrap( true );\\n				}\\n			}\\n			return op.wrap( false );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "==",\\n		kind: "EQEQ",\\n		precedence: 12,\\n		f: function ( op, ev, ast, ctx, left, right ) {\\n			const left_vals  := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n			const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n			let is_eq := false;\\n\\n			if ( left_vals and right_vals ) {\\n				for ( let ln in left_vals ) {\\n					last if is_eq;\\n					for ( let rn in right_vals ) {\\n						last if is_eq;\\n						if ( ev.equals( ln, rn ) ) {\\n							is_eq := true;\\n						}\\n					}\\n				}\\n			}\\n\\n			return op.wrap( is_eq );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "!=",\\n		kind: "NEQ",\\n		precedence: 12,\\n		f: function ( op, ev, ast, ctx, left, right ) {\\n			const left_vals  := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n			const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n			let is_eq := false;\\n\\n			if ( left_vals and right_vals ) {\\n				for ( let ln in left_vals ) {\\n					last if is_eq;\\n					for ( let rn in right_vals ) {\\n						last if is_eq;\\n						if ( ev.equals( ln, rn ) ) {\\n							is_eq := true;\\n						}\\n					}\\n				}\\n			}\\n\\n			return op.wrap( not is_eq );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: ">=",\\n		kind: "GE",\\n		precedence: 14,\\n		f: function ( op, ev, ast, ctx, left, right ) {\\n			let left_val  := op._handle_numeric_operand( ev, ctx, left );\\n			let right_val := op._handle_numeric_operand( ev, ctx, right );\\n			if ( ( left_val \\u2261 null ) or ( right_val \\u2261 null ) ) {\\n				left_val  := op._handle_stringy_operand( ev, ctx, left );\\n				right_val := op._handle_stringy_operand( ev, ctx, right );\\n				return op.wrap( left_val ge right_val );\\n			}\\n			return op.wrap( left_val \\u2265 right_val );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "<=",\\n		kind: "LE",\\n		precedence: 14,\\n		f: function ( op, ev, ast, ctx, left, right ) {\\n			let left_val  := op._handle_numeric_operand( ev, ctx, left );\\n			let right_val := op._handle_numeric_operand( ev, ctx, right );\\n			if ( ( left_val \\u2261 null ) or ( right_val \\u2261 null ) ) {\\n				left_val  := op._handle_stringy_operand( ev, ctx, left );\\n				right_val := op._handle_stringy_operand( ev, ctx, right );\\n				return op.wrap( left_val le right_val );\\n			}\\n			return op.wrap( left_val \\u2264 right_val );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "+",\\n		kind: "PLUS",\\n		require_ws: true,\\n		precedence: 16,\\n		f: function ( op, ev, ast, ctx, left, right ) {\\n			const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n			const right_val := op._handle_numeric_operand( ev, ctx, right );\\n			return op.wrap( left_val + right_val );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "-",\\n		kind: "MINUS",\\n		require_ws: true,\\n		precedence: 16,\\n		f: function ( op, ev, ast, ctx, left, right ) {\\n			const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n			const right_val := op._handle_numeric_operand( ev, ctx, right );\\n			return op.wrap( left_val - right_val );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "%",\\n		kind: "PCT",\\n		require_ws: true,\\n		precedence: 18,\\n		f: function ( op, ev, ast, ctx, left, right ) {\\n			const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n			const right_val := op._handle_numeric_operand( ev, ctx, right );\\n			if ( ( left_val ~ /\\\\./ ) or ( right_val ~ /\\\\./ ) ) {\\n				return op.wrap( _floaty_modulus( left_val, right_val ) );\\n			}\\n			return op.wrap( left_val mod right_val );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "*",\\n		kind: "TIMES",\\n		require_ws: true,\\n		precedence: 18,\\n		lex_ignore: true,\\n		alias: "STAR",\\n		f: function ( op, ev, ast, ctx, left, right ) {\\n			const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n			const right_val := op._handle_numeric_operand( ev, ctx, right );\\n			return op.wrap( left_val \\xD7 right_val );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "/",\\n		kind: "DIVIDE",\\n		require_ws: true,\\n		precedence: 18,\\n		lex_ignore: true,\\n		alias: "SLASH",\\n		f: function ( op, ev, ast, ctx, left, right ) {\\n			const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n			const right_val := op._handle_numeric_operand( ev, ctx, right );\\n			return op.wrap( left_val \\xF7 right_val );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "^",\\n		kind: "BXOR",\\n		precedence: 8,\\n		f: function ( op, ev, ast, ctx, left, right ) {\\n			const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n			const right_val := op._handle_numeric_operand( ev, ctx, right );\\n			return op.wrap( left_val ^ right_val );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "&",\\n		kind: "BAND",\\n		precedence: 10,\\n		f: function ( op, ev, ast, ctx, left, right ) {\\n			const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n			const right_val := op._handle_numeric_operand( ev, ctx, right );\\n			return op.wrap( left_val & right_val );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "|",\\n		kind: "BOR",\\n		precedence: 6,\\n		f: function ( op, ev, ast, ctx, left, right ) {\\n			const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n			const right_val := op._handle_numeric_operand( ev, ctx, right );\\n			return op.wrap( left_val | right_val );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: ">",\\n		kind: "GT",\\n		precedence: 14,\\n		f: function ( op, ev, ast, ctx, left, right ) {\\n			let left_val  := op._handle_numeric_operand( ev, ctx, left );\\n			let right_val := op._handle_numeric_operand( ev, ctx, right );\\n			if ( ( left_val \\u2261 null ) or ( right_val \\u2261 null ) ) {\\n				left_val  := op._handle_stringy_operand( ev, ctx, left );\\n				right_val := op._handle_stringy_operand( ev, ctx, right );\\n				return op.wrap( left_val gt right_val );\\n			}\\n			return op.wrap( left_val > right_val );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "<",\\n		kind: "LT",\\n		precedence: 14,\\n		f: function ( op, ev, ast, ctx, left, right ) {\\n			let left_val  := op._handle_numeric_operand( ev, ctx, left );\\n			let right_val := op._handle_numeric_operand( ev, ctx, right );\\n			if ( ( left_val \\u2261 null ) or ( right_val \\u2261 null ) ) {\\n				left_val  := op._handle_stringy_operand( ev, ctx, left );\\n				right_val := op._handle_stringy_operand( ev, ctx, right );\\n				return op.wrap( left_val le right_val );\\n			}\\n			return op.wrap( left_val < right_val );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "!",\\n		kind: "NOT",\\n		unary: true,\\n		precedence: 20,\\n		f: function ( op, ev, ast, ctx, expr ) {\\n			const got := ev.eval_expr( expr, ctx );\\n			const value := got.length() > 0 ? got[0] : null;\\n			return op.wrap( not ev.truthy(value) );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "~",\\n		kind: "BNOT",\\n		unary: true,\\n		precedence: 20,\\n		f: function ( op, ev, ast, ctx, expr ) {\\n			const value := op._handle_numeric_operand( ev, ctx, expr );\\n			return op.wrap( ~value );\\n		},\\n	),\\n];\\n\';\n        virtualFiles["/modules/std/path/z/parser.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/path/z/parser - Pure Zuzu parser for ZPath expressions.\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nThis module provides the pure-Zuzu parser used by ZPath.\\n\\n=head1 EXPORTS\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<< Parser({ lexer_class?, allowed_operators }) >>\\n\\nConstructs a ZPath parser. Returns: C<Parser>.\\n\\n=over\\n\\n=item C<< parser.parse_top_level_terms(src) >>\\n\\nParameters: C<src> is a ZPath expression string. Returns: C<Array>.\\nParses comma-separated top-level expression terms.\\n\\n=item C<< parser.parse_expression(lx) >>\\n\\nParameters: C<lx> is a C<Lexer>. Returns: C<Dict>. Parses an expression.\\n\\n=item C<< parser.parse_ternary(lx) >>\\n\\nParameters: C<lx> is a C<Lexer>. Returns: C<Dict>. Parses ternary and\\nElvis expressions.\\n\\n=item C<< parser.parse_subexpression(lx, min_prec) >>\\n\\nParameters: C<lx> is a C<Lexer> and C<min_prec> is a precedence floor.\\nReturns: C<Dict>. Parses a precedence-climbing subexpression.\\n\\n=item C<< parser.parse_primary(lx) >>\\n\\nParameters: C<lx> is a C<Lexer>. Returns: C<Dict>. Parses a primary\\nexpression.\\n\\n=back\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/path/z/parser >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/string import trim;\\nfrom std/path/z/lexer import Lexer;\\n\\nclass Parser {\\n	let lexer_class;\\n	let allowed_operators;\\n	let _binop_prec := {};\\n	let _unop_prec  := {};\\n	let _need_ws    := {};\\n	let _right_assoc := {};\\n	let _path_terminators := {};\\n	let _allow_elvis := false;\\n\\n	method __build__ () {\\n		lexer_class ?:= Lexer;\\n		self._init_path_terminators();\\n		for ( let op in allowed_operators ) {\\n			let spell := op.get_spelling();\\n			if ( op.is_unary() ) {\\n				_unop_prec.set( spell, op.get_precedence() );\\n			}\\n			else {\\n				if ( op.get_kind() \\u2261 "ELVIS" ) {\\n					_allow_elvis := true;\\n					_path_terminators.set( op.get_kind(), true );\\n					next;\\n				}\\n				_binop_prec.set( spell, op.get_precedence() );\\n				_path_terminators.set( op.get_kind(), true );\\n				if ( op.has_alias() ) {\\n					_path_terminators.set( op.get_alias(), true );\\n				}\\n				if ( op.requires_whitespace() ) {\\n					_need_ws.set( spell, true );\\n				}\\n				if ( op.is_right_associative() ) {\\n					_right_assoc.set( spell, true );\\n				}\\n			}\\n		}\\n	}\\n\\n	method _init_path_terminators () {\\n		for ( let k in [\\n			"EOF",\\n			"COMMA",\\n			"RPAREN",\\n			"RBRACK",\\n			"QMARK",\\n			"COLON",\\n		] ) {\\n			_path_terminators.set( k, true );\\n		}\\n	}\\n\\n	method parse_top_level_terms ( src ) {\\n		let terms := [];\\n		let lexer := new lexer_class(\\n			src:               src,\\n			allowed_operators: allowed_operators,\\n		);\\n\\n		while ( true ) {\\n			let expr := self.parse_expression(lexer);\\n			terms.push(expr);\\n			if ( lexer.peek_kind() \\u2261 "COMMA" ) {\\n				lexer.next_tok();\\n				next;\\n			}\\n			lexer.expect("EOF");\\n			last;\\n		}\\n\\n		return terms;\\n	}\\n\\n	method _trim ( s ) {\\n		return trim(s);\\n	}\\n\\n	method parse_expression ( lx ) {\\n		return self.parse_ternary(lx);\\n	}\\n\\n	method parse_ternary ( lx ) {\\n		let cond := self.parse_subexpression( lx, 1 );\\n\\n		if ( lx.peek_kind() \\u2261 "QMARK" ) {\\n			lx.next_tok();\\n			let then := self.parse_expression(lx); // ZZPath should use: self.parse_subexpression( lx, 1 )\\n			lx.expect("COLON");\\n			let els := self.parse_expression(lx);\\n			return { t: "ternary", c: cond, a: then, b: els };\\n		}\\n		if ( _allow_elvis and lx.peek_kind() \\u2261 "ELVIS" ) {\\n			lx.next_tok();\\n			let fallback := self.parse_expression(lx);\\n			return { t: "elvis", c: cond, b: fallback };\\n		}\\n\\n		return cond;\\n	}\\n\\n	method parse_subexpression ( lx, min_prec ) {\\n		let left := self._parse_maybe_unary( lx, min_prec );\\n\\n		while ( true ) {\\n			let spell := lx.peek{v};\\n			let op_prec := _binop_prec.get( spell, null );\\n			last if op_prec \\u2261 null or op_prec < min_prec;\\n\\n			let op := lx.next_tok;\\n			if ( _need_ws.exists( spell ) ) {\\n				if ( not ( op{ws_before} and op{ws_after} ) ) {\\n					die `Binary operator \\\'${spell}\\\' requires whitespace around it`;\\n				}\\n			}\\n\\n			let next_min := _right_assoc.exists(spell) ? op_prec : op_prec + 1;\\n			let right := self.parse_subexpression( lx, next_min );\\n			left := { t: "bin", op: spell, l: left, r: right };\\n		}\\n\\n		return left;\\n	}\\n\\n	method _parse_maybe_unary ( lx, min_prec ) {\\n		let spell := lx.peek{v};\\n		let op_prec := _unop_prec.get( spell, null );\\n		if ( op_prec \\u2262 null and op_prec >= min_prec ) {\\n			let op := lx.next_tok{v};\\n			let e  := self._parse_maybe_unary( lx, op_prec );\\n			return { t: "un", op: op, e: e };\\n		}\\n		return self.parse_primary( lx );\\n	}\\n\\n	method parse_primary ( lx ) {\\n		let k := lx.peek_kind;\\n\\n		if ( k \\u2261 "NUMBER" ) {\\n			return { t: "num", v: lx.next_tok(){v} };\\n		}\\n		if ( k \\u2261 "STRING" ) {\\n			return { t: "str", v: lx.next_tok(){v} };\\n		}\\n		if ( k \\u2261 "LPAREN" ) {\\n			lx.next_tok();\\n			let e := self.parse_expression(lx);\\n			lx.expect("RPAREN");\\n			return e;\\n		}\\n\\n		if ( k \\u2261 "NAME" and lx.peek_kind_n(1) \\u2261 "LPAREN" ) {\\n			let name := lx.next_tok(){v};\\n			lx.expect("LPAREN");\\n			let args := [];\\n			if ( lx.peek_kind() \\u2262 "RPAREN" ) {\\n				args.push( self.parse_expression(lx) );\\n				while ( lx.peek_kind() \\u2261 "COMMA" ) {\\n					lx.next_tok();\\n					args.push( self.parse_expression(lx) );\\n				}\\n			}\\n			lx.expect("RPAREN");\\n			return { t: "fn", n: name, a: args };\\n		}\\n\\n		return self._parse_path_expr(lx);\\n	}\\n\\n	method _is_path_terminator ( k ) {\\n		return _path_terminators.exists(k);\\n	}\\n\\n	method _parse_path_expr ( lx ) {\\n		let segs := [];\\n\\n		if ( lx.peek_kind() \\u2261 "SLASH_PATH" ) {\\n			lx.next_tok();\\n			let root := { k: "root", q: [] };\\n			segs.push(root);\\n\\n			if ( lx.peek_kind() \\u2261 "LBRACK" ) {\\n				root{q} := self._parse_qualifiers(lx);\\n			}\\n\\n			if ( self._is_path_terminator( lx.peek_kind() ) ) {\\n				return { t: "path", s: segs };\\n			}\\n		}\\n		else if ( lx.peek_kind() \\u2261 "LBRACK" ) {\\n			let seg := { k: "dot", q: self._parse_qualifiers(lx) };\\n			segs.push(seg);\\n			if ( self._is_path_terminator( lx.peek_kind() ) ) {\\n				return { t: "path", s: segs };\\n			}\\n		}\\n\\n		if (\\n			lx.peek_kind() \\u2262 "SLASH_PATH"\\n			and not self._is_path_terminator( lx.peek_kind() )\\n		) {\\n			segs.push( self._parse_path_segment(lx) );\\n		}\\n\\n		while ( lx.peek_kind() \\u2261 "SLASH_PATH" ) {\\n			lx.next_tok();\\n			if ( lx.peek_kind() \\u2261 "LBRACK" ) {\\n				let seg := { k: "star", q: [] };\\n				seg{q} := self._parse_qualifiers(lx);\\n				segs.push(seg);\\n				next;\\n			}\\n			segs.push( self._parse_path_segment(lx) );\\n		}\\n\\n		return { t: "path", s: segs };\\n	}\\n\\n	method _parse_path_segment ( lx ) {\\n		let k := lx.peek_kind();\\n		let seg := null;\\n\\n		if ( k \\u2261 "DOT" ) {\\n			lx.next_tok();\\n			seg := { k: "dot" };\\n		}\\n		else if ( k \\u2261 "DOTDOT" ) {\\n			lx.next_tok();\\n			seg := { k: "parent" };\\n		}\\n		else if ( k \\u2261 "DOTDOTSTAR" ) {\\n			lx.next_tok();\\n			seg := { k: "ancestors" };\\n		}\\n		else if ( k \\u2261 "STAR_PATH" ) {\\n			lx.next_tok();\\n			seg := { k: "star" };\\n		}\\n		else if ( k \\u2261 "STARSTAR" ) {\\n			lx.next_tok();\\n			seg := { k: "desc" };\\n		}\\n		else if ( k \\u2261 "INDEX" ) {\\n			let i := lx.next_tok(){v};\\n			seg := { k: "index", i: i };\\n		}\\n		else if ( k \\u2261 "NUMBER" ) {\\n			let i := lx.next_tok(){v};\\n			seg := { k: "index", i: i };\\n		}\\n		else if ( k \\u2261 "NAME" and lx.peek_kind_n(1) \\u2261 "LPAREN" ) {\\n			let name := lx.next_tok(){v};\\n			lx.expect("LPAREN");\\n			let args := [];\\n			if ( lx.peek_kind() \\u2262 "RPAREN" ) {\\n				args.push( self.parse_expression(lx) );\\n				while ( lx.peek_kind() \\u2261 "COMMA" ) {\\n					lx.next_tok();\\n					args.push( self.parse_expression(lx) );\\n				}\\n			}\\n			lx.expect("RPAREN");\\n			seg := { k: "fnseg", n: name, a: args };\\n		}\\n		else if ( k \\u2261 "NAME" ) {\\n			let n := lx.next_tok(){v};\\n			seg := { k: "name", n: n };\\n		}\\n		else {\\n			die `Unexpected token in path segment: ${k}`;\\n		}\\n\\n		if ( seg{k} \\u2261 "name" and lx.peek_kind() \\u2261 "INDEX" ) {\\n			seg{i} := lx.next_tok(){v};\\n		}\\n\\n		seg{q} := self._parse_qualifiers(lx);\\n		return seg;\\n	}\\n\\n	method _parse_qualifiers ( lx ) {\\n		let q := [];\\n\\n		while ( lx.peek_kind() \\u2261 "LBRACK" ) {\\n			lx.next_tok();\\n			let e := self.parse_expression(lx);\\n			lx.expect("RBRACK");\\n			q.push(e);\\n		}\\n\\n		return q;\\n	}\\n}\\n\';\n        virtualFiles["/modules/std/path/zz.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/path/zz - ZuzuScript-flavoured path selectors.\\n\\n=head1 SYNOPSIS\\n\\n  from std/path/zz import ZZPath;\\n\\n  let data := { users: [ { name: "Ada" } ] };\\n  say( ( new ZZPath( path: "/users/#0/name" ) ).first(data) );\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nThis module provides the public C<ZZPath> class. It currently reuses the\\nZPath traversal, parser, lexer, assignment, and reference\\nmachinery while routing expression operators through\\nC<std/path/zz/operators> and expression functions through\\nC<std/path/zz/functions>.\\n\\n=head1 EXPORTS\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<ZZEvaluator>\\n\\nEvaluator class that supplies ZZPath operators and functions.\\n\\n=over\\n\\n=item C<< evaluator.operator_definitions() >>\\n\\nParameters: none. Returns: C<Array>. Returns ZZPath operator\\ndefinitions.\\n\\n=item C<< evaluator.function_definitions() >>\\n\\nParameters: none. Returns: C<Array>. Returns ZZPath function\\ndefinitions.\\n\\n=back\\n\\n=item C<< ZZPath({ path: String }) >>\\n\\nConstructs a ZZPath query object. Returns: C<ZZPath>. Inherits the\\npublic query, assignment, and reference methods from C<ZPath>.\\n\\n=over\\n\\n=item C<< path.get_evaluator() >>\\n\\nParameters: none. Returns: C<ZZEvaluator>. Returns the evaluator used\\nfor this path.\\n\\n=item C<< node.find(path) >>\\n\\nC<ZZPath> inherits from C<ZPath>, so a C<ZZPath> object can be passed to\\nC<std/path/z/node> C<Node.find()>.\\n\\n=back\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/path/zz >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/path/z import ZPath;\\nfrom std/path/z/evaluate import Evaluator as ZEvaluator;\\n\\nclass ZZEvaluator extends ZEvaluator {\\n	method operator_definitions () {\\n		from std/path/zz/operators import STANDARD_OPERATORS;\\n		return STANDARD_OPERATORS;\\n	}\\n\\n	method function_definitions () {\\n		from std/path/zz/functions import STANDARD_FUNCTIONS;\\n		return STANDARD_FUNCTIONS;\\n	}\\n}\\n\\nclass ZZPath extends ZPath {\\n	method get_evaluator () {\\n		return new ZZEvaluator();\\n	}\\n}\\n\';\n        virtualFiles["/modules/std/path/zz/functions.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/path/zz/functions - Function definitions for ZZPath expressions.\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nThis module extends the base ZPath function table with\\nZuzuScript-flavoured path expression helpers.\\n\\n=head1 EXPORTS\\n\\n=head2 Constants\\n\\n=over\\n\\n=item C<STANDARD_FUNCTION_NAMES>\\n\\nType: C<Array>. Names of inherited ZPath functions available to ZZPath.\\n\\n=item C<STANDARD_FUNCTIONS>\\n\\nType: C<Array>. Complete ZZPath function definition table.\\n\\n=back\\n\\n=head2 Functions\\n\\n=over\\n\\n=item C<< first_arg_node(name, ev, ctx, args) >>\\n\\nParameters: function name, evaluator, context, and argument AST nodes.\\nReturns: C<Node> or C<null>. Resolves the first argument or current\\ncontext node.\\n\\n=item C<< first_number_arg(name, ev, ctx, args) >>, C<< nth_number_arg(name, ev, ctx, args, i) >>\\n\\nParameters: function name, evaluator, context, arguments, and optional\\nindex. Returns: C<Number>. Resolves an argument as a number.\\n\\n=item C<< first_string_arg(name, ev, ctx, args) >>, C<< nth_string_arg(name, ev, ctx, args, i) >>\\n\\nParameters: function name, evaluator, context, arguments, and optional\\nindex. Returns: C<String>. Resolves an argument as a string.\\n\\n=item C<< nth_value_arg(name, ev, ctx, args, i) >>\\n\\nParameters: function name, evaluator, context, arguments, and index.\\nReturns: value. Resolves an argument as a primitive value.\\n\\n=item C<< nth_array_arg(name, ev, ctx, args, i) >>\\n\\nParameters: function name, evaluator, context, arguments, and index.\\nReturns: C<Array>. Resolves an argument as an array value.\\n\\n=item C<< number_args(ev, ctx, args) >>\\n\\nParameters: evaluator, context, and argument AST nodes. Returns:\\nC<Array>. Resolves all arguments as numbers.\\n\\n=item C<< first_arg_value(name, ev, ctx, args) >>\\n\\nParameters: function name, evaluator, context, and arguments. Returns:\\nvalue. Resolves the first argument as a primitive value.\\n\\n=item C<< z_function(spelling) >>\\n\\nParameters: C<spelling> is a base ZPath function name. Returns:\\nC<Function>. Returns the inherited function implementation.\\n\\n=item C<< string_index_of(funk, ev, ast, ctx, args) >>\\n\\nParameters: standard ZPath function callback arguments. Returns:\\nC<Array>. Implements string C<index-of>.\\n\\n=item C<< string_rindex(funk, ev, ast, ctx, args) >>\\n\\nParameters: standard ZPath function callback arguments. Returns:\\nC<Array>. Implements string reverse-index lookup.\\n\\n=item C<< defined_function(funk, ev, ast, ctx, args) >>\\n\\nParameters: standard ZPath function callback arguments. Returns:\\nC<Array>. Implements defined-value testing.\\n\\n=item C<< empty_function(funk, ev, ast, ctx, args) >>\\n\\nParameters: standard ZPath function callback arguments. Returns:\\nC<Array>. Implements empty-value testing.\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/path/zz/functions >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/path/z/functions import Func, STANDARD_FUNCTIONS as Z_STANDARD_FUNCTIONS;\\n\\n\\nconst STANDARD_FUNCTION_NAMES := [\\n	"true",\\n	"false",\\n	"null",\\n	"tag",\\n	"url",\\n	"local-name",\\n	"key",\\n	"value",\\n	"index",\\n	"count",\\n	"is-first",\\n	"is-last",\\n	"next",\\n	"prev",\\n];\\n\\nfunction first_arg_node ( name, ev, ctx, args ) {\\n	if ( args.length() = 0 ) {\\n		return ctx.nodeset.get( 0, null );\\n	}\\n	if ( args.length() = 1 ) {\\n		const got := ev.eval_expr( args[0], ev.nested_ctx( ctx ) );\\n		return got.get( 0, null );\\n	}\\n	die `Too many arguments for ${name}()`;\\n}\\n\\nfunction first_number_arg ( name, ev, ctx, args ) {\\n	const node := first_arg_node( name, ev, ctx, args );\\n	// Numeric coercion may produce 0; only null falls back.\\n	return ev.to_number(node) ?: 0;\\n}\\n\\nfunction nth_number_arg ( name, ev, ctx, args, i ) {\\n	die `Not enough arguments for ${name}()` if args.length() <= i;\\n	const got := ev.eval_expr( args[i], ev.nested_ctx( ctx ) );\\n	// Numeric coercion may produce 0; only null falls back.\\n	return ev.to_number( got.get( 0, null ) ) ?: 0;\\n}\\n\\nfunction nth_string_arg ( name, ev, ctx, args, i ) {\\n	die `Not enough arguments for ${name}()` if args.length() <= i;\\n	const got := ev.eval_expr( args[i], ev.nested_ctx( ctx ) );\\n	const value := ev.to_string( got.get( 0, null ) );\\n	return value \\u2261 null ? "" : "" _ value;\\n}\\n\\nfunction nth_value_arg ( name, ev, ctx, args, i ) {\\n	die `Not enough arguments for ${name}()` if args.length() <= i;\\n	const got := ev.eval_expr( args[i], ev.nested_ctx( ctx ) );\\n	const node := got.get( 0, null );\\n	return node \\u2261 null ? null : node.primitive_value();\\n}\\n\\nfunction nth_array_arg ( name, ev, ctx, args, i ) {\\n	die `Not enough arguments for ${name}()` if args.length() <= i;\\n	const got := ev.eval_expr( args[i], ev.nested_ctx( ctx ) );\\n	if ( got.length() = 1 ) {\\n		const one := got[0].primitive_value();\\n		return one if one instanceof Array;\\n	}\\n	return got.map( fn node \\u2192 node.primitive_value() );\\n}\\n\\nfunction number_args ( ev, ctx, args ) {\\n	let nums := [];\\n	if ( args.length() = 0 ) {\\n		for ( let node in ctx.nodeset ) {\\n			const value := ev.to_number(node);\\n			nums.push(value) if value instanceof Number;\\n		}\\n		return nums;\\n	}\\n	for ( let arg in args ) {\\n		const got := ev.eval_expr( arg, ev.nested_ctx( ctx ) );\\n		for ( let node in got ) {\\n			const value := ev.to_number(node);\\n			nums.push(value) if value instanceof Number;\\n		}\\n	}\\n	return nums;\\n}\\n\\nfunction first_string_arg ( name, ev, ctx, args ) {\\n	const node := first_arg_node( name, ev, ctx, args );\\n	const value := ev.to_string(node);\\n	return value \\u2261 null ? "" : "" _ value;\\n}\\n\\nfunction first_arg_value ( name, ev, ctx, args ) {\\n	const node := first_arg_node( name, ev, ctx, args );\\n	return node \\u2261 null ? null : node.primitive_value();\\n}\\n\\nfunction z_function ( spelling ) {\\n	const func := Z_STANDARD_FUNCTIONS.first( fn f \\u2192 f.has_name(spelling) );\\n	die `std/path/z/functions is missing ${spelling}()` if func \\u2261 null;\\n	return func;\\n}\\n\\nfunction string_index_of ( funk, ev, ast, ctx, args ) {\\n	from std/string import index;\\n	die "Too many arguments for index-of()" if args.length() > 3;\\n	if ( args.length() = 2 ) {\\n		return funk.wrap( index(\\n			nth_string_arg( "index-of", ev, ctx, args, 0 ),\\n			nth_string_arg( "index-of", ev, ctx, args, 1 ),\\n		) );\\n	}\\n	return funk.wrap( index(\\n		nth_string_arg( "index-of", ev, ctx, args, 0 ),\\n		nth_string_arg( "index-of", ev, ctx, args, 1 ),\\n		nth_number_arg( "index-of", ev, ctx, args, 2 ),\\n	) );\\n}\\n\\nfunction string_rindex ( funk, ev, ast, ctx, args ) {\\n	from std/string import rindex;\\n	const name := funk.get_spelling;\\n	die `Too many arguments for ${name}()` if args.length() > 3;\\n	if ( args.length() = 2 ) {\\n		return funk.wrap( rindex(\\n			nth_string_arg( name, ev, ctx, args, 0 ),\\n			nth_string_arg( name, ev, ctx, args, 1 ),\\n		) );\\n	}\\n	return funk.wrap( rindex(\\n		nth_string_arg( name, ev, ctx, args, 0 ),\\n		nth_string_arg( name, ev, ctx, args, 1 ),\\n		nth_number_arg( name, ev, ctx, args, 2 ),\\n	) );\\n}\\n\\nfunction defined_function ( funk, ev, ast, ctx, args ) {\\n	const node := first_arg_node( "defined", ev, ctx, args );\\n	return funk.wrap( node \\u2262 null and node.primitive_value() \\u2262 null );\\n}\\n\\nfunction empty_function ( funk, ev, ast, ctx, args ) {\\n	const value := first_arg_value( "empty", ev, ctx, args );\\n	return funk.wrap( true ) if value \\u2261 null;\\n\\n	if (\\n		value instanceof Array or\\n		value instanceof Bag or\\n		value instanceof Set or\\n		value instanceof Dict or\\n		value instanceof PairList\\n	) {\\n		return funk.wrap( value.length() = 0 );\\n	}\\n\\n	die `empty() expects a Collection or null, got ${typeof value}`;\\n}\\n\\n// Start with a base of functions inherited from ZPath:\\nconst STANDARD_FUNCTIONS := STANDARD_FUNCTION_NAMES.map( fn n \\u2192 z_function(n) );\\n\\n// Add equivalents for ZuzuScript word-like unary operators:\\nSTANDARD_FUNCTIONS.push(\\n	new Func(\\n		spelling: "abs",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			return funk.wrap( abs first_number_arg( "abs", ev, ctx, args ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "floor",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			return funk.wrap( floor first_number_arg( "floor", ev, ctx, args ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "ceil",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			return funk.wrap( ceil first_number_arg( "ceil", ev, ctx, args ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "round",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			return funk.wrap( round first_number_arg( "round", ev, ctx, args ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "int",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			return funk.wrap( int first_number_arg( "int", ev, ctx, args ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "sqrt",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			return funk.wrap( sqrt first_number_arg( "sqrt", ev, ctx, args ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "uc",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			return funk.wrap( uc first_string_arg( "uc", ev, ctx, args ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "lc",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			return funk.wrap( lc first_string_arg( "lc", ev, ctx, args ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "length",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			return funk.wrap( length first_string_arg( "length", ev, ctx, args ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "not",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			const node := first_arg_node( "not", ev, ctx, args );\\n			return funk.wrap( not ev.truthy(node) );\\n		},\\n	),\\n	new Func(\\n		spelling: "typeof",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			const node := first_arg_node( "typeof", ev, ctx, args );\\n			const value := node \\u2261 null ? null : node.primitive_value();\\n			return funk.wrap( typeof value );\\n		},\\n	),\\n	new Func(\\n		spelling: "defined",\\n		f: defined_function,\\n	),\\n	new Func(\\n		spelling: "empty",\\n		f: empty_function,\\n	),\\n);\\n\\n// Functions from std/internals:\\nSTANDARD_FUNCTIONS.push(\\n	new Func(\\n		spelling: "string",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/internals import to_String;\\n			return funk.wrap( to_String( first_arg_value(\\n				"string",\\n				ev,\\n				ctx,\\n				args,\\n			) ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "number",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/internals import to_Number;\\n			return funk.wrap( to_Number( first_arg_value(\\n				"number",\\n				ev,\\n				ctx,\\n				args,\\n			) ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "boolean",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/internals import to_Boolean;\\n			return funk.wrap( to_Boolean( first_arg_value(\\n				"boolean",\\n				ev,\\n				ctx,\\n				args,\\n			) ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "regexp",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/internals import to_Regexp;\\n			return funk.wrap( to_Regexp( first_arg_value(\\n				"regexp",\\n				ev,\\n				ctx,\\n				args,\\n			) ) );\\n		},\\n	),\\n);\\n\\n// Functions from std/math:\\nSTANDARD_FUNCTIONS.push(\\n	new Func(\\n		spelling: "sum",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/math import Math;\\n			return funk.wrap( Math.sum( number_args( ev, ctx, args ) ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "min",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/math import Math;\\n			return funk.wrap( Math.min( number_args( ev, ctx, args ) ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "max",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/math import Math;\\n			return funk.wrap( Math.max( number_args( ev, ctx, args ) ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "clamp",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/math import Math;\\n			die "Too many arguments for clamp()" if args.length() > 3;\\n			return funk.wrap( Math.clamp(\\n				nth_number_arg( "clamp", ev, ctx, args, 0 ),\\n				nth_number_arg( "clamp", ev, ctx, args, 1 ),\\n				nth_number_arg( "clamp", ev, ctx, args, 2 ),\\n			) );\\n		},\\n	),\\n);\\n\\n// Functions from std/string:\\nSTANDARD_FUNCTIONS.push(\\n	new Func(\\n		spelling: "substr",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import substr;\\n			die "Too many arguments for substr()" if args.length() > 3;\\n			if ( args.length() = 2 ) {\\n				return funk.wrap( substr(\\n					nth_string_arg( "substr", ev, ctx, args, 0 ),\\n					nth_number_arg( "substr", ev, ctx, args, 1 ),\\n				) );\\n			}\\n			return funk.wrap( substr(\\n				nth_string_arg( "substr", ev, ctx, args, 0 ),\\n				nth_number_arg( "substr", ev, ctx, args, 1 ),\\n				nth_number_arg( "substr", ev, ctx, args, 2 ),\\n			) );\\n		},\\n	),\\n	new Func(\\n		spelling: "index-of",\\n		f: string_index_of,\\n	),\\n	new Func(\\n		spelling: "rindex",\\n		f: string_rindex,\\n	),\\n	new Func(\\n		spelling: "last-index-of",\\n		f: string_rindex,\\n	),\\n	new Func(\\n		spelling: "contains",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import contains;\\n			die "Too many arguments for contains()" if args.length() > 2;\\n			return funk.wrap( contains(\\n				nth_string_arg( "contains", ev, ctx, args, 0 ),\\n				nth_string_arg( "contains", ev, ctx, args, 1 ),\\n			) );\\n		},\\n	),\\n	new Func(\\n		spelling: "chr",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import chr;\\n			die "Too many arguments for chr()" if args.length() > 1;\\n			return funk.wrap( chr( nth_number_arg(\\n				"chr",\\n				ev,\\n				ctx,\\n				args,\\n				0,\\n			) ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "ord",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import ord;\\n			die "Too many arguments for ord()" if args.length() > 2;\\n			if ( args.length() = 1 ) {\\n				return funk.wrap( ord( nth_string_arg(\\n					"ord",\\n					ev,\\n					ctx,\\n					args,\\n					0,\\n				) ) );\\n			}\\n			return funk.wrap( ord(\\n				nth_string_arg( "ord", ev, ctx, args, 0 ),\\n				nth_number_arg( "ord", ev, ctx, args, 1 ),\\n			) );\\n		},\\n	),\\n	new Func(\\n		spelling: "replace",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import replace;\\n			die "Too many arguments for replace()" if args.length() > 4;\\n			if ( args.length() = 3 ) {\\n				return funk.wrap( replace(\\n					nth_string_arg( "replace", ev, ctx, args, 0 ),\\n					nth_value_arg( "replace", ev, ctx, args, 1 ),\\n					nth_string_arg( "replace", ev, ctx, args, 2 ),\\n				) );\\n			}\\n			return funk.wrap( replace(\\n				nth_string_arg( "replace", ev, ctx, args, 0 ),\\n				nth_value_arg( "replace", ev, ctx, args, 1 ),\\n				nth_string_arg( "replace", ev, ctx, args, 2 ),\\n				nth_string_arg( "replace", ev, ctx, args, 3 ),\\n			) );\\n		},\\n	),\\n	new Func(\\n		spelling: "search",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import search;\\n			die "Too many arguments for search()" if args.length() > 3;\\n			if ( args.length() = 2 ) {\\n				return funk.wrap( search(\\n					nth_string_arg( "search", ev, ctx, args, 0 ),\\n					nth_value_arg( "search", ev, ctx, args, 1 ),\\n				) );\\n			}\\n			return funk.wrap( search(\\n				nth_string_arg( "search", ev, ctx, args, 0 ),\\n				nth_value_arg( "search", ev, ctx, args, 1 ),\\n				nth_string_arg( "search", ev, ctx, args, 2 ),\\n			) );\\n		},\\n	),\\n	new Func(\\n		spelling: "starts_with",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import starts_with;\\n			die "Too many arguments for starts_with()" if args.length() > 2;\\n			return funk.wrap( starts_with(\\n				nth_string_arg( "starts_with", ev, ctx, args, 0 ),\\n				nth_string_arg( "starts_with", ev, ctx, args, 1 ),\\n			) );\\n		},\\n	),\\n	new Func(\\n		spelling: "ends_with",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import ends_with;\\n			die "Too many arguments for ends_with()" if args.length() > 2;\\n			return funk.wrap( ends_with(\\n				nth_string_arg( "ends_with", ev, ctx, args, 0 ),\\n				nth_string_arg( "ends_with", ev, ctx, args, 1 ),\\n			) );\\n		},\\n	),\\n	new Func(\\n		spelling: "matches",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import matches;\\n			die "Too many arguments for matches()" if args.length() > 3;\\n			if ( args.length() = 2 ) {\\n				return funk.wrap( matches(\\n					nth_string_arg( "matches", ev, ctx, args, 0 ),\\n					nth_value_arg( "matches", ev, ctx, args, 1 ),\\n				) );\\n			}\\n			return funk.wrap( matches(\\n				nth_string_arg( "matches", ev, ctx, args, 0 ),\\n				nth_value_arg( "matches", ev, ctx, args, 1 ),\\n				nth_string_arg( "matches", ev, ctx, args, 2 ),\\n			) );\\n		},\\n	),\\n	new Func(\\n		spelling: "pattern_to_regexp",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import pattern_to_regexp;\\n			die "Too many arguments for pattern_to_regexp()"\\n				if args.length() > 2;\\n			if ( args.length() = 1 ) {\\n				return funk.wrap( pattern_to_regexp(\\n					nth_string_arg( "pattern_to_regexp", ev, ctx, args, 0 ),\\n				) );\\n			}\\n			return funk.wrap( pattern_to_regexp(\\n				nth_string_arg( "pattern_to_regexp", ev, ctx, args, 0 ),\\n				nth_value_arg( "pattern_to_regexp", ev, ctx, args, 1 ),\\n			) );\\n		},\\n	),\\n	new Func(\\n		spelling: "quotemeta",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import quotemeta;\\n			die "Too many arguments for quotemeta()" if args.length() > 1;\\n			return funk.wrap( quotemeta(\\n				nth_string_arg( "quotemeta", ev, ctx, args, 0 ),\\n			) );\\n		},\\n	),\\n	new Func(\\n		spelling: "sprint",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import sprint;\\n			die "Not enough arguments for sprint()" if args.length() = 0;\\n			die "Too many arguments for sprint()" if args.length() > 8;\\n\\n			const fmt := nth_string_arg( "sprint", ev, ctx, args, 0 );\\n			if ( args.length() = 1 ) {\\n				return funk.wrap( sprint(fmt) );\\n			}\\n			if ( args.length() = 2 ) {\\n				return funk.wrap( sprint(\\n					fmt,\\n					nth_value_arg( "sprint", ev, ctx, args, 1 ),\\n				) );\\n			}\\n			if ( args.length() = 3 ) {\\n				return funk.wrap( sprint(\\n					fmt,\\n					nth_value_arg( "sprint", ev, ctx, args, 1 ),\\n					nth_value_arg( "sprint", ev, ctx, args, 2 ),\\n				) );\\n			}\\n			if ( args.length() = 4 ) {\\n				return funk.wrap( sprint(\\n					fmt,\\n					nth_value_arg( "sprint", ev, ctx, args, 1 ),\\n					nth_value_arg( "sprint", ev, ctx, args, 2 ),\\n					nth_value_arg( "sprint", ev, ctx, args, 3 ),\\n				) );\\n			}\\n			if ( args.length() = 5 ) {\\n				return funk.wrap( sprint(\\n					fmt,\\n					nth_value_arg( "sprint", ev, ctx, args, 1 ),\\n					nth_value_arg( "sprint", ev, ctx, args, 2 ),\\n					nth_value_arg( "sprint", ev, ctx, args, 3 ),\\n					nth_value_arg( "sprint", ev, ctx, args, 4 ),\\n				) );\\n			}\\n			if ( args.length() = 6 ) {\\n				return funk.wrap( sprint(\\n					fmt,\\n					nth_value_arg( "sprint", ev, ctx, args, 1 ),\\n					nth_value_arg( "sprint", ev, ctx, args, 2 ),\\n					nth_value_arg( "sprint", ev, ctx, args, 3 ),\\n					nth_value_arg( "sprint", ev, ctx, args, 4 ),\\n					nth_value_arg( "sprint", ev, ctx, args, 5 ),\\n				) );\\n			}\\n			if ( args.length() = 7 ) {\\n				return funk.wrap( sprint(\\n					fmt,\\n					nth_value_arg( "sprint", ev, ctx, args, 1 ),\\n					nth_value_arg( "sprint", ev, ctx, args, 2 ),\\n					nth_value_arg( "sprint", ev, ctx, args, 3 ),\\n					nth_value_arg( "sprint", ev, ctx, args, 4 ),\\n					nth_value_arg( "sprint", ev, ctx, args, 5 ),\\n					nth_value_arg( "sprint", ev, ctx, args, 6 ),\\n				) );\\n			}\\n			return funk.wrap( sprint(\\n				fmt,\\n				nth_value_arg( "sprint", ev, ctx, args, 1 ),\\n				nth_value_arg( "sprint", ev, ctx, args, 2 ),\\n				nth_value_arg( "sprint", ev, ctx, args, 3 ),\\n				nth_value_arg( "sprint", ev, ctx, args, 4 ),\\n				nth_value_arg( "sprint", ev, ctx, args, 5 ),\\n				nth_value_arg( "sprint", ev, ctx, args, 6 ),\\n				nth_value_arg( "sprint", ev, ctx, args, 7 ),\\n			) );\\n		},\\n	),\\n	new Func(\\n		spelling: "split",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import split;\\n			die "Too many arguments for split()" if args.length() > 3;\\n			if ( args.length() = 2 ) {\\n				return funk.wrap( split(\\n					nth_string_arg( "split", ev, ctx, args, 0 ),\\n					nth_value_arg( "split", ev, ctx, args, 1 ),\\n				) );\\n			}\\n			return funk.wrap( split(\\n				nth_string_arg( "split", ev, ctx, args, 0 ),\\n				nth_value_arg( "split", ev, ctx, args, 1 ),\\n				nth_number_arg( "split", ev, ctx, args, 2 ),\\n			) );\\n		},\\n	),\\n	new Func(\\n		spelling: "join",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import join;\\n			die "Too many arguments for join()" if args.length() > 2;\\n			return funk.wrap( join(\\n				nth_string_arg( "join", ev, ctx, args, 0 ),\\n				nth_array_arg( "join", ev, ctx, args, 1 ),\\n			) );\\n		},\\n	),\\n	new Func(\\n		spelling: "trim",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import trim;\\n			die "Too many arguments for trim()" if args.length() > 1;\\n			return funk.wrap( trim( first_string_arg(\\n				"trim",\\n				ev,\\n				ctx,\\n				args,\\n			) ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "pad",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import pad;\\n			die "Too many arguments for pad()" if args.length() > 4;\\n			if ( args.length() = 2 ) {\\n				return funk.wrap( pad(\\n					nth_string_arg( "pad", ev, ctx, args, 0 ),\\n					nth_number_arg( "pad", ev, ctx, args, 1 ),\\n				) );\\n			}\\n			if ( args.length() = 3 ) {\\n				return funk.wrap( pad(\\n					nth_string_arg( "pad", ev, ctx, args, 0 ),\\n					nth_number_arg( "pad", ev, ctx, args, 1 ),\\n					nth_string_arg( "pad", ev, ctx, args, 2 ),\\n				) );\\n			}\\n			return funk.wrap( pad(\\n				nth_string_arg( "pad", ev, ctx, args, 0 ),\\n				nth_number_arg( "pad", ev, ctx, args, 1 ),\\n				nth_string_arg( "pad", ev, ctx, args, 2 ),\\n				nth_string_arg( "pad", ev, ctx, args, 3 ),\\n			) );\\n		},\\n	),\\n	new Func(\\n		spelling: "chomp",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import chomp;\\n			die "Too many arguments for chomp()" if args.length() > 1;\\n			return funk.wrap( chomp( first_string_arg(\\n				"chomp",\\n				ev,\\n				ctx,\\n				args,\\n			) ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "title",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import title;\\n			die "Too many arguments for title()" if args.length() > 1;\\n			return funk.wrap( title( first_string_arg(\\n				"title",\\n				ev,\\n				ctx,\\n				args,\\n			) ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "snake",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import snake;\\n			die "Too many arguments for snake()" if args.length() > 1;\\n			return funk.wrap( snake( first_string_arg(\\n				"snake",\\n				ev,\\n				ctx,\\n				args,\\n			) ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "kebab",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import kebab;\\n			die "Too many arguments for kebab()" if args.length() > 1;\\n			return funk.wrap( kebab( first_string_arg(\\n				"kebab",\\n				ev,\\n				ctx,\\n				args,\\n			) ) );\\n		},\\n	),\\n	new Func(\\n		spelling: "camel",\\n		f: function ( funk, ev, ast, ctx, args ) {\\n			from std/string import camel;\\n			die "Too many arguments for camel()" if args.length() > 1;\\n			return funk.wrap( camel( first_string_arg(\\n				"camel",\\n				ev,\\n				ctx,\\n				args,\\n			) ) );\\n		},\\n	),\\n);\\n\';\n        virtualFiles["/modules/std/path/zz/operators.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/path/zz/operators - Operator definitions for ZZPath expressions.\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by all implementations of ZuzuScript.\\n\\n=head1 DESCRIPTION\\n\\nThis module extends the base ZPath operator model with\\nZuzuScript-flavoured expression operators.\\n\\n=head1 EXPORTS\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<Operator>\\n\\nZZPath operator class extending C<std/path/z/operators> C<Operator>.\\n\\n=back\\n\\n=head2 Functions\\n\\n=over\\n\\n=item C<< string_operand(ev, ctx, expr) >>, C<< string_operands(ev, ctx, left, right) >>\\n\\nParameters: evaluator, context, and expression AST nodes. Returns:\\nC<String> or C<Array>. Evaluates one or two operands as strings.\\n\\n=item C<< first_eval_value(values) >>, C<< primitive_eval_value(values) >>\\n\\nParameters: C<values> is an evaluated node array. Returns: value.\\nExtracts the first or primitive value used by ZZPath operators.\\n\\n=item C<< collection_operand(ev, ctx, expr) >>\\n\\nParameters: evaluator, context, and expression AST node. Returns:\\ncollection value. Evaluates an operand for collection operators.\\n\\n=item C<< builtin_can(value, method_name) >>\\n\\nParameters: C<value> is any value and C<method_name> is a method name.\\nReturns: C<Boolean>. Tests whether built-in values support a method.\\n\\n=back\\n\\n=head2 Constants\\n\\n=over\\n\\n=item C<STANDARD_OPERATORS>\\n\\nType: C<Array>. Complete ZZPath operator definition table.\\n\\n=item C<logical_negation>, C<logical_and>, C<logical_nand>, C<logical_butnot>, C<logical_xor>, C<logical_nor>, C<logical_xnor>, C<logical_onlyif>, C<logical_or>, C<logical_and_value>, C<logical_nand_value>, C<logical_butnot_value>, C<logical_xor_value>, C<logical_nor_value>, C<logical_xnor_value>, C<logical_onlyif_value>, C<logical_or_value>\\n\\nType: C<Function>. Logical operator implementations.\\n\\n=item C<numeric_power>, C<numeric_multiplication>, C<numeric_division>, C<numeric_modulus>, C<numeric_addition>, C<numeric_subtraction>, C<numeric_left_shift>, C<numeric_right_shift>, C<numeric_equality>, C<numeric_inequality>, C<numeric_less_than>, C<numeric_greater_than>, C<numeric_less_than_or_equal>, C<numeric_greater_than_or_equal>, C<numeric_compare>, C<numeric_divides>, C<numeric_not_divides>\\n\\nType: C<Function>. Numeric operator implementations.\\n\\n=item C<string_concatenation>, C<string_equality>, C<string_inequality>, C<string_greater_than>, C<string_greater_than_or_equal>, C<string_less_than>, C<string_less_than_or_equal>, C<string_compare>, C<string_equality_insensitive>, C<string_inequality_insensitive>, C<string_greater_than_insensitive>, C<string_greater_than_or_equal_insensitive>, C<string_less_than_insensitive>, C<string_less_than_or_equal_insensitive>, C<string_compare_insensitive>\\n\\nType: C<Function>. String operator implementations.\\n\\n=item C<regexp_match>, C<bitwise_and>, C<bitwise_xor>, C<bitwise_or>, C<set_union>, C<set_intersection>, C<set_difference>, C<collection_membership>, C<collection_non_membership>, C<set_subsetof>, C<set_supersetof>, C<set_equivalentof>, C<type_aware_equality>, C<type_aware_inequality>, C<object_can>\\n\\nType: C<Function>. Regular expression, bitwise, collection, type-aware,\\nand object capability operator implementations.\\n\\n=back\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/path/zz/operators >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/path/z/operators import Operator as ZOperator;\\n\\n\\nclass Operator extends ZOperator;\\n\\nconst logical_negation := function ( op, ev, ast, ctx, expr ) {\\n	const got := ev.eval_expr( expr, ev.nested_ctx( ctx ) );\\n	const value := got.length() > 0 ? got[0] : null;\\n	return op.wrap( not ev.truthy(value) );\\n};\\n\\nconst numeric_power := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val ** right_val );\\n};\\n\\nconst numeric_multiplication := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val \\xD7 right_val );\\n};\\n\\nconst numeric_division := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val \\xF7 right_val );\\n};\\n\\nconst numeric_modulus := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val mod right_val );\\n};\\n\\nconst numeric_left_shift := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	const first := left_vals.length() > 0 ? left_vals[0] : null;\\n	const left_val := first \\u2261 null ? null : first.primitive_value();\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val \\xAB right_val );\\n};\\n\\nconst numeric_right_shift := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	const first := left_vals.length() > 0 ? left_vals[0] : null;\\n	const left_val := first \\u2261 null ? null : first.primitive_value();\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val \\xBB right_val );\\n};\\n\\nconst numeric_addition := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val + right_val );\\n};\\n\\nconst numeric_subtraction := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val - right_val );\\n};\\n\\nconst numeric_equality := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val = right_val );\\n};\\n\\nconst numeric_inequality := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val \\u2260 right_val );\\n};\\n\\nconst numeric_less_than := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val < right_val );\\n};\\n\\nconst numeric_greater_than := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val > right_val );\\n};\\n\\nconst numeric_less_than_or_equal := function (\\n	op,\\n	ev,\\n	ast,\\n	ctx,\\n	left,\\n	right,\\n) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val \\u2264 right_val );\\n};\\n\\nconst numeric_greater_than_or_equal := function (\\n	op,\\n	ev,\\n	ast,\\n	ctx,\\n	left,\\n	right,\\n) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val \\u2265 right_val );\\n};\\n\\nconst numeric_compare := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val <=> right_val );\\n};\\n\\nconst numeric_divides := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( right_val mod left_val = 0 );\\n};\\n\\nconst numeric_not_divides := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( right_val mod left_val );\\n};\\n\\nfunction string_operand ( ev, ctx, expr ) {\\n	const result := ev.eval_expr( expr, ev.nested_ctx( ctx ) );\\n	return "" unless result.length;\\n	const value := ev.to_string( result[0] );\\n	return value \\u2261 null ? "" : "" _ value;\\n}\\n\\nfunction string_operands ( ev, ctx, left, right ) {\\n	return [\\n		string_operand( ev, ctx, left ),\\n		string_operand( ev, ctx, right ),\\n	];\\n}\\n\\nconst string_concatenation := function ( op, ev, ast, ctx, left, right ) {\\n	const values := string_operands( ev, ctx, left, right );\\n	return op.wrap( values[0] _ values[1] );\\n};\\n\\nconst string_equality := function ( op, ev, ast, ctx, left, right ) {\\n	const values := string_operands( ev, ctx, left, right );\\n	return op.wrap( values[0] eq values[1] );\\n};\\n\\nconst string_inequality := function ( op, ev, ast, ctx, left, right ) {\\n	const values := string_operands( ev, ctx, left, right );\\n	return op.wrap( values[0] ne values[1] );\\n};\\n\\nconst string_greater_than := function ( op, ev, ast, ctx, left, right ) {\\n	const values := string_operands( ev, ctx, left, right );\\n	return op.wrap( values[0] gt values[1] );\\n};\\n\\nconst string_greater_than_or_equal := function ( op, ev, ast, ctx, left, right ) {\\n	const values := string_operands( ev, ctx, left, right );\\n	return op.wrap( values[0] ge values[1] );\\n};\\n\\nconst string_less_than := function ( op, ev, ast, ctx, left, right ) {\\n	const values := string_operands( ev, ctx, left, right );\\n	return op.wrap( values[0] lt values[1] );\\n};\\n\\nconst string_less_than_or_equal := function ( op, ev, ast, ctx, left, right ) {\\n	const values := string_operands( ev, ctx, left, right );\\n	return op.wrap( values[0] le values[1] );\\n};\\n\\nconst string_compare := function ( op, ev, ast, ctx, left, right ) {\\n	const values := string_operands( ev, ctx, left, right );\\n	return op.wrap( values[0] cmp values[1] );\\n};\\n\\nconst string_equality_insensitive := function ( op, ev, ast, ctx, left, right ) {\\n	const values := string_operands( ev, ctx, left, right );\\n	const left_val := lc values[0];\\n	const right_val := lc values[1];\\n	return op.wrap( left_val eq right_val );\\n};\\n\\nconst string_inequality_insensitive := function ( op, ev, ast, ctx, left, right ) {\\n	const values := string_operands( ev, ctx, left, right );\\n	const left_val := lc values[0];\\n	const right_val := lc values[1];\\n	return op.wrap( left_val ne right_val );\\n};\\n\\nconst string_greater_than_insensitive := function ( op, ev, ast, ctx, left, right ) {\\n	const values := string_operands( ev, ctx, left, right );\\n	const left_val := lc values[0];\\n	const right_val := lc values[1];\\n	return op.wrap( left_val gt right_val );\\n};\\n\\nconst string_greater_than_or_equal_insensitive := function (\\n	op,\\n	ev,\\n	ast,\\n	ctx,\\n	left,\\n	right,\\n) {\\n	const values := string_operands( ev, ctx, left, right );\\n	const left_val := lc values[0];\\n	const right_val := lc values[1];\\n	return op.wrap( left_val ge right_val );\\n};\\n\\nconst string_less_than_insensitive := function ( op, ev, ast, ctx, left, right ) {\\n	const values := string_operands( ev, ctx, left, right );\\n	const left_val := lc values[0];\\n	const right_val := lc values[1];\\n	return op.wrap( left_val lt right_val );\\n};\\n\\nconst string_less_than_or_equal_insensitive := function (\\n	op,\\n	ev,\\n	ast,\\n	ctx,\\n	left,\\n	right,\\n) {\\n	const values := string_operands( ev, ctx, left, right );\\n	const left_val := lc values[0];\\n	const right_val := lc values[1];\\n	return op.wrap( left_val le right_val );\\n};\\n\\nconst string_compare_insensitive := function ( op, ev, ast, ctx, left, right ) {\\n	const values := string_operands( ev, ctx, left, right );\\n	const left_val := lc values[0];\\n	const right_val := lc values[1];\\n	return op.wrap( left_val cmp right_val );\\n};\\n\\nconst regexp_match := function ( op, ev, ast, ctx, left, right ) {\\n	const values := string_operands( ev, ctx, left, right );\\n	return op.wrap( values[0] ~ values[1] );\\n};\\n\\nconst bitwise_and := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val & right_val );\\n};\\n\\nconst bitwise_xor := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val ^ right_val );\\n};\\n\\nconst bitwise_or := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val  := op._handle_numeric_operand( ev, ctx, left );\\n	const right_val := op._handle_numeric_operand( ev, ctx, right );\\n	return op.wrap( left_val | right_val );\\n};\\n\\nfunction first_eval_value ( values ) {\\n	return values.length() > 0 ? values[0] : null;\\n}\\n\\nfunction primitive_eval_value ( values ) {\\n	const first := first_eval_value(values);\\n	return first \\u2261 null ? null : first.primitive_value();\\n}\\n\\nfunction collection_operand ( ev, ctx, expr ) {\\n	const values := ev.eval_expr( expr, ev.nested_ctx( ctx ) );\\n	if ( values.length() = 1 ) {\\n		return values[0].primitive_value();\\n	}\\n	return values.map( fn value \\u2192 value.primitive_value() );\\n}\\n\\nconst logical_and := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	if ( ev.truthy( first_eval_value(left_vals) ) ) {\\n		return ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	}\\n	return op.wrap(false);\\n};\\n\\nconst logical_nand := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	if ( not ev.truthy( first_eval_value(left_vals) ) ) {\\n		return op.wrap(true);\\n	}\\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	return op.wrap( ev.truthy( first_eval_value(right_vals) ) ? false : true );\\n};\\n\\nconst logical_butnot := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	if ( not ev.truthy( first_eval_value(left_vals) ) ) {\\n		return op.wrap(false);\\n	}\\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	return op.wrap( ev.truthy( first_eval_value(right_vals) ) ? false : true );\\n};\\n\\nconst logical_xor := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	const left_truth := ev.truthy( first_eval_value(left_vals) );\\n	const right_truth := ev.truthy( first_eval_value(right_vals) );\\n	return op.wrap( ( left_truth xor right_truth ) ? true : false );\\n};\\n\\nconst logical_nor := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	if ( ev.truthy( first_eval_value(left_vals) ) ) {\\n		return op.wrap(false);\\n	}\\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	return op.wrap( ev.truthy( first_eval_value(right_vals) ) ? false : true );\\n};\\n\\nconst logical_xnor := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	const left_truth := ev.truthy( first_eval_value(left_vals) );\\n	const right_truth := ev.truthy( first_eval_value(right_vals) );\\n	return op.wrap( left_truth \\u2261 right_truth );\\n};\\n\\nconst logical_onlyif := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	if ( not ev.truthy( first_eval_value(left_vals) ) ) {\\n		return op.wrap(true);\\n	}\\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	return op.wrap( ev.truthy( first_eval_value(right_vals) ) ? true : false );\\n};\\n\\nconst logical_or := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	if ( ev.truthy( first_eval_value(left_vals) ) ) {\\n		return op.wrap(true);\\n	}\\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	return op.wrap( ev.truthy( first_eval_value(right_vals) ) ? true : false );\\n};\\n\\nconst logical_and_value := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	if ( ev.truthy( first_eval_value(left_vals) ) ) {\\n		return ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	}\\n	return left_vals;\\n};\\n\\nconst logical_nand_value := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	const left_truth := ev.truthy( first_eval_value(left_vals) );\\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	const right_truth := ev.truthy( first_eval_value(right_vals) );\\n	if ( left_truth and right_truth ) {\\n		return op.wrap(false);\\n	}\\n	return right_vals if not left_truth and right_truth;\\n	return op.wrap(true);\\n};\\n\\nconst logical_butnot_value := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	const left_truth := ev.truthy( first_eval_value(left_vals) );\\n	return left_vals unless left_truth;\\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	return ev.truthy( first_eval_value(right_vals) )\\n		? op.wrap(false)\\n		: left_vals;\\n};\\n\\nconst logical_xor_value := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	const left_truth := ev.truthy( first_eval_value(left_vals) );\\n	const right_truth := ev.truthy( first_eval_value(right_vals) );\\n	if ( left_truth xor right_truth ) {\\n		return left_truth ? left_vals : right_vals;\\n	}\\n	return op.wrap(false);\\n};\\n\\nconst logical_nor_value := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	const left_truth := ev.truthy( first_eval_value(left_vals) );\\n	const right_truth := ev.truthy( first_eval_value(right_vals) );\\n	return op.wrap(false) if left_truth and right_truth;\\n	return right_vals if left_truth and not right_truth;\\n	return left_vals if not left_truth and right_truth;\\n	return op.wrap(true);\\n};\\n\\nconst logical_xnor_value := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	const left_truth := ev.truthy( first_eval_value(left_vals) );\\n	const right_truth := ev.truthy( first_eval_value(right_vals) );\\n	if ( left_truth \\u2261 right_truth ) {\\n		return left_truth ? right_vals : op.wrap(true);\\n	}\\n	return left_truth ? right_vals : left_vals;\\n};\\n\\nconst logical_onlyif_value := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	if ( not ev.truthy( first_eval_value(left_vals) ) ) {\\n		return op.wrap(true);\\n	}\\n	return ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n};\\n\\nconst logical_or_value := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	if ( ev.truthy( first_eval_value(left_vals) ) ) {\\n		return left_vals;\\n	}\\n	return ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n};\\n\\nconst set_union := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val := collection_operand( ev, ctx, left );\\n	const right_val := collection_operand( ev, ctx, right );\\n	return op.wrap( left_val union right_val );\\n};\\n\\nconst set_intersection := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val := collection_operand( ev, ctx, left );\\n	const right_val := collection_operand( ev, ctx, right );\\n	return op.wrap( left_val intersection right_val );\\n};\\n\\nconst set_difference := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val := collection_operand( ev, ctx, left );\\n	const right_val := collection_operand( ev, ctx, right );\\n	return op.wrap( left_val \\u2216 right_val );\\n};\\n\\nconst collection_membership := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	const left_val := primitive_eval_value(left_vals);\\n	const right_val := collection_operand( ev, ctx, right );\\n	return op.wrap( left_val in right_val );\\n};\\n\\nconst collection_non_membership := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	const left_val := primitive_eval_value(left_vals);\\n	const right_val := collection_operand( ev, ctx, right );\\n	return op.wrap( left_val \\u2209 right_val );\\n};\\n\\nconst set_subsetof := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val := collection_operand( ev, ctx, left );\\n	const right_val := collection_operand( ev, ctx, right );\\n	return op.wrap( left_val subsetof right_val );\\n};\\n\\nconst set_supersetof := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val := collection_operand( ev, ctx, left );\\n	const right_val := collection_operand( ev, ctx, right );\\n	return op.wrap( left_val supersetof right_val );\\n};\\n\\nconst set_equivalentof := function ( op, ev, ast, ctx, left, right ) {\\n	const left_val := collection_operand( ev, ctx, left );\\n	const right_val := collection_operand( ev, ctx, right );\\n	return op.wrap( left_val equivalentof right_val );\\n};\\n\\nconst type_aware_equality := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	return op.wrap( ev.equals(\\n		first_eval_value(left_vals),\\n		first_eval_value(right_vals),\\n	) );\\n};\\n\\nconst type_aware_inequality := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	return op.wrap( not ev.equals(\\n		first_eval_value(left_vals),\\n		first_eval_value(right_vals),\\n	) );\\n};\\n\\nfunction builtin_can ( value, method_name ) {\\n	return false if value \\u2261 null\\n		or method_name \\u2261 null\\n		or method_name eq "";\\n\\n	if ( value instanceof Array or value instanceof Bag or value instanceof Set ) {\\n		return method_name in [\\n			"length",\\n			"empty",\\n			"contains",\\n			"push",\\n			"to_Array",\\n			"to_Bag",\\n			"to_Set",\\n		];\\n	}\\n	if ( value instanceof Dict or value instanceof PairList ) {\\n		return method_name in [\\n			"length",\\n			"empty",\\n			"exists",\\n			"keys",\\n			"values",\\n			"to_Array",\\n		];\\n	}\\n	if ( value instanceof String or value instanceof BinaryString ) {\\n		return method_name in [ "length" ];\\n	}\\n	return false;\\n}\\n\\nconst object_can := function ( op, ev, ast, ctx, left, right ) {\\n	const left_vals := ev.eval_expr( left, ev.nested_ctx( ctx ) );\\n	const right_vals := ev.eval_expr( right, ev.nested_ctx( ctx ) );\\n	const left_val := primitive_eval_value(left_vals);\\n	const right_val := primitive_eval_value(right_vals);\\n	return op.wrap(\\n		( left_val can (right_val) ) or builtin_can( left_val, right_val )\\n	);\\n};\\n\\nconst STANDARD_OPERATORS := [\\n	new Operator(\\n		spelling: "?:",\\n		kind: "ELVIS",\\n		precedence: 2,\\n		lex_ignore: true,\\n	),\\n\\n	new Operator(\\n		spelling: "+",\\n		kind: "UPLUS",\\n		unary: true,\\n		precedence: 40,\\n		f: function ( op, ev, ast, ctx, expr ) {\\n			const value := op._handle_numeric_operand( ev, ctx, expr );\\n			return op.wrap( +value );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "-",\\n		kind: "UMINUS",\\n		unary: true,\\n		precedence: 40,\\n		f: function ( op, ev, ast, ctx, expr ) {\\n			const value := op._handle_numeric_operand( ev, ctx, expr );\\n			return op.wrap( -value );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "\\u221A",\\n		kind: "SQRT",\\n		unary: true,\\n		precedence: 40,\\n		f: function ( op, ev, ast, ctx, expr ) {\\n			const value := op._handle_numeric_operand( ev, ctx, expr );\\n			return op.wrap( sqrt value );\\n		},\\n	),\\n\\n	new Operator(\\n		spelling: "!",\\n		kind: "NOT",\\n		unary: true,\\n		precedence: 40,\\n		f: logical_negation,\\n	),\\n\\n	new Operator(\\n		spelling: "\\xAC",\\n		kind: "NOTSYM",\\n		unary: true,\\n		precedence: 40,\\n		f: logical_negation,\\n	),\\n\\n	new Operator(\\n		spelling: "**",\\n		kind: "POW",\\n		require_ws: true,\\n		right_assoc: true,\\n		precedence: 26,\\n		f: numeric_power,\\n	),\\n\\n	new Operator(\\n		spelling: "\\xD7",\\n		kind: "TIMES_SIGN",\\n		precedence: 24,\\n		f: numeric_multiplication,\\n	),\\n\\n	new Operator(\\n		spelling: "*",\\n		kind: "TIMES",\\n		require_ws: true,\\n		precedence: 24,\\n		lex_ignore: true,\\n		alias: "STAR",\\n		f: numeric_multiplication,\\n	),\\n\\n	new Operator(\\n		spelling: "\\xF7",\\n		kind: "DIVIDE_SIGN",\\n		precedence: 24,\\n		f: numeric_division,\\n	),\\n\\n	new Operator(\\n		spelling: "/",\\n		kind: "DIVIDE",\\n		require_ws: true,\\n		precedence: 24,\\n		lex_ignore: true,\\n		alias: "SLASH",\\n		f: numeric_division,\\n	),\\n\\n	new Operator(\\n		spelling: "mod",\\n		kind: "MOD",\\n		precedence: 24,\\n		f: numeric_modulus,\\n	),\\n\\n	new Operator(\\n		spelling: "+",\\n		kind: "PLUS",\\n		require_ws: true,\\n		precedence: 22,\\n		f: numeric_addition,\\n	),\\n\\n	new Operator(\\n		spelling: "-",\\n		kind: "MINUS",\\n		require_ws: true,\\n		precedence: 22,\\n		f: numeric_subtraction,\\n	),\\n\\n	new Operator(\\n		spelling: "=",\\n		kind: "EQ",\\n		precedence: 10,\\n		f: numeric_equality,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2260",\\n		kind: "NE",\\n		precedence: 10,\\n		f: numeric_inequality,\\n	),\\n\\n	new Operator(\\n		spelling: "<",\\n		kind: "LT",\\n		precedence: 10,\\n		f: numeric_less_than,\\n	),\\n\\n	new Operator(\\n		spelling: ">",\\n		kind: "GT",\\n		precedence: 10,\\n		f: numeric_greater_than,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2264",\\n		kind: "LE_SIGN",\\n		precedence: 10,\\n		f: numeric_less_than_or_equal,\\n	),\\n\\n	new Operator(\\n		spelling: "<=",\\n		kind: "LE",\\n		precedence: 10,\\n		f: numeric_less_than_or_equal,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2265",\\n		kind: "GE_SIGN",\\n		precedence: 10,\\n		f: numeric_greater_than_or_equal,\\n	),\\n\\n	new Operator(\\n		spelling: ">=",\\n		kind: "GE",\\n		precedence: 10,\\n		f: numeric_greater_than_or_equal,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2276",\\n		kind: "CMP_SIGN",\\n		precedence: 10,\\n		f: numeric_compare,\\n	),\\n\\n	new Operator(\\n		spelling: "<=>",\\n		kind: "CMP",\\n		precedence: 10,\\n		f: numeric_compare,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2277",\\n		kind: "CMP_REV_SIGN",\\n		precedence: 10,\\n		f: numeric_compare,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2223",\\n		kind: "DIVIDES_SIGN",\\n		precedence: 10,\\n		f: numeric_divides,\\n	),\\n\\n	new Operator(\\n		spelling: "divides",\\n		kind: "DIVIDES",\\n		precedence: 10,\\n		f: numeric_divides,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2224",\\n		kind: "NOT_DIVIDES_SIGN",\\n		precedence: 10,\\n		f: numeric_not_divides,\\n	),\\n\\n	new Operator(\\n		spelling: "_",\\n		kind: "CONCAT",\\n		require_ws: true,\\n		precedence: 21,\\n		f: string_concatenation,\\n	),\\n\\n	new Operator(\\n		spelling: "eq",\\n		kind: "STR_EQ",\\n		precedence: 10,\\n		f: string_equality,\\n	),\\n\\n	new Operator(\\n		spelling: "ne",\\n		kind: "STR_NE",\\n		precedence: 10,\\n		f: string_inequality,\\n	),\\n\\n	new Operator(\\n		spelling: "gt",\\n		kind: "STR_GT",\\n		precedence: 10,\\n		f: string_greater_than,\\n	),\\n\\n	new Operator(\\n		spelling: "ge",\\n		kind: "STR_GE",\\n		precedence: 10,\\n		f: string_greater_than_or_equal,\\n	),\\n\\n	new Operator(\\n		spelling: "lt",\\n		kind: "STR_LT",\\n		precedence: 10,\\n		f: string_less_than,\\n	),\\n\\n	new Operator(\\n		spelling: "le",\\n		kind: "STR_LE",\\n		precedence: 10,\\n		f: string_less_than_or_equal,\\n	),\\n\\n	new Operator(\\n		spelling: "cmp",\\n		kind: "STR_CMP",\\n		precedence: 10,\\n		f: string_compare,\\n	),\\n\\n	new Operator(\\n		spelling: "eqi",\\n		kind: "STR_EQI",\\n		precedence: 10,\\n		f: string_equality_insensitive,\\n	),\\n\\n	new Operator(\\n		spelling: "nei",\\n		kind: "STR_NEI",\\n		precedence: 10,\\n		f: string_inequality_insensitive,\\n	),\\n\\n	new Operator(\\n		spelling: "gti",\\n		kind: "STR_GTI",\\n		precedence: 10,\\n		f: string_greater_than_insensitive,\\n	),\\n\\n	new Operator(\\n		spelling: "gei",\\n		kind: "STR_GEI",\\n		precedence: 10,\\n		f: string_greater_than_or_equal_insensitive,\\n	),\\n\\n	new Operator(\\n		spelling: "lti",\\n		kind: "STR_LTI",\\n		precedence: 10,\\n		f: string_less_than_insensitive,\\n	),\\n\\n	new Operator(\\n		spelling: "lei",\\n		kind: "STR_LEI",\\n		precedence: 10,\\n		f: string_less_than_or_equal_insensitive,\\n	),\\n\\n	new Operator(\\n		spelling: "cmpi",\\n		kind: "STR_CMPI",\\n		precedence: 10,\\n		f: string_compare_insensitive,\\n	),\\n\\n	new Operator(\\n		spelling: "~",\\n		kind: "REGEXP_MATCH",\\n		precedence: 10,\\n		f: regexp_match,\\n	),\\n\\n	new Operator(\\n		spelling: "\\xAB",\\n		kind: "LSHIFT_SIGN",\\n		precedence: 18,\\n		f: numeric_left_shift,\\n	),\\n\\n	new Operator(\\n		spelling: "<<",\\n		kind: "LSHIFT",\\n		precedence: 18,\\n		f: numeric_left_shift,\\n	),\\n\\n	new Operator(\\n		spelling: "\\xBB",\\n		kind: "RSHIFT_SIGN",\\n		precedence: 18,\\n		f: numeric_right_shift,\\n	),\\n\\n	new Operator(\\n		spelling: ">>",\\n		kind: "RSHIFT",\\n		precedence: 18,\\n		f: numeric_right_shift,\\n	),\\n\\n	new Operator(\\n		spelling: "&",\\n		kind: "BAND",\\n		precedence: 16,\\n		f: bitwise_and,\\n	),\\n\\n	new Operator(\\n		spelling: "^",\\n		kind: "BXOR",\\n		precedence: 14,\\n		f: bitwise_xor,\\n	),\\n\\n	new Operator(\\n		spelling: "|",\\n		kind: "BOR",\\n		precedence: 12,\\n		f: bitwise_or,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u22C0",\\n		kind: "LAND_SIGN",\\n		precedence: 7,\\n		f: logical_and,\\n	),\\n\\n	new Operator(\\n		spelling: "and",\\n		kind: "LAND",\\n		precedence: 7,\\n		f: logical_and,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u22C0?",\\n		kind: "LAND_VALUE_SIGN",\\n		precedence: 7,\\n		f: logical_and_value,\\n	),\\n\\n	new Operator(\\n		spelling: "and?",\\n		kind: "LAND_VALUE",\\n		precedence: 7,\\n		f: logical_and_value,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u22BC",\\n		kind: "LNAND_SIGN",\\n		precedence: 7,\\n		f: logical_nand,\\n	),\\n\\n	new Operator(\\n		spelling: "nand",\\n		kind: "LNAND",\\n		precedence: 7,\\n		f: logical_nand,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u22BC?",\\n		kind: "LNAND_VALUE_SIGN",\\n		precedence: 7,\\n		f: logical_nand_value,\\n	),\\n\\n	new Operator(\\n		spelling: "nand?",\\n		kind: "LNAND_VALUE",\\n		precedence: 7,\\n		f: logical_nand_value,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u22AD",\\n		kind: "LBUTNOT_SIGN",\\n		precedence: 7,\\n		f: logical_butnot,\\n	),\\n\\n	new Operator(\\n		spelling: "butnot",\\n		kind: "LBUTNOT",\\n		precedence: 7,\\n		f: logical_butnot,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u22AD?",\\n		kind: "LBUTNOT_VALUE_SIGN",\\n		precedence: 7,\\n		f: logical_butnot_value,\\n	),\\n\\n	new Operator(\\n		spelling: "butnot?",\\n		kind: "LBUTNOT_VALUE",\\n		precedence: 7,\\n		f: logical_butnot_value,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u22BB",\\n		kind: "LXOR_SIGN",\\n		precedence: 5,\\n		f: logical_xor,\\n	),\\n\\n	new Operator(\\n		spelling: "xor",\\n		kind: "LXOR",\\n		precedence: 5,\\n		f: logical_xor,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u22BB?",\\n		kind: "LXOR_VALUE_SIGN",\\n		precedence: 5,\\n		f: logical_xor_value,\\n	),\\n\\n	new Operator(\\n		spelling: "xor?",\\n		kind: "LXOR_VALUE",\\n		precedence: 5,\\n		f: logical_xor_value,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u22BD",\\n		kind: "LNOR_SIGN",\\n		precedence: 5,\\n		f: logical_nor,\\n	),\\n\\n	new Operator(\\n		spelling: "nor",\\n		kind: "LNOR",\\n		precedence: 5,\\n		f: logical_nor,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u22BD?",\\n		kind: "LNOR_VALUE_SIGN",\\n		precedence: 5,\\n		f: logical_nor_value,\\n	),\\n\\n	new Operator(\\n		spelling: "nor?",\\n		kind: "LNOR_VALUE",\\n		precedence: 5,\\n		f: logical_nor_value,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2194",\\n		kind: "LXNOR_SIGN",\\n		precedence: 5,\\n		f: logical_xnor,\\n	),\\n\\n	new Operator(\\n		spelling: "xnor",\\n		kind: "LXNOR",\\n		precedence: 5,\\n		f: logical_xnor,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2194?",\\n		kind: "LXNOR_VALUE_SIGN",\\n		precedence: 5,\\n		f: logical_xnor_value,\\n	),\\n\\n	new Operator(\\n		spelling: "xnor?",\\n		kind: "LXNOR_VALUE",\\n		precedence: 5,\\n		f: logical_xnor_value,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u22A8",\\n		kind: "LONLYIF_SIGN",\\n		precedence: 4,\\n		right_assoc: true,\\n		f: logical_onlyif,\\n	),\\n\\n	new Operator(\\n		spelling: "onlyif",\\n		kind: "LONLYIF",\\n		precedence: 4,\\n		right_assoc: true,\\n		f: logical_onlyif,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u22A8?",\\n		kind: "LONLYIF_VALUE_SIGN",\\n		precedence: 4,\\n		right_assoc: true,\\n		f: logical_onlyif_value,\\n	),\\n\\n	new Operator(\\n		spelling: "onlyif?",\\n		kind: "LONLYIF_VALUE",\\n		precedence: 4,\\n		right_assoc: true,\\n		f: logical_onlyif_value,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u22C1",\\n		kind: "LOR_SIGN",\\n		precedence: 2,\\n		f: logical_or,\\n	),\\n\\n	new Operator(\\n		spelling: "or",\\n		kind: "LOR",\\n		precedence: 2,\\n		f: logical_or,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u22C1?",\\n		kind: "LOR_VALUE_SIGN",\\n		precedence: 2,\\n		f: logical_or_value,\\n	),\\n\\n	new Operator(\\n		spelling: "or?",\\n		kind: "LOR_VALUE",\\n		precedence: 2,\\n		f: logical_or_value,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u22C3",\\n		kind: "SET_UNION_SIGN",\\n		precedence: 20,\\n		f: set_union,\\n	),\\n\\n	new Operator(\\n		spelling: "union",\\n		kind: "SET_UNION",\\n		precedence: 20,\\n		f: set_union,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u22C2",\\n		kind: "SET_INTERSECTION_SIGN",\\n		precedence: 20,\\n		f: set_intersection,\\n	),\\n\\n	new Operator(\\n		spelling: "intersection",\\n		kind: "SET_INTERSECTION",\\n		precedence: 20,\\n		f: set_intersection,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2216",\\n		kind: "SET_DIFFERENCE_SIGN",\\n		precedence: 20,\\n		f: set_difference,\\n	),\\n\\n	new Operator(\\n		spelling: "\\\\\\\\",\\n		kind: "SET_DIFFERENCE",\\n		precedence: 20,\\n		require_ws: true,\\n		f: set_difference,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2208",\\n		kind: "MEMBER_SIGN",\\n		precedence: 10,\\n		f: collection_membership,\\n	),\\n\\n	new Operator(\\n		spelling: "in",\\n		kind: "MEMBER",\\n		precedence: 10,\\n		f: collection_membership,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2209",\\n		kind: "NOT_MEMBER_SIGN",\\n		precedence: 10,\\n		f: collection_non_membership,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2282",\\n		kind: "SUBSETOF_SIGN",\\n		precedence: 10,\\n		f: set_subsetof,\\n	),\\n\\n	new Operator(\\n		spelling: "subsetof",\\n		kind: "SUBSETOF",\\n		precedence: 10,\\n		f: set_subsetof,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2283",\\n		kind: "SUPERSETOF_SIGN",\\n		precedence: 10,\\n		f: set_supersetof,\\n	),\\n\\n	new Operator(\\n		spelling: "supersetof",\\n		kind: "SUPERSETOF",\\n		precedence: 10,\\n		f: set_supersetof,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2282\\u2283",\\n		kind: "EQUIVALENTOF_SIGN",\\n		precedence: 10,\\n		f: set_equivalentof,\\n	),\\n\\n	new Operator(\\n		spelling: "equivalentof",\\n		kind: "EQUIVALENTOF",\\n		precedence: 10,\\n		f: set_equivalentof,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2261",\\n		kind: "TYPE_EQ_SIGN",\\n		precedence: 8,\\n		f: type_aware_equality,\\n	),\\n\\n	new Operator(\\n		spelling: "==",\\n		kind: "TYPE_EQ",\\n		precedence: 8,\\n		f: type_aware_equality,\\n	),\\n\\n	new Operator(\\n		spelling: "\\u2262",\\n		kind: "TYPE_NE_SIGN",\\n		precedence: 8,\\n		f: type_aware_inequality,\\n	),\\n\\n	new Operator(\\n		spelling: "!=",\\n		kind: "TYPE_NE",\\n		precedence: 8,\\n		f: type_aware_inequality,\\n	),\\n\\n	new Operator(\\n		spelling: "can",\\n		kind: "CAN",\\n		precedence: 10,\\n		f: object_can,\\n	),\\n\\n	new Operator(\\n		spelling: "~",\\n		kind: "BNOT",\\n		unary: true,\\n		precedence: 40,\\n		f: function ( op, ev, ast, ctx, expr ) {\\n			const value := op._handle_numeric_operand( ev, ctx, expr );\\n			return op.wrap( ~value );\\n		},\\n	),\\n];\\n\';\n        virtualFiles["/modules/std/template/z.zzm"] = \'=encoding utf8\\n\\n=head1 NAME\\n\\nstd/template/z - Pure ZuzuScript template engine.\\n\\n=head1 SYNOPSIS\\n\\n  from std/template/z import ZTemplate;\\n\\n  let inline := new ZTemplate(\\n    string: "Hello {{ user/name }}!",\\n  );\\n  say( inline.process( { user: { name: "Ada" } } ) );\\n\\n  let file_tmpl := new ZTemplate(\\n    file: "templates/page.zt",\\n    escape: "html",\\n  );\\n  say( file_tmpl.process( data ) );\\n\\n=head1 IMPLEMENTATION SUPPORT\\n\\nThis module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Node and\\nElectron. It is partially supported by zuzu-js in the browser: complex,\\nHTTP/JSON/ZPath pipeline, self-contained, and trait-object rendering\\ncoverage passes, but filesystem-backed template loading and database row\\nrendering coverage are unsupported.\\n\\n=head1 DESCRIPTION\\n\\nC<std/template/z> is a pure ZuzuScript template renderer.\\n\\nThe module compiles template text into a cached parse tree and renders\\nit against data using C<std/path/z> expressions.\\n\\n=head1 EXPORTS\\n\\n=head2 Classes\\n\\n=over\\n\\n=item C<< ZTemplate({ string?: String, file?, escape?: String, includes?: Boolean }) >>\\n\\nConstructs a template from inline text or a file path. Returns:\\nC<ZTemplate>.\\n\\n=over\\n\\n=item C<< template.process(data) >>\\n\\nParameters: C<data> is the model used for path lookups. Returns:\\nC<String>. Renders the template.\\n\\n=back\\n\\n=back\\n\\n=head1 TAG FORMS\\n\\n=over 4\\n\\n=item * C<{{ expr }}>\\n\\nRender expression output using template default escaping.\\n\\n=item * C<{{ expr :: raw }}>, C<{{ expr :: html }}>\\n\\nRender expression output using per-tag escape override.\\n\\n=item * C<{{# expr }}> ... C<{{/expr}}>\\n\\nBlock form. Each truthy match renders child nodes.\\n\\n=item * C<{{> include.zt }}>\\n\\nInclude another template file. Relative include paths resolve from the\\ncurrent template\\\'s file directory.\\n\\n=back\\n\\n=head1 ESCAPING\\n\\nDefault escape mode is C<html>. Supported escape modes are C<html> and\\nC<raw>.\\n\\nC<html> escapes C<&>, C<< < >>, C<E<gt>>, double quotes, and single\\nquotes.\\n\\n=head1 INCLUDE RULES\\n\\n=over 4\\n\\n=item * Include processing is enabled by default.\\n\\n=item * Pass C<includes: false> to disable include tags.\\n\\n=item * Relative includes require a file-backed template source.\\n\\n=item * Circular include chains throw a deterministic error.\\n\\n=back\\n\\n=head1 KNOWN DIFFERENCES\\n\\nThis module is implemented on top of C<std/path/z>. Parser/rendering\\ndeltas across runtimes are covered in ztests and should be treated as\\nimplementation bugs unless explicitly documented.\\n\\n=head1 COPYRIGHT AND LICENCE\\n\\nB<< std/template/z >> is copyright Toby Inkster.\\n\\nIt is free software; you may redistribute it and/or modify it under\\nthe terms of either the Artistic License 1.0 or the GNU General Public\\nLicense version 2.\\n\\n=cut\\n\\nfrom std/string import index, substr, trim;\\nfrom std/path/z import ZPath;\\n\\nclass ZTemplate {\\n	let string;\\n	let file;\\n	let String escape := "html";\\n	let includes := true;\\n	let source_file := null;\\n	let Array tree := [];\\n	let compiled_paths := {};\\n\\n	method __build__ () {\\n		let has_string := string \\u2262 null;\\n		let has_file := file \\u2262 null;\\n\\n		if ( has_string and has_file ) {\\n			die "Specify only one of \\\\"string\\\\" or \\\\"file\\\\"";\\n		}\\n		if ( not has_string and not has_file ) {\\n			die "Missing template source: provide \\\\"string\\\\" or \\\\"file\\\\"";\\n		}\\n\\n		escape := lc( "" _ escape );\\n		if ( escape \\u2262 "html" and escape \\u2262 "raw" ) {\\n			die `Invalid escape mode "${escape}"`;\\n		}\\n\\n		if ( has_file ) {\\n			let loaded := self._read_template_file(file);\\n			string := loaded{text};\\n			source_file := loaded{file};\\n		}\\n\\n		tree := self._parse_template(\\n			template: string \\u2261 null ? "": string,\\n			current_file: source_file,\\n			seen_files: {},\\n			includes: includes,\\n		);\\n	}\\n\\n	method process ( data ) {\\n		die "process() requires a data model" if data \\u2261 null;\\n\\n		return self._render_nodes(\\n			nodes: tree,\\n			context: data,\\n			eval_meta: {},\\n			default_escape: escape,\\n		);\\n	}\\n\\n	method _parse_template ( ... PairList args ) {\\n		let template := args.get( "template", "" );\\n		let current_file := args.get( "current_file", null );\\n		let seen_files := args.get( "seen_files", {} );\\n		let includes_enabled := args.get( "includes", true );\\n		let root := [];\\n\\n		let stack := [\\n			{\\n				expr: null,\\n				nodes: root,\\n			},\\n		];\\n\\n		let pos := 0;\\n		while ( true ) {\\n			let tag_open := index( template, "{{", pos );\\n			last if tag_open < 0;\\n\\n			let text := substr( template, pos, tag_open - pos );\\n			self._push_text( stack[ stack.length() - 1 ]{nodes}, text );\\n\\n			let tag_close := index( template, "}}", tag_open + 2 );\\n			if ( tag_close < 0 ) {\\n				die `Unterminated tag at character ${tag_open}`;\\n			}\\n\\n			let raw := substr( template, tag_open + 2, tag_close - tag_open - 2 );\\n			let tagged := trim(raw);\\n\\n			if ( substr( tagged, 0, 1 ) \\u2261 "#" ) {\\n				let inner := trim( substr( tagged, 1 ) );\\n				let parsed := self._parse_expression_spec(inner);\\n				let block := {\\n					type: "block",\\n					expr_src: parsed{expr},\\n					nodes: [],\\n				};\\n				stack[ stack.length() - 1 ]{nodes}.push(block);\\n				stack.push( {\\n					expr: parsed{expr},\\n					nodes: block{nodes},\\n				} );\\n			}\\n			else if ( substr( tagged, 0, 1 ) \\u2261 "/" ) {\\n				let inner := trim( substr( tagged, 1 ) );\\n				let current := stack.pop();\\n				if ( current \\u2261 null or current{expr} \\u2261 null ) {\\n					die `Mismatched close tag {{/${inner}}}`;\\n				}\\n				if ( inner \\u2262 "" ) {\\n					let parsed := self._parse_expression_spec(inner);\\n					if ( current{expr} \\u2262 parsed{expr} ) {\\n						die `Mismatched close tag {{/${inner}}} for {{${current{expr}}}}`;\\n					}\\n				}\\n			}\\n			else if ( tagged \\u2262 "" ) {\\n				if ( substr( tagged, 0, 1 ) \\u2261 ">" ) {\\n					die "Template includes are disabled"\\n						if not includes_enabled;\\n\\n					let include_path := trim( substr( tagged, 1 ) );\\n					die "Empty include path in template tag"\\n						if include_path \\u2261 "";\\n\\n					let resolved := self._resolve_include_path(\\n						include_path: include_path,\\n						current_file: current_file,\\n					);\\n\\n					let key := self._canonical_path(resolved);\\n					if ( seen_files.exists(key) and seen_files.get(key) ) {\\n						die `Circular include detected for "${resolved}"`;\\n					}\\n\\n					seen_files.set( key, true );\\n					let loaded := self._read_template_file(resolved);\\n					let include_nodes := self._parse_template(\\n						template: loaded{text},\\n						current_file: loaded{file},\\n						seen_files: seen_files,\\n						includes: includes_enabled,\\n					);\\n					seen_files.remove(key);\\n\\n					for ( let node in include_nodes ) {\\n						stack[ stack.length() - 1 ]{nodes}.push(node);\\n					}\\n				}\\n				else {\\n					let parsed := self._parse_expression_spec(tagged);\\n					stack[ stack.length() - 1 ]{nodes}.push( {\\n						type: "expr",\\n						expr_src: parsed{expr},\\n						escape: parsed{escape},\\n					} );\\n				}\\n			}\\n\\n			pos := tag_close + 2;\\n		}\\n\\n		let tail := substr( template, pos );\\n		self._push_text( stack[ stack.length() - 1 ]{nodes}, tail );\\n\\n		if ( stack.length() > 1 ) {\\n			let missing := stack[ stack.length() - 1 ]{expr};\\n			die `Missing close tag for {{${missing}}}`;\\n		}\\n\\n		return root;\\n	}\\n\\n	method _push_text ( nodes, text ) {\\n		if ( text \\u2262 "" ) {\\n			nodes.push( {\\n				type: "text",\\n				text: text,\\n			} );\\n		}\\n	}\\n\\n	method _read_template_file ( raw_file ) {\\n		let path_obj := self._to_path(raw_file);\\n		let text := path_obj.slurp_utf8();\\n		let canonical := self._canonical_path(path_obj);\\n\\n		return {\\n			text: text,\\n			file: canonical,\\n		};\\n	}\\n\\n	method _to_path ( raw_file ) {\\n		from std/io import Path;\\n		if ( raw_file instanceof Path ) {\\n			return raw_file;\\n		}\\n		return new Path( "" _ raw_file );\\n	}\\n\\n	method _canonical_path ( path_obj ) {\\n		let obj := self._to_path(path_obj);\\n		let canonical := obj.realpath();\\n		if ( canonical \\u2261 null ) {\\n			canonical := obj.absolute();\\n		}\\n		if ( canonical \\u2261 null ) {\\n			return obj.to_String;\\n		}\\n		from std/io import Path;\\n		if ( canonical instanceof Path ) {\\n			return canonical.to_String;\\n		}\\n		return "" _ canonical;\\n	}\\n\\n	method _resolve_include_path ( ... PairList args ) {\\n		let include_path := args.get( "include_path" );\\n		let current_file := args.get( "current_file" );\\n\\n		let include_obj := self._to_path(include_path);\\n		if ( include_obj.is_absolute() ) {\\n			return include_obj.to_String;\\n		}\\n\\n		if ( current_file \\u2261 null ) {\\n			die `Relative include path "${include_path}" requires file-based template source`;\\n		}\\n\\n		let base := self._to_path(current_file).parent();\\n		return base.child( include_obj.to_String ).to_String;\\n	}\\n\\n	method _parse_expression_spec ( raw ) {\\n		let expr := raw;\\n		let escape_mode := null;\\n\\n		let split := self._find_escape_separator(raw);\\n		if ( split \\u2262 null ) {\\n			let lhs := split[0];\\n			let rhs := split[1];\\n			if ( rhs \\u2261 "html" or rhs \\u2261 "raw" ) {\\n				expr := lhs;\\n				escape_mode := rhs;\\n			}\\n		}\\n\\n		expr := trim(expr);\\n		if ( expr \\u2261 "" ) {\\n			die "Empty expression in template tag";\\n		}\\n\\n		return {\\n			expr: expr,\\n			escape: escape_mode,\\n		};\\n	}\\n\\n	method _find_escape_separator ( text ) {\\n		let quote := "";\\n		let i := 0;\\n		while ( i < length text ) {\\n			let ch := substr( text, i, 1 );\\n			if ( quote \\u2262 "" ) {\\n				if ( ch \\u2261 "\\\\\\\\" ) {\\n					i += 2;\\n					next;\\n				}\\n				if ( ch \\u2261 quote ) {\\n					quote := "";\\n				}\\n				i++;\\n				next;\\n			}\\n\\n			if ( ch \\u2261 "\\\\"" or ch \\u2261 "\\\'" ) {\\n				quote := ch;\\n				i++;\\n				next;\\n			}\\n\\n			if ( ch \\u2261 ":" and substr( text, i, 2 ) \\u2261 "::" ) {\\n				let lhs := trim( substr( text, 0, i ) );\\n				let rhs := lc( trim( substr( text, i + 2 ) ) );\\n				return [ lhs, rhs ];\\n			}\\n\\n			i++;\\n		}\\n\\n		return null;\\n	}\\n\\n	method _render_nodes ( ... PairList args ) {\\n		let nodes := args.get( "nodes", [] );\\n		let context := args.get( "context", null );\\n		let eval_meta := args.get( "eval_meta", {} );\\n		let default_escape := args.get( "default_escape", "html" );\\n		let out := "";\\n\\n		for ( let node in nodes ) {\\n			if ( node{type} \\u2261 "text" ) {\\n				out _= node{text};\\n			}\\n			else if ( node{type} \\u2261 "expr" ) {\\n				let results := self._evaluate_expression(\\n					expr_src: node{expr_src},\\n					context: context,\\n					eval_meta: eval_meta,\\n				);\\n				let value := "";\\n				for ( let matched in results ) {\\n					let sv := matched.string_value();\\n					value _= sv \\u2261 null ? "" : sv;\\n				}\\n\\n				let escape_mode := node{escape};\\n				if ( escape_mode \\u2261 null ) {\\n					escape_mode := default_escape;\\n				}\\n\\n				if ( escape_mode \\u2261 "html" ) {\\n					out _= self._escape_html(value);\\n				}\\n				else {\\n					out _= value;\\n				}\\n			}\\n			else if ( node{type} \\u2261 "block" ) {\\n				let results := self._evaluate_expression(\\n					expr_src: node{expr_src},\\n					context: context,\\n					eval_meta: eval_meta,\\n				);\\n				for ( let matched in results ) {\\n					let primitive := matched.primitive_value();\\n					next if not self._truthy(primitive);\\n\\n					let inner_context := context;\\n					let inner_meta := eval_meta;\\n					if ( self._node_has_identity(matched) ) {\\n						inner_context := matched;\\n						inner_meta := { parentset: results };\\n					}\\n\\n					out _= self._render_nodes(\\n						nodes: node{nodes},\\n						context: inner_context,\\n						eval_meta: inner_meta,\\n						default_escape: default_escape,\\n					);\\n				}\\n			}\\n		}\\n\\n		return out;\\n	}\\n\\n	method _evaluate_expression ( ... PairList args ) {\\n		let expr_src := args.get( "expr_src" );\\n		let context := args.get( "context" );\\n		let eval_meta := args.get( "eval_meta", {} );\\n		if ( not compiled_paths.exists(expr_src) ) {\\n			compiled_paths.set(\\n				expr_src,\\n				self._compile_path(expr_src),\\n			);\\n		}\\n		let zpath := compiled_paths.get(expr_src);\\n		return zpath.evaluate( context, eval_meta );\\n	}\\n\\n	method _compile_path ( expr_src ) {\\n		return new ZPath( path: expr_src );\\n	}\\n\\n	method _node_has_identity ( node ) {\\n		let parent := node.parent();\\n		if ( parent \\u2261 null ) {\\n			return false;\\n		}\\n\\n		return true;\\n	}\\n\\n	method _truthy ( value ) {\\n		return value ? true : false;\\n	}\\n\\n	method _escape_html ( text ) {\\n		let out := "";\\n		let i := 0;\\n		while ( i < length text ) {\\n			let ch := substr( text, i, 1 );\\n			if ( ch \\u2261 "&" ) {\\n				out _= "&amp;";\\n			}\\n			else if ( ch \\u2261 "<" ) {\\n				out _= "&lt;";\\n			}\\n			else if ( ch \\u2261 ">" ) {\\n				out _= "&gt;";\\n			}\\n			else if ( ch \\u2261 "\\\\"" ) {\\n				out _= "&quot;";\\n			}\\n			else if ( ch \\u2261 "\\\'" ) {\\n				out _= "&#39;";\\n			}\\n			else {\\n				out _= ch;\\n			}\\n			i++;\\n		}\\n		return out;\\n	}\\n}\\n\';\n        virtualFiles["/modules/std/template/zz.zzm"] = `=encoding utf8\n\n=head1 NAME\n\nstd/template/zz - ZZPath-backed template engine.\n\n=head1 SYNOPSIS\n\n  from std/template/zz import ZZTemplate;\n\n  let tmpl := new ZZTemplate(\n    string: "Hello {{ name ?: \\\\"friend\\\\" }}!",\n  );\n  say( tmpl.process( { name: "Ada" } ) );\n\n=head1 IMPLEMENTATION SUPPORT\n\nThis module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Node and\nElectron. It is partially supported by zuzu-js in the browser:\nfilesystem-backed template loading is unsupported.\n\n=head1 DESCRIPTION\n\nC<std/template/zz> provides C<ZZTemplate>, a subclass of\nC<std/template/z>\'s C<ZTemplate> which renders template expressions\nusing C<std/path/zz> instead of C<std/path/z>.\n\nThe parser, escaping, include handling, and rendering machinery are\ninherited from C<ZTemplate>.\n\n=head1 EXPORTS\n\n=head2 Classes\n\n=over\n\n=item C<< ZZTemplate({ string?: String, file?, escape?: String, includes?: Boolean }) >>\n\nConstructs a template that evaluates expressions with C<std/path/zz>.\nReturns: C<ZZTemplate>. It inherits C<process(data)> from C<ZTemplate>,\nwhich takes a model value and returns rendered C<String> output.\n\n=back\n\n=head1 COPYRIGHT AND LICENCE\n\nB<< std/template/zz >> is copyright Toby Inkster.\n\nIt is free software; you may redistribute it and/or modify it under\nthe terms of either the Artistic License 1.0 or the GNU General Public\nLicense version 2.\n\n=cut\n\nfrom std/template/z import ZTemplate;\nfrom std/path/zz import ZZPath;\n\nclass ZZTemplate extends ZTemplate {\n	method _compile_path ( expr_src ) {\n		return new ZZPath( path: expr_src );\n	}\n}\n`;\n        return {\n          repoRoot: "/",\n          includePaths: [],\n          jsModules,\n          virtualFiles\n        };\n      }\n      module2.exports = {\n        createBrowserStdlib: createBrowserStdlib2\n      };\n    }\n  });\n\n  // lib/browser-worker-entry.js\n  var require_browser_worker_entry = __commonJS({\n    "lib/browser-worker-entry.js"(exports2, module2) {\n      "use strict";\n      var { createBrowserRuntime } = require_browser_runtime();\n      var { BinaryString: BinaryString2 } = require_runtime_helpers();\n      var taskRuntime2 = require_task();\n      function bytesFromData(value) {\n        if (value instanceof Uint8Array) {\n          return new BinaryString2(value);\n        }\n        if (Array.isArray(value)) {\n          return new BinaryString2(Uint8Array.from(value));\n        }\n        return new BinaryString2();\n      }\n      function errorText(err) {\n        if (err && typeof err.to_String === "function") {\n          return err.to_String();\n        }\n        if (err && err.name && err.message) {\n          return `${err.name}: ${err.message}`;\n        }\n        return err && err.message ? err.message : String(err);\n      }\n      function workerDenyCapabilities(policy = {}) {\n        const out = [];\n        for (const capability of [\n          "fs",\n          "net",\n          "perl",\n          "js",\n          "proc",\n          "db",\n          "clib",\n          "gui",\n          "worker"\n        ]) {\n          if (policy[`deny_${capability}`]) {\n            out.push(capability);\n          }\n        }\n        return out;\n      }\n      async function runWorkerJob(payload, defaultOptions = {}) {\n        const policy = payload.policy || {};\n        const browser = createBrowserRuntime({\n          ...defaultOptions,\n          repoRoot: policy.repo_root || defaultOptions.repoRoot || "/",\n          includePaths: policy.include_paths || defaultOptions.includePaths || [],\n          denyCapabilities: workerDenyCapabilities(policy),\n          denyModules: policy.deny_modules || defaultOptions.denyModules || [],\n          debugLevel: policy.debug_level || 0,\n          transpiler: policy.transpiler || defaultOptions.transpiler\n        });\n        const marshal = browser.runtime.loadModule(\n          "std/marshal",\n          "/<browser-worker>.zzs"\n        );\n        if (marshal && typeof marshal.__zuzu_set_runtime_policy === "function") {\n          marshal.__zuzu_set_runtime_policy({\n            ...policy,\n            host_name: "browser"\n          });\n        }\n        const request = marshal.load(bytesFromData(payload.request_bytes));\n        if (!Array.isArray(request) || request.length !== 2) {\n          throw new Error("Worker.spawn payload did not decode as Array");\n        }\n        const [callable, workerArgs] = request;\n        if (typeof callable !== "function") {\n          throw new Error("Worker.spawn payload callable did not decode as Function");\n        }\n        if (!Array.isArray(workerArgs)) {\n          throw new Error("Worker.spawn payload arguments did not decode as Array");\n        }\n        let result = callable(...workerArgs);\n        if (result instanceof taskRuntime2.Task) {\n          result = await taskRuntime2.awaitValue(result);\n        } else if (result && typeof result.then === "function") {\n          result = await result;\n        }\n        const bytes = marshal.dump(result);\n        return Array.from(bytes.bytes);\n      }\n      var BrowserWorkerInbox = class {\n        constructor(marshal, post) {\n          this._marshal = marshal;\n          this._post = post;\n          this._queue = [];\n          this._receivers = [];\n          this._closed = false;\n        }\n        _postLater(message) {\n          Promise.resolve().then(() => this._post(message));\n        }\n        _deliver(message) {\n          const receiver = this._receivers.shift();\n          if (receiver) {\n            receiver._resolve(message);\n          } else {\n            this._queue.push(message);\n          }\n        }\n        _closeRemote() {\n          this._closed = true;\n          while (this._receivers.length > 0) {\n            this._receivers.shift()._reject(\n              new taskRuntime2.ChannelClosedException("worker inbox closed")\n            );\n          }\n        }\n        send(value = null) {\n          let bytes;\n          try {\n            bytes = this._marshal.dump(value);\n          } catch (err) {\n            return taskRuntime2.Task.failed(err);\n          }\n          this._post({\n            type: "message",\n            bytes: Array.from(bytes.bytes)\n          });\n          return taskRuntime2.Task.resolved(value);\n        }\n        recv() {\n          if (this._queue.length > 0) {\n            return taskRuntime2.Task.resolved(this._queue.shift());\n          }\n          if (this._closed) {\n            return taskRuntime2.Task.failed(\n              new taskRuntime2.ChannelClosedException("worker inbox closed")\n            );\n          }\n          const task = new taskRuntime2.Task(null, {\n            status: "waiting",\n            name: "WorkerInbox.recv",\n            cancel: () => {\n              this._receivers = this._receivers.filter((item) => item !== task);\n            }\n          });\n          this._receivers.push(task);\n          return task;\n        }\n        close() {\n          this._postLater({ type: "close" });\n          return taskRuntime2.Task.resolved(null);\n        }\n      };\n      async function runWorkerHandle(payload, defaultOptions = {}, post, registerControl = null) {\n        let nextOutgoingSeq = 1;\n        const postFrame = (message) => {\n          post({\n            ...message,\n            seq: nextOutgoingSeq++\n          });\n        };\n        const policy = payload.policy || {};\n        const browser = createBrowserRuntime({\n          ...defaultOptions,\n          repoRoot: policy.repo_root || defaultOptions.repoRoot || "/",\n          includePaths: policy.include_paths || defaultOptions.includePaths || [],\n          denyCapabilities: workerDenyCapabilities(policy),\n          denyModules: policy.deny_modules || defaultOptions.denyModules || [],\n          debugLevel: policy.debug_level || 0,\n          transpiler: policy.transpiler || defaultOptions.transpiler\n        });\n        const marshal = browser.runtime.loadModule(\n          "std/marshal",\n          "/<browser-worker>.zzs"\n        );\n        if (marshal && typeof marshal.__zuzu_set_runtime_policy === "function") {\n          marshal.__zuzu_set_runtime_policy({\n            ...policy,\n            host_name: "browser"\n          });\n        }\n        const request = marshal.load(bytesFromData(payload.request_bytes));\n        if (!Array.isArray(request) || request.length !== 2) {\n          throw new Error("Worker.spawn_handle payload did not decode as Array");\n        }\n        const [callable, workerArgs] = request;\n        if (typeof callable !== "function") {\n          throw new Error("Worker.spawn_handle payload callable did not decode as Function");\n        }\n        if (!Array.isArray(workerArgs)) {\n          throw new Error("Worker.spawn_handle payload arguments did not decode as Array");\n        }\n        const inbox = new BrowserWorkerInbox(marshal, postFrame);\n        const handleControl = (message) => {\n          if (!message || typeof message !== "object") {\n            return;\n          }\n          if (message.type === "message") {\n            inbox._deliver(marshal.load(bytesFromData(message.bytes)));\n          } else if (message.type === "close") {\n            inbox._closeRemote();\n          } else if (message.type === "cancel") {\n            inbox._closeRemote();\n            throw new taskRuntime2.CancelledException(\n              message.reason || "worker cancelled"\n            );\n          }\n        };\n        if (typeof registerControl === "function") {\n          registerControl(handleControl);\n        }\n        let result = callable(inbox, ...workerArgs);\n        if (result instanceof taskRuntime2.Task) {\n          result = await taskRuntime2.awaitValue(result);\n        } else if (result && typeof result.then === "function") {\n          result = await result;\n        }\n        const bytes = marshal.dump(result);\n        postFrame({\n          type: "result",\n          ok: true,\n          bytes: Array.from(bytes.bytes)\n        });\n        Promise.resolve().then(() => postFrame({ type: "close" }));\n      }\n      function installBrowserWorker2(defaultOptions = {}, root = globalThis) {\n        if (!root || typeof root !== "object") {\n          return null;\n        }\n        const post = (message) => {\n          if (typeof root.postMessage === "function") {\n            root.postMessage(message);\n          }\n        };\n        let activeHandleControl = null;\n        let nextControlSeq = 1;\n        const pendingControlFrames = /* @__PURE__ */ new Map();\n        const pendingUnsequencedControl = [];\n        const deliverHandleControl = (payload) => {\n          try {\n            activeHandleControl(payload);\n          } catch (err) {\n            activeHandleControl = null;\n            nextControlSeq = 1;\n            pendingControlFrames.clear();\n            pendingUnsequencedControl.length = 0;\n            post({\n              type: "result",\n              ok: false,\n              error: errorText(err)\n            });\n            post({ type: "close" });\n          }\n        };\n        const drainHandleControl = () => {\n          if (!activeHandleControl) {\n            return;\n          }\n          while (pendingUnsequencedControl.length > 0 && activeHandleControl) {\n            deliverHandleControl(pendingUnsequencedControl.shift());\n          }\n          while (activeHandleControl && pendingControlFrames.has(nextControlSeq)) {\n            const payload = pendingControlFrames.get(nextControlSeq);\n            pendingControlFrames.delete(nextControlSeq);\n            nextControlSeq++;\n            deliverHandleControl(payload);\n          }\n        };\n        const dispatchHandleControl = (payload) => {\n          if (Number.isInteger(payload.seq)) {\n            pendingControlFrames.set(payload.seq, payload);\n          } else {\n            pendingUnsequencedControl.push(payload);\n          }\n          drainHandleControl();\n        };\n        const handleMessage = (event) => {\n          const payload = event && Object.prototype.hasOwnProperty.call(event, "data") ? event.data : event;\n          if (payload && (payload.type === "message" || payload.type === "close" || payload.type === "cancel")) {\n            dispatchHandleControl(payload);\n            return;\n          }\n          if (payload && payload.type === "start_handle") {\n            const controlPost = (message) => post(message);\n            runWorkerHandle(\n              payload,\n              defaultOptions,\n              controlPost,\n              (handler) => {\n                activeHandleControl = handler;\n                drainHandleControl();\n              }\n            ).then(\n              () => {\n                activeHandleControl = null;\n                nextControlSeq = 1;\n                pendingControlFrames.clear();\n                pendingUnsequencedControl.length = 0;\n              },\n              (err) => {\n                activeHandleControl = null;\n                nextControlSeq = 1;\n                pendingControlFrames.clear();\n                pendingUnsequencedControl.length = 0;\n                post({\n                  type: "result",\n                  ok: false,\n                  error: errorText(err)\n                });\n                post({ type: "close" });\n              }\n            );\n            return;\n          }\n          runWorkerJob(payload || {}, defaultOptions).then(\n            (bytes) => post({\n              ok: true,\n              bytes\n            }),\n            (err) => post({\n              ok: false,\n              error: errorText(err)\n            })\n          );\n        };\n        if (typeof root.addEventListener === "function") {\n          root.addEventListener("message", handleMessage);\n          root.addEventListener("error", (event) => {\n            post({\n              ok: false,\n              error: errorText(\n                event && (event.error || event.message) ? event.error || event.message : "worker failed"\n              )\n            });\n          });\n          root.addEventListener("unhandledrejection", (event) => {\n            post({\n              ok: false,\n              error: errorText(\n                event && event.reason ? event.reason : "worker failed"\n              )\n            });\n          });\n        } else {\n          root.onmessage = handleMessage;\n          root.onerror = (message, _source, _line, _column, error) => {\n            post({\n              ok: false,\n              error: errorText(error || message || "worker failed")\n            });\n          };\n          root.onunhandledrejection = (event) => {\n            post({\n              ok: false,\n              error: errorText(\n                event && event.reason ? event.reason : "worker failed"\n              )\n            });\n          };\n        }\n        return root;\n      }\n      module2.exports = {\n        installBrowserWorker: installBrowserWorker2,\n        runWorkerJob\n      };\n    }\n  });\n\n  // ../../../../../tmp/zuzu-browser-build.UGYrnC/browser-worker-entry.generated.js\n  var { createBrowserStdlib } = require_browser_stdlib_generated();\n  globalThis.__ZUZU_BROWSER_DEFAULT_RUNTIME_OPTIONS__ = createBrowserStdlib();\n  var { installBrowserWorker } = require_browser_worker_entry();\n  installBrowserWorker(globalThis.__ZUZU_BROWSER_DEFAULT_RUNTIME_OPTIONS__);\n})();\n'
      };
    }
  });

  // lib/browser-bundle-entry.js
  var require_browser_bundle_entry = __commonJS({
    "lib/browser-bundle-entry.js"(exports2, module2) {
      "use strict";
      var { createBrowserRuntime } = require_browser_runtime();
      var { addBrowserModule } = require_browser_host();
      var {
        createBrowserGuiBridge,
        createBrowserGuiRenderer
      } = require_browser_gui_renderer();
      var defaultRuntime = null;
      function _defaultRuntimeOptions() {
        const root = typeof globalThis !== "undefined" ? globalThis : null;
        const value = root && root.__ZUZU_BROWSER_DEFAULT_RUNTIME_OPTIONS__;
        return value && typeof value === "object" ? value : {};
      }
      function _mergeMapOption(left, right) {
        return {
          ...left || {},
          ...right || {}
        };
      }
      function _mergeRuntimeOptions(defaults, options) {
        return {
          ...defaults,
          ...options,
          virtualFiles: _mergeMapOption(defaults.virtualFiles, options.virtualFiles),
          jsModules: _mergeMapOption(defaults.jsModules, options.jsModules),
          workerSource: options.workerSource || defaults.workerSource,
          workerUrl: options.workerUrl || defaults.workerUrl,
          workerFactory: options.workerFactory || defaults.workerFactory
        };
      }
      function createConfiguredBrowserRuntime(options = {}) {
        return createBrowserRuntime(
          _mergeRuntimeOptions(_defaultRuntimeOptions(), options)
        );
      }
      function getDefaultBrowserRuntime(options = {}) {
        if (!defaultRuntime || options.reset === true) {
          defaultRuntime = createConfiguredBrowserRuntime(
            options.runtimeOptions || options
          );
        }
        return defaultRuntime;
      }
      function zuzu_eval(source, options = {}) {
        return getDefaultBrowserRuntime(options.runtimeOptions || {}).zuzu_eval(source, options);
      }
      function zuzu_run(source, options = {}) {
        return getDefaultBrowserRuntime(options.runtimeOptions || {}).zuzu_run(source, options);
      }
      function zuzu_compile(source, options = {}) {
        return getDefaultBrowserRuntime(options.runtimeOptions || {}).zuzu_compile(source, options);
      }
      function installGlobalApis(root = globalThis) {
        if (!root || typeof root !== "object") {
          return null;
        }
        root.zuzu_eval = zuzu_eval;
        root.zuzu_run = zuzu_run;
        root.zuzu_compile = zuzu_compile;
        root.zuzu_runtime = getDefaultBrowserRuntime;
        return root;
      }
      function runEmbeddedScripts(runtime, options = {}) {
        const doc = options.document || (typeof document !== "undefined" ? document : null);
        if (!doc) {
          return [];
        }
        const selector = options.selector || 'script[type="text/x-zuzuscript"]';
        const filenamePrefix = options.filenamePrefix || "/<embedded>";
        const scripts = Array.from(doc.querySelectorAll(selector));
        const log = typeof options.consoleLog === "function" ? options.consoleLog : (line) => console.log(line);
        const errorLog = typeof options.consoleError === "function" ? options.consoleError : (err) => console.error(err);
        const results = [];
        for (let i = 0; i < scripts.length; i++) {
          const script = scripts[i];
          const source = script.textContent || "";
          try {
            const result = runtime.zuzu_run(source, {
              filename: `${filenamePrefix}-${i + 1}.zzs`,
              throwOnError: options.throwOnError !== false
            });
            if (result.stdout) {
              for (const line of result.stdout.trimEnd().split(/\r?\n/u)) {
                if (line) {
                  log(line);
                }
              }
            }
            results.push(result);
          } catch (err) {
            errorLog(err);
            results.push(err);
            if (options.stopOnError !== false) {
              throw err;
            }
          }
        }
        return results;
      }
      function autoRunEmbeddedScripts(options = {}) {
        const doc = options.document || (typeof document !== "undefined" ? document : null);
        if (!doc) {
          return null;
        }
        const runtime = options.runtime || getDefaultBrowserRuntime({
          runtimeOptions: options.runtimeOptions || {}
        });
        const runNow = () => runEmbeddedScripts(runtime, options);
        if (doc.readyState === "loading") {
          doc.addEventListener("DOMContentLoaded", runNow, { once: true });
          return runtime;
        }
        runNow();
        return runtime;
      }
      if (typeof window !== "undefined" && window && window.document && !window.__ZUZU_BROWSER_NO_AUTORUN__) {
        installGlobalApis(window);
        autoRunEmbeddedScripts({});
      }
      module2.exports = {
        addModule: addBrowserModule,
        createBrowserRuntime: createConfiguredBrowserRuntime,
        createBrowserGuiBridge,
        createBrowserGuiRenderer,
        getDefaultBrowserRuntime,
        zuzu_eval,
        zuzu_run,
        zuzu_compile,
        installGlobalApis,
        runEmbeddedScripts,
        autoRunEmbeddedScripts
      };
    }
  });

  // ../../../../../tmp/zuzu-browser-build.UGYrnC/browser-bundle-entry.generated.js
  var require_browser_bundle_entry_generated = __commonJS({
    "../../../../../tmp/zuzu-browser-build.UGYrnC/browser-bundle-entry.generated.js"(exports2, module2) {
      var { createBrowserStdlib } = require_browser_stdlib_generated();
      var { browserWorkerSource } = require_browser_worker_source_generated();
      var browserStdlib = createBrowserStdlib();
      browserStdlib.workerSource = browserWorkerSource;
      globalThis.__ZUZU_BROWSER_DEFAULT_RUNTIME_OPTIONS__ = browserStdlib;
      module2.exports = require_browser_bundle_entry();
    }
  });
  return require_browser_bundle_entry_generated();
})();
