var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};

// src/runtime/edge-functions/sdk/consts.js
var require_consts = __commonJS({
  "src/runtime/edge-functions/sdk/consts.js"(exports, module) {
    "use strict";
    module.exports = {
      STDOUT_FD: 1,
      STDERR_FD: 2,
      ENV_VAR_NAMESPACE_EDGIO_CONFIG: "edgio-config",
      ENV_VAR_NAMESPACE_EDGIO_ORIGINS: "edgio-origins",
      ENV_VAR_NAMESPACE_EDGIO_PROPENVVAR: "edgio-property-environment-variables",
      ENV_VAR_NAMESPACE_EDGIO_FEATURE_FLAGS: "edgio-feature-flags",
      ENV_VAR_NAMESPACE_EDGIO_USRVAR: "edgio-usrvar",
      ENV_VAR_NAMESPACE_EDGIO_GEO: "edgio-geo",
      ENV_VAR_NAMESPACE_EDGIO_WURFL: "edgio-wurfl",
      ENV_VAR_NAMESPACE_EDGIO_VIRT: "edgio-virt",
      ENV_VAR_NAMESPACE_EDGIO_HTTP: "edgio-http",
      UTF_8: "utf-8",
      WASM_METRIC_JSON_PARSE_INVOCATION_TOTAL: 1e3,
      WASM_METRIC_JSON_STRINGIFY_INVOCATION_TOTAL: 1001,
      WASM_METRIC_JSON_PARSE_MICROSECONDS_TOTAL: 1002,
      WASM_METRIC_JSON_STRINGIFY_MICROSECONDS_TOTAL: 1003,
      WASM_METRIC_TEXT_ENCODE_INVOCATION_TOTAL: 1004,
      WASM_METRIC_TEXT_DECODE_INVOCATION_TOTAL: 1005,
      WASM_METRIC_TEXT_ENCODE_MICROSECONDS_TOTAL: 1006,
      WASM_METRIC_TEXT_DECODE_MICROSECONDS_TOTAL: 1007,
      WASM_METRIC_HTMLTRANSFORMER_CTOR_INVOCATIONS_TOTAL: 1008,
      WASM_METRIC_HTMLTRANSFORMER_CTOR_MICROSECONDS_TOTAL: 1009,
      WASM_METRIC_HTMLTRANSFORMER_WRITE_INVOCATIONS_TOTAL: 1010,
      WASM_METRIC_HTMLTRANSFORMER_WRITE_MICROSECONDS_TOTAL: 1011,
      WASM_METRIC_HTMLTRANSFORMER_END_INVOCATIONS_TOTAL: 1012,
      WASM_METRIC_HTMLTRANSFORMER_END_MICROSECONDS_TOTAL: 1013,
      WASM_METRIC_URL_CTOR_INVOCATIONS_TOTAL: 1014,
      WASM_METRIC_URL_CTOR_MICROSECONDS_TOTAL: 1015,
      WASM_METRIC_PARSEURL_INVOCATIONS_TOTAL: 1016,
      WASM_METRIC_PARSEURL_MICROSECONDS_TOTAL: 1017,
      EVENT_ERROR: -1,
      EVENT_NONE: 0,
      EVENT_IO_FETCH: 1,
      EVENT_IO_RESPONSE_CHUNK: 2,
      EVENT_IO_REQUEST_CHUNK: 3,
      INTERNAL_ERROR_PREFIX: "Internal Error: "
    };
  }
});

// src/runtime/edge-functions/sdk/symbols.js
var require_symbols = __commonJS({
  "src/runtime/edge-functions/sdk/symbols.js"(exports, module) {
    "use strict";
    module.exports = {
      AppendFn: Symbol("append-fn"),
      Body: Symbol("body"),
      BodyOnHost: Symbol("body-on-host"),
      BodyReadOffset: Symbol("body-read-offset"),
      BodyUsed: Symbol("body-used"),
      CheckFn: Symbol("check-fn"),
      Chunks: Symbol("Chunks"),
      Controller: Symbol("Controller"),
      Done: Symbol("Done"),
      EdgioId: Symbol("edgio-id"),
      Encoding: Symbol("encoding"),
      ErrorCode: Symbol("error-code"),
      ErrorState: Symbol("error-state"),
      Fatal: Symbol("fatal"),
      GetBodyChunkFn: Symbol("get-body-chunk-fn"),
      GetStreamingBodyChunkFn: Symbol("get-streaming-body-chunk-fn"),
      GetFn: Symbol("get-fn"),
      KeysFn: Symbol("keys-fn"),
      MoveBodyToHost: Symbol("move-body-to-host"),
      Namespace: Symbol("namespace"),
      Options: Symbol("options"),
      Origins: Symbol("edgio-origins"),
      PendingNextPromise: Symbol("PendingNextPromise"),
      PendingNextPromiseReject: Symbol("PendingNextPromiseReject"),
      PendingNextPromiseResolve: Symbol("PendingNextPromiseResolve"),
      PendingResponseChunks: Symbol("PendingResponseChunks"),
      PromisifyAsyncHostcall: Symbol("PromisifyAsyncHostcall"),
      QueuingStrategy: Symbol("QueuingStrategy"),
      Redirected: Symbol("redirected"),
      RemoveFn: Symbol("remove-fn"),
      ReqOrRespObject: Symbol("req-or-resp-object"),
      ReqRespHeaders: Symbol("req-resp-headers"),
      RequestObject: Symbol("request-object"),
      ResponseObject: Symbol("response-object"),
      SendToClient: Symbol("send-to-client"),
      SetFn: Symbol("set-fn"),
      Stream: Symbol("Stream"),
      UnderlyingSource: Symbol("UnderlyingSource"),
      Url: Symbol("url")
    };
  }
});

// src/runtime/edge-functions/bundled-object-inspect.js
var require_bundled_object_inspect = __commonJS({
  "src/runtime/edge-functions/bundled-object-inspect.js"(exports, module) {
    "use strict";
    var __getOwnPropNames2 = Object.getOwnPropertyNames;
    var __commonJS2 = (cb, mod) => function __require() {
      return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
    };
    var require_util_inspect = __commonJS2({
      "util.inspect.js"() {
      }
    });
    var hasMap = typeof Map === "function" && Map.prototype;
    var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null;
    var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === "function" ? mapSizeDescriptor.get : null;
    var mapForEach = hasMap && Map.prototype.forEach;
    var hasSet = typeof Set === "function" && Set.prototype;
    var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null;
    var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === "function" ? setSizeDescriptor.get : null;
    var setForEach = hasSet && Set.prototype.forEach;
    var hasWeakMap = typeof WeakMap === "function" && WeakMap.prototype;
    var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
    var hasWeakSet = typeof WeakSet === "function" && WeakSet.prototype;
    var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
    var hasWeakRef = typeof WeakRef === "function" && WeakRef.prototype;
    var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
    var booleanValueOf = Boolean.prototype.valueOf;
    var objectToString = Object.prototype.toString;
    var functionToString = Function.prototype.toString;
    var $match = String.prototype.match;
    var $slice = String.prototype.slice;
    var $replace = String.prototype.replace;
    var $toUpperCase = String.prototype.toUpperCase;
    var $toLowerCase = String.prototype.toLowerCase;
    var $test = RegExp.prototype.test;
    var $concat = Array.prototype.concat;
    var $join = Array.prototype.join;
    var $arrSlice = Array.prototype.slice;
    var $floor = Math.floor;
    var bigIntValueOf = typeof BigInt === "function" ? BigInt.prototype.valueOf : null;
    var gOPS = Object.getOwnPropertySymbols;
    var symToString = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol.prototype.toString : null;
    var hasShammedSymbols = typeof Symbol === "function" && typeof Symbol.iterator === "object";
    var toStringTag = typeof Symbol === "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? "object" : "symbol") ? Symbol.toStringTag : null;
    var isEnumerable = Object.prototype.propertyIsEnumerable;
    var gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O) {
      return O.__proto__;
    } : null);
    function addNumericSeparator(num, str) {
      if (num === Infinity || num === -Infinity || num !== num || num && num > -1e3 && num < 1e3 || $test.call(/e/, str)) {
        return str;
      }
      var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;
      if (typeof num === "number") {
        var int = num < 0 ? -$floor(-num) : $floor(num);
        if (int !== num) {
          var intStr = String(int);
          var dec = $slice.call(str, intStr.length + 1);
          return $replace.call(intStr, sepRegex, "$&_") + "." + $replace.call($replace.call(dec, /([0-9]{3})/g, "$&_"), /_$/, "");
        }
      }
      return $replace.call(str, sepRegex, "$&_");
    }
    var utilInspect = require_util_inspect();
    var inspectCustom = utilInspect.custom;
    var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null;
    module.exports = function inspect_(obj, options, depth, seen) {
      var opts = options || {};
      if (has(opts, "quoteStyle") && (opts.quoteStyle !== "single" && opts.quoteStyle !== "double")) {
        throw new TypeError('option "quoteStyle" must be "single" or "double"');
      }
      if (has(opts, "maxStringLength") && (typeof opts.maxStringLength === "number" ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) {
        throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
      }
      var customInspect = has(opts, "customInspect") ? opts.customInspect : true;
      if (typeof customInspect !== "boolean" && customInspect !== "symbol") {
        throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");
      }
      if (has(opts, "indent") && opts.indent !== null && opts.indent !== "	" && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) {
        throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');
      }
      if (has(opts, "numericSeparator") && typeof opts.numericSeparator !== "boolean") {
        throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');
      }
      var numericSeparator = opts.numericSeparator;
      if (typeof obj === "undefined") {
        return "undefined";
      }
      if (obj === null) {
        return "null";
      }
      if (typeof obj === "boolean") {
        return obj ? "true" : "false";
      }
      if (typeof obj === "string") {
        return inspectString(obj, opts);
      }
      if (typeof obj === "number") {
        if (obj === 0) {
          return Infinity / obj > 0 ? "0" : "-0";
        }
        var str = String(obj);
        return numericSeparator ? addNumericSeparator(obj, str) : str;
      }
      if (typeof obj === "bigint") {
        var bigIntStr = String(obj) + "n";
        return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;
      }
      var maxDepth = typeof opts.depth === "undefined" ? 5 : opts.depth;
      if (typeof depth === "undefined") {
        depth = 0;
      }
      if (depth >= maxDepth && maxDepth > 0 && typeof obj === "object") {
        return isArray(obj) ? "[Array]" : "[Object]";
      }
      var indent = getIndent(opts, depth);
      if (typeof seen === "undefined") {
        seen = [];
      } else if (indexOf(seen, obj) >= 0) {
        return "[Circular]";
      }
      function inspect(value, from, noIndent) {
        if (from) {
          seen = $arrSlice.call(seen);
          seen.push(from);
        }
        if (noIndent) {
          var newOpts = {
            depth: opts.depth
          };
          if (has(opts, "quoteStyle")) {
            newOpts.quoteStyle = opts.quoteStyle;
          }
          return inspect_(value, newOpts, depth + 1, seen);
        }
        return inspect_(value, opts, depth + 1, seen);
      }
      if (typeof obj === "function" && !isRegExp(obj)) {
        var name = nameOf(obj);
        var keys = arrObjKeys(obj, inspect);
        return "[Function" + (name ? ": " + name : " (anonymous)") + "]" + (keys.length > 0 ? " { " + $join.call(keys, ", ") + " }" : "");
      }
      if (isSymbol(obj)) {
        var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, "$1") : symToString.call(obj);
        return typeof obj === "object" && !hasShammedSymbols ? markBoxed(symString) : symString;
      }
      if (isElement(obj)) {
        var s = "<" + $toLowerCase.call(String(obj.nodeName));
        var attrs = obj.attributes || [];
        for (var i = 0; i < attrs.length; i++) {
          s += " " + attrs[i].name + "=" + wrapQuotes(quote(attrs[i].value), "double", opts);
        }
        s += ">";
        if (obj.childNodes && obj.childNodes.length) {
          s += "...";
        }
        s += "</" + $toLowerCase.call(String(obj.nodeName)) + ">";
        return s;
      }
      if (isArray(obj)) {
        if (obj.length === 0) {
          return "[]";
        }
        var xs = arrObjKeys(obj, inspect);
        if (indent && !singleLineValues(xs)) {
          return "[" + indentedJoin(xs, indent) + "]";
        }
        return "[ " + $join.call(xs, ", ") + " ]";
      }
      if (isError(obj)) {
        var parts = arrObjKeys(obj, inspect);
        if (!("cause" in Error.prototype) && "cause" in obj && !isEnumerable.call(obj, "cause")) {
          return "{ [" + String(obj) + "] " + $join.call($concat.call("[cause]: " + inspect(obj.cause), parts), ", ") + " }";
        }
        if (parts.length === 0) {
          return "[" + String(obj) + "]";
        }
        return "{ [" + String(obj) + "] " + $join.call(parts, ", ") + " }";
      }
      if (typeof obj === "object" && customInspect) {
        if (inspectSymbol && typeof obj[inspectSymbol] === "function" && utilInspect) {
          return utilInspect(obj, { depth: maxDepth - depth });
        } else if (customInspect !== "symbol" && typeof obj.inspect === "function") {
          return obj.inspect();
        }
      }
      if (isMap(obj)) {
        var mapParts = [];
        if (mapForEach) {
          mapForEach.call(obj, function(value, key) {
            mapParts.push(inspect(key, obj, true) + " => " + inspect(value, obj));
          });
        }
        return collectionOf("Map", mapSize.call(obj), mapParts, indent);
      }
      if (isSet(obj)) {
        var setParts = [];
        if (setForEach) {
          setForEach.call(obj, function(value) {
            setParts.push(inspect(value, obj));
          });
        }
        return collectionOf("Set", setSize.call(obj), setParts, indent);
      }
      if (isWeakMap(obj)) {
        return weakCollectionOf("WeakMap");
      }
      if (isWeakSet(obj)) {
        return weakCollectionOf("WeakSet");
      }
      if (isWeakRef(obj)) {
        return weakCollectionOf("WeakRef");
      }
      if (isNumber(obj)) {
        return markBoxed(inspect(Number(obj)));
      }
      if (isBigInt(obj)) {
        return markBoxed(inspect(bigIntValueOf.call(obj)));
      }
      if (isBoolean(obj)) {
        return markBoxed(booleanValueOf.call(obj));
      }
      if (isString(obj)) {
        return markBoxed(inspect(String(obj)));
      }
      if (!isDate(obj) && !isRegExp(obj)) {
        var ys = arrObjKeys(obj, inspect);
        var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
        var protoTag = obj instanceof Object ? "" : "null prototype";
        var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? "Object" : "";
        var constructorTag = isPlainObject || typeof obj.constructor !== "function" ? "" : obj.constructor.name ? obj.constructor.name + " " : "";
        var tag = constructorTag + (stringTag || protoTag ? "[" + $join.call($concat.call([], stringTag || [], protoTag || []), ": ") + "] " : "");
        if (ys.length === 0) {
          return tag + "{}";
        }
        if (indent) {
          return tag + "{" + indentedJoin(ys, indent) + "}";
        }
        return tag + "{ " + $join.call(ys, ", ") + " }";
      }
      return String(obj);
    };
    function wrapQuotes(s, defaultStyle, opts) {
      var quoteChar = (opts.quoteStyle || defaultStyle) === "double" ? '"' : "'";
      return quoteChar + s + quoteChar;
    }
    function quote(s) {
      return $replace.call(String(s), /"/g, "&quot;");
    }
    function isArray(obj) {
      return toStr(obj) === "[object Array]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj));
    }
    function isDate(obj) {
      return toStr(obj) === "[object Date]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj));
    }
    function isRegExp(obj) {
      return toStr(obj) === "[object RegExp]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj));
    }
    function isError(obj) {
      return toStr(obj) === "[object Error]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj));
    }
    function isString(obj) {
      return toStr(obj) === "[object String]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj));
    }
    function isNumber(obj) {
      return toStr(obj) === "[object Number]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj));
    }
    function isBoolean(obj) {
      return toStr(obj) === "[object Boolean]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj));
    }
    function isSymbol(obj) {
      if (hasShammedSymbols) {
        return obj && typeof obj === "object" && obj instanceof Symbol;
      }
      if (typeof obj === "symbol") {
        return true;
      }
      if (!obj || typeof obj !== "object" || !symToString) {
        return false;
      }
      try {
        symToString.call(obj);
        return true;
      } catch (e) {
      }
      return false;
    }
    function isBigInt(obj) {
      if (!obj || typeof obj !== "object" || !bigIntValueOf) {
        return false;
      }
      try {
        bigIntValueOf.call(obj);
        return true;
      } catch (e) {
      }
      return false;
    }
    var hasOwn = Object.prototype.hasOwnProperty || function(key) {
      return key in this;
    };
    function has(obj, key) {
      return hasOwn.call(obj, key);
    }
    function toStr(obj) {
      return objectToString.call(obj);
    }
    function nameOf(f) {
      if (f.name) {
        return f.name;
      }
      var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/);
      if (m) {
        return m[1];
      }
      return null;
    }
    function indexOf(xs, x) {
      if (xs.indexOf) {
        return xs.indexOf(x);
      }
      for (var i = 0, l = xs.length; i < l; i++) {
        if (xs[i] === x) {
          return i;
        }
      }
      return -1;
    }
    function isMap(x) {
      if (!mapSize || !x || typeof x !== "object") {
        return false;
      }
      try {
        mapSize.call(x);
        try {
          setSize.call(x);
        } catch (s) {
          return true;
        }
        return x instanceof Map;
      } catch (e) {
      }
      return false;
    }
    function isWeakMap(x) {
      if (!weakMapHas || !x || typeof x !== "object") {
        return false;
      }
      try {
        weakMapHas.call(x, weakMapHas);
        try {
          weakSetHas.call(x, weakSetHas);
        } catch (s) {
          return true;
        }
        return x instanceof WeakMap;
      } catch (e) {
      }
      return false;
    }
    function isWeakRef(x) {
      if (!weakRefDeref || !x || typeof x !== "object") {
        return false;
      }
      try {
        weakRefDeref.call(x);
        return true;
      } catch (e) {
      }
      return false;
    }
    function isSet(x) {
      if (!setSize || !x || typeof x !== "object") {
        return false;
      }
      try {
        setSize.call(x);
        try {
          mapSize.call(x);
        } catch (m) {
          return true;
        }
        return x instanceof Set;
      } catch (e) {
      }
      return false;
    }
    function isWeakSet(x) {
      if (!weakSetHas || !x || typeof x !== "object") {
        return false;
      }
      try {
        weakSetHas.call(x, weakSetHas);
        try {
          weakMapHas.call(x, weakMapHas);
        } catch (s) {
          return true;
        }
        return x instanceof WeakSet;
      } catch (e) {
      }
      return false;
    }
    function isElement(x) {
      if (!x || typeof x !== "object") {
        return false;
      }
      if (typeof HTMLElement !== "undefined" && x instanceof HTMLElement) {
        return true;
      }
      return typeof x.nodeName === "string" && typeof x.getAttribute === "function";
    }
    function inspectString(str, opts) {
      if (str.length > opts.maxStringLength) {
        var remaining = str.length - opts.maxStringLength;
        var trailer = "... " + remaining + " more character" + (remaining > 1 ? "s" : "");
        return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer;
      }
      var s = $replace.call($replace.call(str, /(['\\])/g, "\\$1"), /[\x00-\x1f]/g, lowbyte);
      return wrapQuotes(s, "single", opts);
    }
    function lowbyte(c) {
      var n = c.charCodeAt(0);
      var x = {
        8: "b",
        9: "t",
        10: "n",
        12: "f",
        13: "r"
      }[n];
      if (x) {
        return "\\" + x;
      }
      return "\\x" + (n < 16 ? "0" : "") + $toUpperCase.call(n.toString(16));
    }
    function markBoxed(str) {
      return "Object(" + str + ")";
    }
    function weakCollectionOf(type) {
      return type + " { ? }";
    }
    function collectionOf(type, size, entries, indent) {
      var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ", ");
      return type + " (" + size + ") {" + joinedEntries + "}";
    }
    function singleLineValues(xs) {
      for (var i = 0; i < xs.length; i++) {
        if (indexOf(xs[i], "\n") >= 0) {
          return false;
        }
      }
      return true;
    }
    function getIndent(opts, depth) {
      var baseIndent;
      if (opts.indent === "	") {
        baseIndent = "	";
      } else if (typeof opts.indent === "number" && opts.indent > 0) {
        baseIndent = $join.call(Array(opts.indent + 1), " ");
      } else {
        return null;
      }
      return {
        base: baseIndent,
        prev: $join.call(Array(depth + 1), baseIndent)
      };
    }
    function indentedJoin(xs, indent) {
      if (xs.length === 0) {
        return "";
      }
      var lineJoiner = "\n" + indent.prev + indent.base;
      return lineJoiner + $join.call(xs, "," + lineJoiner) + "\n" + indent.prev;
    }
    function arrObjKeys(obj, inspect) {
      var isArr = isArray(obj);
      var xs = [];
      if (isArr) {
        xs.length = obj.length;
        for (var i = 0; i < obj.length; i++) {
          xs[i] = has(obj, i) ? inspect(obj[i], obj) : "";
        }
      }
      var syms = typeof gOPS === "function" ? gOPS(obj) : [];
      var symMap;
      if (hasShammedSymbols) {
        symMap = {};
        for (var k = 0; k < syms.length; k++) {
          symMap["$" + syms[k]] = syms[k];
        }
      }
      for (var key in obj) {
        if (!has(obj, key)) {
          continue;
        }
        if (isArr && String(Number(key)) === key && key < obj.length) {
          continue;
        }
        if (hasShammedSymbols && symMap["$" + key] instanceof Symbol) {
          continue;
        } else if ($test.call(/[^\w$]/, key)) {
          xs.push(inspect(key, obj) + ": " + inspect(obj[key], obj));
        } else {
          xs.push(key + ": " + inspect(obj[key], obj));
        }
      }
      if (typeof gOPS === "function") {
        for (var j = 0; j < syms.length; j++) {
          if (isEnumerable.call(obj, syms[j])) {
            xs.push("[" + inspect(syms[j]) + "]: " + inspect(obj[syms[j]], obj));
          }
        }
      }
      return xs;
    }
  }
});

// src/runtime/edge-functions/sdk/readable-stream.js
var require_readable_stream = __commonJS({
  "src/runtime/edge-functions/sdk/readable-stream.js"(exports, module) {
    "use strict";
    var {
      Chunks,
      Controller,
      Done,
      ErrorState,
      PendingNextPromise,
      PendingNextPromiseReject,
      PendingNextPromiseResolve,
      QueuingStrategy,
      Stream,
      UnderlyingSource
    } = require_symbols();
    var promisify = function ReadableStream_promisify(fn) {
      return function ReadableStream_promisify_execute(...args) {
        return new Promise(function ReadableStream_promise(resolve, reject) {
          try {
            resolve(fn(...args));
          } catch (err) {
            reject(err);
          }
        });
      };
    };
    var ReadableStreamDefaultController = class {
      constructor(stream) {
        __publicField(this, "enqueue", function ReadableStreamDefaultController_enqueue(data) {
          this[Stream].push(data);
        });
        __publicField(this, "close", function ReadableStreamDefaultController_close() {
          this[Stream].push();
        });
        __publicField(this, "error", function ReadableStreamDefaultController_error(error) {
          this[Stream].push(error);
        });
        this[Stream] = stream;
      }
    };
    var ReadableByteStreamController = class {
      constructor(stream) {
        __publicField(this, "enqueue", function ReadableByteStreamController_enqueue(data) {
          this[Stream].push(data);
        });
        __publicField(this, "close", function ReadableByteStreamController_close() {
          this[Stream].push();
        });
        __publicField(this, "error", function ReadableByteStreamController_error(error) {
          this[Stream].push(error);
        });
        this[Stream] = stream;
      }
    };
    var _a;
    var ReadableStream = class {
      constructor(underlyingSource, queuingStrategy) {
        __publicField(this, "ReadableStream_constructor", function ReadableStream_constructor(underlyingSource, queuingStrategy) {
          this[UnderlyingSource] = underlyingSource;
          this[QueuingStrategy] = queuingStrategy;
          if (underlyingSource?.type === "bytes") {
            this[Controller] = new ReadableByteStreamController(this);
          } else {
            this[Controller] = new ReadableStreamDefaultController(this);
          }
          this[Chunks] = [];
          this[Done] = false;
          this[ErrorState] = null;
          if (underlyingSource?.start) {
            const self = this;
            promisify(underlyingSource.start)(this[Controller]).catch(function ReadableStream_error(err) {
              self[Controller].error(err);
            });
          }
          return this;
        });
        __publicField(this, _a, function ReadableStream_asyncIterator() {
          return this;
        });
        __publicField(this, "next", async function ReadableStream_next() {
          if (this[PendingNextPromise]) {
            throw new Error(
              "Cannot call next() while a promise is pending from the previous call to next()"
            );
          }
          if (this[ErrorState]) {
            throw this[ErrorState];
          }
          if (this[Chunks].length > 0) {
            const nextChunk = this[Chunks].shift();
            if (nextChunk.error) {
              this[ErrorState] = nextChunk.error;
              throw nextChunk.error;
            }
            return nextChunk;
          }
          const self = this;
          this[PendingNextPromise] = new Promise(function ReadableStream_next_promise(resolve, reject) {
            self[PendingNextPromiseResolve] = resolve;
            self[PendingNextPromiseReject] = reject;
          });
          return this[PendingNextPromise];
        });
        __publicField(this, "push", function ReadableStream_push(data) {
          if (this[Done]) {
            return;
          }
          if (data === void 0) {
            this[Chunks].push({ done: true });
            this[Done] = true;
          } else if (data instanceof Error) {
            this[Chunks].push({ error: data, done: true });
            this[Done] = true;
          } else {
            this[Chunks].push({ value: data, done: false });
          }
          if (this[PendingNextPromise]) {
            this[PendingNextPromise] = null;
            const resolve = this[PendingNextPromiseResolve];
            this[PendingNextPromiseResolve] = null;
            const reject = this[PendingNextPromiseReject];
            this[PendingNextPromiseReject] = null;
            const nextValue = this[Chunks].shift();
            if (nextValue.error) {
              this[ErrorState] = nextValue.error;
              reject(nextValue.error);
            } else {
              resolve(nextValue);
            }
          }
        });
        return this.ReadableStream_constructor(underlyingSource, queuingStrategy);
      }
      get locked() {
        return false;
      }
    };
    _a = Symbol.asyncIterator;
    module.exports = {
      ReadableStream
    };
  }
});

// src/runtime/edge-functions/sdk/edgio-readable-stream-reader.js
var require_edgio_readable_stream_reader = __commonJS({
  "src/runtime/edge-functions/sdk/edgio-readable-stream-reader.js"(exports, module) {
    "use strict";
    var {
      BodyReadOffset,
      Done,
      PendingResponseChunks,
      PromisifyAsyncHostcall,
      ReqOrRespObject,
      BodyUsed
    } = require_symbols();
    var MAX_CHUNK_SIZE = 64 * 1024;
    function getEdgioReadableStreamReader({ host, _feature_flags }) {
      let EdgioReadableResponseStreamReader = class EdgioReadableResponseStreamReader {
        constructor(response) {
          __publicField(this, "read", async function EdgioReadableResponseStreamReader_read() {
            if (this[Done]) {
              return { value: void 0, done: true };
            }
            this[ReqOrRespObject][BodyUsed] = true;
            host.hostcall_event_enable_response_events(this[ReqOrRespObject].edgioId);
            await globalThis[PromisifyAsyncHostcall](
              globalThis[PendingResponseChunks],
              this[ReqOrRespObject].edgioId
            );
            globalThis[PendingResponseChunks].delete(this[ReqOrRespObject].edgioId);
            let rawChunk;
            try {
              rawChunk = host.hostcall_resp_get_next_body_chunk(
                this[ReqOrRespObject].edgioId,
                MAX_CHUNK_SIZE
              );
            } catch (e) {
              this[Done] = true;
              throw e;
            }
            if (rawChunk === void 0) {
              this[Done] = true;
              return { value: void 0, done: true };
            }
            const chunk = new Uint8Array(rawChunk);
            return { value: chunk, done: false };
          });
          this[Done] = false;
          this[ReqOrRespObject] = response;
        }
      };
      let EdgioReadableRequestStreamReader = class EdgioReadableRequestStreamReader {
        constructor(request) {
          __publicField(this, "read", async function EdgioReadableRequestStreamReader_read() {
            if (this[Done]) {
              return { value: void 0, done: true };
            }
            this[ReqOrRespObject][BodyUsed] = true;
            let rawChunk = host.hostcall_req_get_body_chunk(
              this[ReqOrRespObject].edgioId,
              this[BodyReadOffset],
              MAX_CHUNK_SIZE
            );
            if (rawChunk === void 0) {
              this[Done] = true;
              return { value: void 0, done: true };
            }
            this[BodyReadOffset] += rawChunk.byteLength;
            const chunk = new Uint8Array(rawChunk);
            return { value: chunk, done: false };
          });
          this[Done] = false;
          this[BodyReadOffset] = 0;
          this[ReqOrRespObject] = request;
        }
      };
      return {
        EdgioReadableResponseStreamReader,
        EdgioReadableRequestStreamReader
      };
    }
    module.exports = getEdgioReadableStreamReader;
  }
});

// src/runtime/edge-functions/sdk.js
var require_sdk = __commonJS({
  "src/runtime/edge-functions/sdk.js"(exports, module) {
    "use strict";
    module.exports = function sdk(runtime, edgeFunctions) {
      const { host, utility, feature_flags } = runtime;
      const {
        STDOUT_FD,
        STDERR_FD,
        ENV_VAR_NAMESPACE_EDGIO_CONFIG,
        ENV_VAR_NAMESPACE_EDGIO_ORIGINS,
        ENV_VAR_NAMESPACE_EDGIO_PROPENVVAR,
        ENV_VAR_NAMESPACE_EDGIO_FEATURE_FLAGS,
        ENV_VAR_NAMESPACE_EDGIO_USRVAR,
        ENV_VAR_NAMESPACE_EDGIO_GEO,
        ENV_VAR_NAMESPACE_EDGIO_WURFL,
        ENV_VAR_NAMESPACE_EDGIO_VIRT,
        ENV_VAR_NAMESPACE_EDGIO_HTTP,
        UTF_8,
        WASM_METRIC_JSON_PARSE_INVOCATION_TOTAL,
        WASM_METRIC_JSON_STRINGIFY_INVOCATION_TOTAL,
        WASM_METRIC_JSON_PARSE_MICROSECONDS_TOTAL,
        WASM_METRIC_JSON_STRINGIFY_MICROSECONDS_TOTAL,
        WASM_METRIC_TEXT_ENCODE_INVOCATION_TOTAL,
        WASM_METRIC_TEXT_DECODE_INVOCATION_TOTAL,
        WASM_METRIC_TEXT_ENCODE_MICROSECONDS_TOTAL,
        WASM_METRIC_TEXT_DECODE_MICROSECONDS_TOTAL,
        WASM_METRIC_URL_CTOR_INVOCATIONS_TOTAL,
        WASM_METRIC_URL_CTOR_MICROSECONDS_TOTAL,
        WASM_METRIC_PARSEURL_INVOCATIONS_TOTAL,
        WASM_METRIC_PARSEURL_MICROSECONDS_TOTAL,
        EVENT_IO_FETCH,
        EVENT_IO_RESPONSE_CHUNK,
        INTERNAL_ERROR_PREFIX
      } = require_consts();
      const {
        AppendFn,
        Body,
        BodyOnHost,
        BodyUsed,
        CheckFn,
        EdgioId,
        Encoding,
        ErrorCode,
        Fatal,
        GetFn,
        KeysFn,
        MoveBodyToHost,
        Namespace,
        Options,
        Origins,
        PromisifyAsyncHostcall,
        PendingResponseChunks,
        Redirected,
        RemoveFn,
        ReqRespHeaders,
        RequestObject,
        ResponseObject,
        SendToClient,
        SetFn,
        Url
      } = require_symbols();
      const supportsHostcallMetricsV2 = feature_flags && feature_flags["hostcall-metrics-v2-supported"];
      const _sailfishFeatureFlags = EdgioDict(ENV_VAR_NAMESPACE_EDGIO_FEATURE_FLAGS);
      const debugLoggingEnabled = EdgioDict(ENV_VAR_NAMESPACE_EDGIO_CONFIG).get("debug") === "enabled";
      if (debugLoggingEnabled)
        host.hostcall_debug("Debug logging is enabled.");
      const inspect = require_bundled_object_inspect();
      let consoleGroupIndentDepth = 0;
      const CONSOLE_GROUP_INDENT_STEP = 2;
      const getConsoleIndent = function getConsoleIndent2() {
        return " ".repeat(consoleGroupIndentDepth);
      };
      function wrappedConsoleWrite(fdWrite, ...args) {
        fdWrite(getConsoleIndent());
        if (args.length > 0) {
          let firstArg = args[0];
          if (typeof firstArg === "string") {
            args.shift();
            firstArg = firstArg.replace(/%[oOdisf]/g, function ConsoleWrite_match(match) {
              if (args.length === 0) {
                return match;
              }
              const arg = args.shift();
              switch (match) {
                case "%o":
                case "%O":
                  return inspect(arg);
                case "%d":
                case "%i":
                  return parseInt(arg, 10).toString();
                case "%s":
                  return arg.toString();
                case "%f":
                  return parseFloat(arg).toString();
                default:
                  return match;
              }
            });
            args.unshift(firstArg);
          }
        }
        for (let i = 0; i < args.length; i++) {
          if (i !== 0) {
            fdWrite(" ");
          }
          const arg = args[i];
          const type = typeof arg;
          switch (type) {
            case "string":
              fdWrite(arg);
              break;
            case "number":
            case "function":
              fdWrite(arg.toString());
              break;
            case "boolean":
              fdWrite(arg ? "true" : "false");
              break;
            case "undefined":
              fdWrite(type);
              break;
            default:
              if (arg === null) {
                fdWrite("null");
              } else {
                fdWrite(inspect(arg));
              }
              break;
          }
        }
        fdWrite("\n");
      }
      function consoleWrite(fd, ...args) {
        const fdWrite = utility.stream_write_all.bind(this, fd);
        try {
          return wrappedConsoleWrite(fdWrite, ...args);
        } catch (e) {
          fdWrite("Exception during console output: ");
          fdWrite(e.toString());
          fdWrite("\n");
        }
      }
      const consoleCounters = /* @__PURE__ */ new Map();
      globalThis.console = {
        assert: function console_assert(condition, ...args) {
          if (!condition) {
            consoleWrite(STDERR_FD, "Assertion failed:", ...args);
          }
        },
        clear: function console_clear() {
        },
        count: function console_count(label) {
          consoleCounters.set(label, (consoleCounters.get(label) || 0) + 1);
          globalThis.console.log(`${label}: ${consoleCounters.get(label)}`);
        },
        countReset: function console_countReset(label) {
          consoleCounters.set(label, 0);
        },
        debug: consoleWrite.bind(globalThis.console, STDOUT_FD),
        dir: function console_dir(...args) {
          return globalThis.console.log(...args);
        },
        dirxml: function console_dirxml(...args) {
          return globalThis.console.log(...args);
        },
        error: consoleWrite.bind(globalThis.console, STDERR_FD),
        group: function console_group(...args) {
          if (args !== void 0) {
            globalThis.console.log(...args);
          }
          consoleGroupIndentDepth += CONSOLE_GROUP_INDENT_STEP;
        },
        groupCollapsed: function console_groupCollapsed(...args) {
          return globalThis.console.group(...args);
        },
        groupEnd: function console_groupEnd() {
          consoleGroupIndentDepth = Math.max(consoleGroupIndentDepth - CONSOLE_GROUP_INDENT_STEP, 0);
        },
        info: consoleWrite.bind(globalThis.console, STDOUT_FD),
        log: consoleWrite.bind(globalThis.console, STDOUT_FD),
        profile: function console_profile() {
        },
        table: function console_table(data, columns) {
          return globalThis.console.warn("table not implemented", data, columns);
        },
        time: function console_time() {
        },
        timeEnd: function console_timeEnd(label) {
          return globalThis.console.warn("timeEnd not implemented", label);
        },
        timeLog: function console_timeLog(label) {
          return globalThis.console.warn("timeLog not implemented", label);
        },
        timeStamp: function console_timeStamp() {
        },
        trace: consoleWrite.bind(globalThis.console, STDOUT_FD),
        warn: consoleWrite.bind(globalThis.console, STDERR_FD)
      };
      const { ReadableStream } = require_readable_stream();
      globalThis.ReadableStream = ReadableStream;
      const { EdgioReadableResponseStreamReader, EdgioReadableRequestStreamReader } = require_edgio_readable_stream_reader()(runtime);
      class EdgioReadableResponseStream {
        constructor(response) {
          this[ResponseObject] = response;
        }
        getReader() {
          return new EdgioReadableResponseStreamReader(this[ResponseObject]);
        }
      }
      class EdgioReadableRequestStream {
        constructor(request) {
          this[RequestObject] = request;
        }
        getReader() {
          return new EdgioReadableRequestStreamReader(this[RequestObject]);
        }
      }
      class EdgioHeaders {
        constructor(id, headers, { appendFn, checkFn, getFn, keysFn, removeFn, setFn }) {
          __publicField(this, "EdgioHeaders_constructor", function EdgioHeaders_constructor(id, headers, { appendFn, checkFn, getFn, keysFn, removeFn, setFn }) {
            if (this.constructor == EdgioHeaders) {
              throw new Error(
                `${INTERNAL_ERROR_PREFIX}Headers Abstract class cannot be instantiated directly.`
              );
            }
            this[EdgioId] = id;
            this[AppendFn] = appendFn;
            this[CheckFn] = checkFn;
            this[GetFn] = getFn;
            this[KeysFn] = keysFn;
            this[RemoveFn] = removeFn;
            this[SetFn] = setFn;
            if (Array.isArray(headers)) {
              headers.forEach((h) => {
                if (!Array.isArray(h)) {
                  throw new Error(
                    `When passing an array of headers, each array element must be an array of length = 2. '${h}' is type '${typeof h}' not type array.`
                  );
                }
                if (h.length !== 2) {
                  throw new Error(
                    `When passing an array of headers, each array element must be an array of length = 2. '${h}' is array of length ${h.length}.`
                  );
                }
                if (debugLoggingEnabled)
                  host.hostcall_debug(`.append(${h})`);
                this.append(h[0], h[1]);
              });
            } else if (headers && headers instanceof Headers) {
              const rawHeaders = headers.getRaw();
              Object.keys(rawHeaders).forEach((name) => {
                rawHeaders[name].forEach((value) => {
                  this.append(name, value);
                });
              });
            } else if (headers && headers instanceof EdgioHeaders) {
              for (const key of headers.keys()) {
                for (const value of headers._getValuesForKey(key)) {
                  this.append(key, value);
                }
              }
            } else if (headers && Function.prototype.toString.call(headers.constructor).match(/class.*/)) {
              throw new Error(
                `'headers' must be a 'Headers' instance, dictionary, or an array of array pairs. Found ${Function.prototype.toString.call(
                  headers.constructor
                )}`
              );
            } else if (typeof headers === "object") {
              Object.keys(headers).forEach((name) => {
                this.append(name, headers[name]);
              });
            } else if (headers !== void 0) {
              throw new Error(
                `'headers' must be a dictionary or an array of array pairs. Found type ${typeof headers}.`
              );
            }
            return this;
          });
          return this.EdgioHeaders_constructor(id, headers, {
            appendFn,
            checkFn,
            getFn,
            keysFn,
            removeFn,
            setFn
          });
        }
        _validateName(name) {
          if (name === void 0) {
            throw new Error("The 'name' argument is required, but was not present.");
          }
          if (typeof name !== "string") {
            throw new Error(`The 'name' argument must be a 'string' type, not a '${typeof name}' type.`);
          }
          return name;
        }
        _validateValue(value) {
          if (value === void 0) {
            throw new Error("The 'value' argument is required, but was not present.");
          }
          if (typeof value !== "string" && !Array.isArray(value)) {
            throw new Error(
              `The 'value' argument must be a 'string' or 'array' type, not a '${typeof value}' type.`
            );
          }
          return value;
        }
        append(name, value) {
          if (value === null || value === void 0) {
            return;
          }
          if (Array.isArray(value)) {
            for (const v of value) {
              this[AppendFn](this[EdgioId], this._validateName(name), this._validateValue(v));
            }
          } else {
            this[AppendFn](this[EdgioId], this._validateName(name), this._validateValue(value));
          }
        }
        delete(name) {
          this[RemoveFn](this[EdgioId], this._validateName(name));
        }
        entries() {
          const entries = [];
          for (const key of this.keys()) {
            entries.push([key, this.get(key)]);
          }
          return entries;
        }
        forEach(callback) {
          for (const key of this.keys()) {
            callback(this.get(key), key);
          }
        }
        get(name) {
          const headers = this[GetFn](this[EdgioId], this._validateName(name));
          if (Array.isArray(headers))
            return headers.join(", ");
          return headers === void 0 ? null : headers;
        }
        _getValuesForKey(key) {
          const headers = this[GetFn](this[EdgioId], this._validateName(key));
          if (headers === void 0 || headers === null) {
            return [];
          }
          return headers;
        }
        getSetCookie() {
          return this._getValuesForKey("set-cookie");
        }
        has(name) {
          return this[CheckFn](this[EdgioId], this._validateName(name));
        }
        keys() {
          return this[KeysFn](this[EdgioId]);
        }
        set(name, value) {
          if (value === null || value === void 0) {
            return;
          }
          this[SetFn](this[EdgioId], this._validateName(name), this._validateValue(value));
        }
        values() {
          const values = [];
          for (const key of this.keys()) {
            values.push(this.get(key));
          }
          return values;
        }
        toJSON() {
          const json = {};
          for (const key of this.keys()) {
            json[key] = this.get(key);
          }
          return json;
        }
      }
      class EdgioResponseHeaders extends EdgioHeaders {
        constructor(responseId, headers) {
          super(responseId, headers, {
            appendFn: host.hostcall_resp_append_header,
            checkFn: host.hostcall_resp_check_header,
            getFn: host.hostcall_resp_get_header_values,
            keysFn: utility.resp_get_header_names,
            removeFn: host.hostcall_resp_remove_header,
            setFn: host.hostcall_resp_set_header
          });
        }
      }
      class EdgioRequestHeaders extends EdgioHeaders {
        constructor(requestId, headers) {
          super(requestId, headers, {
            appendFn: host.hostcall_req_append_header,
            checkFn: host.hostcall_req_check_header,
            getFn: host.hostcall_req_get_header_values,
            keysFn: utility.req_get_header_names,
            removeFn: host.hostcall_req_remove_header,
            setFn: host.hostcall_req_set_header
          });
        }
      }
      class HeadersInternal {
        constructor() {
          __publicField(this, "appendFn", (_requestId, key, value) => {
            key = this.getCaseInsensitiveKey(key);
            if (!this._headers[key])
              this._headers[key] = [];
            this._headers[key].push(value);
          });
          __publicField(this, "checkFn", (_requestId, key) => {
            key = this.getCaseInsensitiveKey(key);
            return !!this._headers[key];
          });
          __publicField(this, "getFn", (_requestId, key) => {
            key = this.getCaseInsensitiveKey(key);
            if (!this._headers[key])
              return null;
            return this._headers[key];
          });
          __publicField(this, "getRawFn", () => {
            return this._headers;
          });
          __publicField(this, "keysFn", (_requestId) => {
            return Object.keys(this._headers);
          });
          __publicField(this, "removeFn", (_requestId, key) => {
            key = this.getCaseInsensitiveKey(key);
            delete this._headers[key];
          });
          __publicField(this, "setFn", (_requestId, key, value) => {
            key = this.getCaseInsensitiveKey(key);
            this._headers[key] = [value];
          });
          __publicField(this, "getCaseInsensitiveKey", (key) => {
            const asLowercase = key.toLowerCase();
            return Object.keys(this._headers).find((k) => k.toLowerCase() === asLowercase) || key;
          });
          this._headers = {};
        }
      }
      globalThis.Headers = class Headers extends EdgioHeaders {
        constructor(headers) {
          const _headersInstance = new HeadersInternal();
          super(0, headers, {
            appendFn: _headersInstance.appendFn.bind(_headersInstance),
            checkFn: _headersInstance.checkFn.bind(_headersInstance),
            getFn: _headersInstance.getFn.bind(_headersInstance),
            keysFn: _headersInstance.keysFn.bind(_headersInstance),
            removeFn: _headersInstance.removeFn.bind(_headersInstance),
            setFn: _headersInstance.setFn.bind(_headersInstance)
          });
          __publicField(this, "getRaw", () => {
            return this._headersInstance.getRawFn();
          });
          this._headersInstance = _headersInstance;
        }
      };
      globalThis.Request = class {
        constructor(input, options) {
          this[Options] = options || {};
          this[BodyUsed] = false;
          if (typeof options?.edgio?.id === "number") {
            this[EdgioId] = options?.edgio?.id;
            this[ReqRespHeaders] = new EdgioRequestHeaders(this[EdgioId]);
            this[BodyOnHost] = true;
            return;
          }
          if (typeof input !== "string") {
            throw new Error(`"string" type is accepted for the input parameter, not '${typeof input}'`);
          }
          const url = input;
          if (this[Options].method !== void 0 && typeof this[Options].method !== "string") {
            throw new Error(
              `options.method must be type 'undefined' or 'string', not '${typeof this[Options].method}'`
            );
          }
          const method = this[Options].method || "GET";
          this[EdgioId] = host.hostcall_req_create(method, url);
          this[ReqRespHeaders] = new EdgioRequestHeaders(this[EdgioId], this[Options]?.headers || {});
          const body = this[Options].body;
          delete this[Options].body;
          this[BodyUsed] = false;
          if (body) {
            this[Body] = body;
          }
          this[BodyOnHost] = false;
        }
        blob() {
          throw new Error(
            `${INTERNAL_ERROR_PREFIX}The 'blob' method is not supported by the Request class.`
          );
        }
        get body() {
          const method = this.method;
          if (method === "GET" || method === "HEAD") {
            return null;
          }
          return new EdgioReadableRequestStream(this);
        }
        get bodyUsed() {
          return this[BodyUsed];
        }
        get cache() {
          throw new Error(
            `${INTERNAL_ERROR_PREFIX}The 'cache' property is not supported by the Request class.`
          );
        }
        get credentials() {
          throw new Error(
            `${INTERNAL_ERROR_PREFIX}The 'credentials' property is not supported by the Request class.`
          );
        }
        clone() {
          throw new Error(
            `${INTERNAL_ERROR_PREFIX}The 'clone' method is not supported by the Request class.`
          );
        }
        get destination() {
          throw new Error(
            `${INTERNAL_ERROR_PREFIX}The 'destination' property is not supported by the Request class.`
          );
        }
        formData() {
          throw new Error(
            `${INTERNAL_ERROR_PREFIX}The 'formData' method is not supported by the Request class.`
          );
        }
        get headers() {
          return this[ReqRespHeaders];
        }
        get integrity() {
          throw new Error(
            `${INTERNAL_ERROR_PREFIX}The 'integrity' property is not supported by the Request class.`
          );
        }
        get method() {
          const method = host.hostcall_req_get_method(this[EdgioId]);
          return method;
        }
        set method(method) {
          return host.hostcall_req_set_method(this[EdgioId], method);
        }
        get mode() {
          throw new Error(
            `${INTERNAL_ERROR_PREFIX}The 'mode' property is not supported by the Request class.`
          );
        }
        get redirect() {
          throw new Error(
            `${INTERNAL_ERROR_PREFIX}The 'redirect' property is not supported by the Request class.`
          );
        }
        get referrer() {
          throw new Error(
            `${INTERNAL_ERROR_PREFIX}The 'referrer' property is not supported by the Request class.`
          );
        }
        get referrerPolicy() {
          throw new Error(
            `${INTERNAL_ERROR_PREFIX}The 'referrerPolicy' property is not supported by the Request class.`
          );
        }
        get signal() {
          throw new Error(
            `${INTERNAL_ERROR_PREFIX}The 'signal' property is not supported by the Request class.`
          );
        }
        async arrayBuffer() {
          await this[MoveBodyToHost]();
          this[BodyUsed] = true;
          return host.hostcall_req_get_body(this[EdgioId]);
        }
        async text() {
          const buffer = await this.arrayBuffer();
          if (buffer.byteLength === 0) {
            return "";
          }
          return new TextDecoder(UTF_8).decode(buffer);
        }
        async json() {
          return JSON.parse(await this.text());
        }
        get url() {
          return host.hostcall_req_get_uri(this[EdgioId]);
        }
        set url(uri) {
          return host.hostcall_req_set_uri(this[EdgioId], uri);
        }
        get path() {
          return host.hostcall_req_get_path(this[EdgioId]);
        }
        get edgioId() {
          return this[EdgioId];
        }
        toJSON() {
          return {
            method: this.method,
            url: this.url,
            headers: this.headers
          };
        }
        cloneWithoutBody() {
          const clone_id = host.hostcall_req_clone_without_body(this[EdgioId]);
          const req = new Request(null, {
            edgio: {
              id: clone_id
            }
          });
          this[ReqRespHeaders] = new EdgioRequestHeaders(clone_id);
          return req;
        }
        async [MoveBodyToHost]() {
          if (this[BodyOnHost]) {
            return;
          }
          const body = this[Body];
          if (body) {
            if (this.method === "GET" || this.method === "HEAD") {
              throw new Error("Request with GET/HEAD method cannot have body.");
            }
            const edgioId = this[EdgioId];
            if (typeof body === "string") {
              if (debugLoggingEnabled)
                host.hostcall_debug(`new Request(${edgioId}, len=string: ${body.length})`);
              host.hostcall_req_set_body_from_string(edgioId, body);
            } else if (body instanceof ArrayBuffer) {
              if (debugLoggingEnabled)
                host.hostcall_debug(`new Request(ArrayBuffer: len=${body.byteLength})`);
              host.hostcall_req_set_body_from_array_buffer(edgioId, body);
            } else if (ArrayBuffer.isView(body)) {
              if (debugLoggingEnabled)
                host.hostcall_debug(`new Request(TypedArray: len=${body.byteLength})`);
              host.hostcall_req_set_body_from_array_buffer(edgioId, body.buffer);
            } else if (body instanceof ReadableStream) {
              if (debugLoggingEnabled)
                host.hostcall_debug(`new Request(ReadableStream)`);
              for await (const chunk of body) {
                if (typeof chunk === "string") {
                  host.hostcall_req_append_body_from_string(edgioId, chunk);
                } else if (chunk instanceof ArrayBuffer) {
                  host.hostcall_req_append_body_from_array_buffer(edgioId, chunk);
                } else if (ArrayBuffer.isView(chunk)) {
                  host.hostcall_req_append_body_from_array_buffer(edgioId, chunk.buffer);
                } else {
                  const text = chunk?.toString();
                  if (text) {
                    host.hostcall_req_append_body_from_string(edgioId, chunk.toString());
                  } else {
                    throw new Error("new Request(ReadableStream: chunk is not string or ArrayBuffer)");
                  }
                }
              }
            } else {
              if (debugLoggingEnabled)
                host.hostcall_debug(`new Request(other: type=${typeof body})`);
              host.hostcall_req_set_body_from_string(edgioId, body.toString());
            }
          }
          this[Body] = null;
          this[BodyOnHost] = true;
        }
      };
      globalThis.Response = class {
        constructor(body, optionsOrResponse) {
          this[BodyUsed] = false;
          this[BodyOnHost] = false;
          this[Redirected] = false;
          this[Url] = null;
          if (typeof optionsOrResponse?.edgio?.id === "number") {
            this[EdgioId] = optionsOrResponse?.edgio?.id;
            this[ReqRespHeaders] = new EdgioResponseHeaders(this[EdgioId]);
            if (debugLoggingEnabled)
              host.hostcall_debug(`_edgioNew Response: ${this[EdgioId]}`);
            this[BodyOnHost] = true;
            return;
          }
          if (optionsOrResponse instanceof Response) {
            const clone = optionsOrResponse.cloneWithoutBody();
            this[EdgioId] = clone[EdgioId];
            this[ReqRespHeaders] = clone[ReqRespHeaders];
            this[Redirected] = clone[Redirected];
            this[Url] = clone[Url];
          } else {
            this[Options] = optionsOrResponse || {};
            if (isNaN(this[Options].status))
              this[Options].status = 200;
            if (this[Options].status < 200 || this[Options].status > 599 || this[Options].status === 204 || this[Options].status === 304) {
              throw new Error(
                `The status provided ${this[Options].status} must be >= 200 and <= 599, and not 204 or 304.`
              );
            }
            this[EdgioId] = host.hostcall_resp_create(this[Options].status);
            this[ReqRespHeaders] = new EdgioResponseHeaders(this[EdgioId], this[Options]?.headers || {});
          }
          if (body !== void 0) {
            if (body instanceof ArrayBuffer || body instanceof ReadableStream) {
              this[Body] = body;
            } else if (ArrayBuffer.isView(body)) {
              this[Body] = body.buffer;
            } else {
              this[Body] = new TextEncoder().encode(body).buffer;
            }
          }
        }
        blob() {
          throw new Error(
            `${INTERNAL_ERROR_PREFIX}The 'blob' method is not supported by the Response class.`
          );
        }
        get body() {
          if (this[BodyOnHost] || this[Body]) {
            return new EdgioReadableResponseStream(this);
          }
          return null;
        }
        get bodyUsed() {
          return this[BodyUsed];
        }
        clone() {
          throw new Error(
            `${INTERNAL_ERROR_PREFIX}The 'clone' method is not supported by the Response class.`
          );
        }
        formData() {
          throw new Error(
            `${INTERNAL_ERROR_PREFIX}The 'formData' method is not supported by the Response class.`
          );
        }
        get headers() {
          return this[ReqRespHeaders];
        }
        async arrayBuffer() {
          this[BodyUsed] = true;
          let bodyToReturn = new ArrayBuffer(0);
          if (!this[BodyOnHost]) {
            if (!this[Body])
              return bodyToReturn;
            if (this[Body] instanceof ArrayBuffer)
              return this[Body];
            const encoder = new TextEncoder();
            for await (let chunk of this[Body]) {
              let value = encoder.encode(chunk.toString()).buffer;
              const tmp = new Uint8Array(bodyToReturn.byteLength + value.byteLength);
              tmp.set(new Uint8Array(bodyToReturn), 0);
              tmp.set(new Uint8Array(value), bodyToReturn.byteLength);
              bodyToReturn = tmp;
            }
          } else {
            const reader = new EdgioReadableResponseStream(this).getReader();
            while (true) {
              const { done, value } = await reader.read();
              if (done)
                break;
              const tmp = new Uint8Array(bodyToReturn.byteLength + value.byteLength);
              tmp.set(new Uint8Array(bodyToReturn), 0);
              tmp.set(new Uint8Array(value), bodyToReturn.byteLength);
              bodyToReturn = tmp;
            }
          }
          return bodyToReturn;
        }
        async text() {
          const buffer = await this.arrayBuffer();
          if (buffer.byteLength === 0) {
            return "";
          }
          return new TextDecoder(UTF_8).decode(buffer);
        }
        async json() {
          return JSON.parse(await this.text());
        }
        get ok() {
          let status = this.status;
          return status >= 200 && status < 300;
        }
        static redirect(url, status) {
          return new Response(void 0, { headers: { location: url }, status: status || 302 });
        }
        set redirected(newRedirected) {
          this[Redirected] = newRedirected;
        }
        get redirected() {
          return this[Redirected];
        }
        get status() {
          return host.hostcall_resp_get_status(this[EdgioId]);
        }
        get statusText() {
          return host.hostcall_resp_get_reason(this[EdgioId]);
        }
        get type() {
          throw new Error(
            `${INTERNAL_ERROR_PREFIX}The 'type' property is not supported by the Response class.`
          );
        }
        get url() {
          return this[Url];
        }
        get edgioId() {
          return this[EdgioId];
        }
        toJSON() {
          return {
            status: this.status,
            statusText: this.statusText,
            headers: this.headers
          };
        }
        cloneWithoutBody() {
          const clone_id = host.hostcall_resp_clone_without_body(this[EdgioId]);
          const resp = new Response(null, {
            edgio: {
              id: clone_id
            }
          });
          resp[Url] = this[Url];
          resp[Redirected] = this[Redirected];
          resp[ReqRespHeaders] = new EdgioResponseHeaders(clone_id);
          return resp;
        }
        async [SendToClient]() {
          const body = this[Body];
          const edgioId = this[EdgioId];
          if (this[BodyOnHost]) {
            if (debugLoggingEnabled)
              host.hostcall_debug("sendToClient(${edgioId}) body on host already");
            host.hostcall_resp_streaming_send_to_client(edgioId);
            return;
          }
          if (body === null || body === void 0) {
            if (debugLoggingEnabled)
              host.hostcall_debug("sendToClient(${edgioId}) empty body");
            host.hostcall_resp_streaming_send_to_client(edgioId);
            host.hostcall_resp_streaming_finalize_send_body(edgioId);
            return;
          }
          if (body instanceof ReadableStream) {
            if (debugLoggingEnabled)
              host.hostcall_debug("sendToClient(${edgioId})new Response(ReadableStream)");
            host.hostcall_resp_streaming_send_to_client(edgioId);
            for await (const chunk of body) {
              if (typeof chunk === "string") {
                host.hostcall_resp_append_body_from_string(edgioId, chunk);
              } else if (chunk instanceof ArrayBuffer) {
                host.hostcall_resp_append_body_from_array_buffer(edgioId, chunk);
              } else if (ArrayBuffer.isView(chunk)) {
                host.hostcall_resp_append_body_from_array_buffer(edgioId, chunk.buffer);
              } else {
                const text = chunk?.toString();
                if (text) {
                  host.hostcall_resp_append_body_from_string(edgioId, chunk.toString());
                } else {
                  throw new Error("new Response(ReadableStream: chunk is not string or ArrayBuffer)");
                }
              }
            }
            host.hostcall_resp_streaming_finalize_send_body(edgioId);
            return;
          }
          if (debugLoggingEnabled)
            host.hostcall_debug(
              `sendToClient(${edgioId}) new Response(ArrayBuffer: len=${body.byteLength})`
            );
          host.hostcall_resp_set_body_from_array_buffer(edgioId, body);
          host.hostcall_resp_streaming_send_to_client(edgioId);
          this[Body] = null;
          this[BodyOnHost] = true;
        }
      };
      class ResponseError extends Error {
        constructor(responseErrorCode) {
          super();
          this[ErrorCode] = responseErrorCode;
        }
        get code() {
          return this[ErrorCode];
        }
        get message() {
          return host.hostcall_resp_get_error_code_message(this[ErrorCode]);
        }
        toString() {
          return `${this.message} (code: ${this.code})`;
        }
      }
      function EdgioDict(namespace) {
        const namespaces = { namespace };
        const dictProxy = new Proxy(namespaces, {
          get(target, property) {
            if (property === "get") {
              return function EdgioDict_get(key) {
                return host.hostcall_dict_get(target.namespace, key);
              };
            }
            if (property === "getBase64Decoded") {
              return function EdgioDict_getBase64Decoded(key) {
                return new Uint8Array(host.hostcall_dict_get_base64_decoded(target.namespace, key));
              };
            }
            if (property === "has") {
              return function EdgioDict_has(key) {
                return host.hostcall_dict_check(target.namespace, key);
              };
            }
            if (property === "keys") {
              return function EdgioDict_keys() {
                return utility.dict_get_keys(target.namespace);
              };
            }
            return host.hostcall_dict_get(target.namespace, property);
          },
          getOwnPropertyDescriptor(target, property) {
            return {
              value: host.hostcall_dict_get(target.namespace, property),
              writable: false,
              enumerable: true,
              configurable: true
            };
          },
          defineProperty(_target, _key, _descriptor) {
            return false;
          },
          deleteProperty(_target, _property) {
            return false;
          },
          has(target, property) {
            return host.hostcall_dict_check(target.namespace, property);
          },
          ownKeys(target) {
            return utility.dict_get_keys(target.namespace);
          }
        });
        return dictProxy;
      }
      class EdgioSet {
        constructor(namespace) {
          this[Namespace] = namespace;
        }
        has(key) {
          return host.hostcall_unique_set_check(this[Namespace], key);
        }
        keys() {
          return utility.unique_set_get_keys(this[Namespace]);
        }
        toJSON() {
          return this.keys();
        }
      }
      class EdgioMetrics {
        startTimer(index) {
          return host.hostcall_metrics_start_timer(index);
        }
        stopTimer(index) {
          return host.hostcall_metrics_stop_timer(index);
        }
        add(index, value) {
          return host.hostcall_metrics_add(index, value);
        }
      }
      function wrapFunctionCallWithMetrics(invocationCountId, microsecondTimerId, fn, ...args) {
        host.hostcall_metrics_add(invocationCountId, 1);
        host.hostcall_metrics_start_timer(microsecondTimerId);
        try {
          return fn(...args);
        } finally {
          host.hostcall_metrics_stop_timer(microsecondTimerId);
        }
      }
      const originalJSONparse = JSON.parse;
      const originalJSONstringify = JSON.stringify;
      globalThis.JSON = {
        parse: (...args) => {
          return wrapFunctionCallWithMetrics(
            WASM_METRIC_JSON_PARSE_INVOCATION_TOTAL,
            WASM_METRIC_JSON_PARSE_MICROSECONDS_TOTAL,
            originalJSONparse,
            ...args
          );
        },
        stringify: (...args) => {
          return wrapFunctionCallWithMetrics(
            WASM_METRIC_JSON_STRINGIFY_INVOCATION_TOTAL,
            WASM_METRIC_JSON_STRINGIFY_MICROSECONDS_TOTAL,
            originalJSONstringify,
            ...args
          );
        }
      };
      globalThis.module = {};
      globalThis.__dirname = "/";
      globalThis.__filename = "/index.js";
      globalThis.global = globalThis;
      globalThis.require = (moduleName) => {
        throw new Error(
          `The Node.js function "require('${moduleName}')" is not supported in edge-functions. Please refer to https://docs.edg.io/guides/v7/edge-functions#polyfills for more information.`
        );
      };
      if (supportsHostcallMetricsV2) {
        const originalURL = globalThis.URL;
        globalThis.URL = class URL extends originalURL {
          constructor(...args) {
            return wrapFunctionCallWithMetrics(
              WASM_METRIC_URL_CTOR_INVOCATIONS_TOTAL,
              WASM_METRIC_URL_CTOR_MICROSECONDS_TOTAL,
              () => super(...args)
            );
          }
        };
        const originalparseURL = globalThis.parseURL;
        globalThis.parseURL = function parseURL(...args) {
          return wrapFunctionCallWithMetrics(
            WASM_METRIC_PARSEURL_INVOCATIONS_TOTAL,
            WASM_METRIC_PARSEURL_MICROSECONDS_TOTAL,
            () => originalparseURL(...args)
          );
        };
      }
      const _HtmlTransformer_write = globalThis.HtmlTransformer.prototype.write;
      globalThis.HtmlTransformer.prototype.write = async function HtmlTransformer_write(obj) {
        if (obj instanceof Promise) {
          return this.write(await obj);
        }
        if (obj instanceof Response) {
          return this.write(obj.body);
        }
        if (obj instanceof ReadableStream || obj instanceof EdgioReadableResponseStream) {
          return this.writeFromReader(obj.getReader());
        }
        return _HtmlTransformer_write.call(this, obj);
      };
      globalThis.HtmlTransformer.prototype.writeFromReader = async function HtmlTransformer_writeFromReader(reader) {
        const self = this;
        const textDecoder = new TextDecoder();
        async function readStream() {
          const { value, done } = await reader.read();
          if (done) {
            return;
          }
          await _HtmlTransformer_write.call(self, textDecoder.decode(value));
          return await readStream();
        }
        return readStream();
      };
      globalThis.HtmlTransformer.stream = function HtmlTransformer_stream(definitions, optionalOriginalResponse) {
        function HtmlTransformer_streamImpl(response) {
          const textDecoder = new TextDecoder();
          const reader = response.body.getReader();
          function HtmlTransformer_start(controller) {
            const htmlTransformer = new globalThis.HtmlTransformer(
              definitions,
              function HtmlTransformer_enqueue(chunk) {
                controller.enqueue(chunk);
              }
            );
            return HtmlTransformer_pump();
            function HtmlTransformer_pump() {
              return reader.read().then(async function HtmlTransformer_read({ done, value }) {
                if (value) {
                  await htmlTransformer.write(textDecoder.decode(value));
                }
                if (done) {
                  await htmlTransformer.end();
                  controller.close();
                  return;
                }
                return HtmlTransformer_pump();
              });
            }
          }
          return new ReadableStream({ start: HtmlTransformer_start });
        }
        if (optionalOriginalResponse) {
          if (optionalOriginalResponse.headers.get("content-type") != "text/html" && optionalOriginalResponse.headers.get("content-type") != "application/xhtml+xml") {
            const msg = `HtmlTransformer.stream() was called with a response that is not of type "text/html" or "application/xhtml+xml". Returning the original response. content-type: "${optionalOriginalResponse.headers.get("content-type")}"`;
            console.warn(msg);
            return optionalOriginalResponse;
          }
          return new Response(
            HtmlTransformer_streamImpl(optionalOriginalResponse),
            optionalOriginalResponse
          );
        }
        return HtmlTransformer_streamImpl;
      };
      globalThis.TextDecoder = class TextDecoder {
        constructor(encoding, options) {
          __publicField(this, "decode", function TextDecoder_decode(buffer) {
            try {
              host.hostcall_metrics_add(WASM_METRIC_TEXT_DECODE_INVOCATION_TOTAL, 1);
              host.hostcall_metrics_start_timer(WASM_METRIC_TEXT_DECODE_MICROSECONDS_TOTAL);
              if (!buffer) {
                return "";
              }
              const array_buffer = ArrayBuffer.isView(buffer) ? buffer.buffer : buffer;
              if (!(array_buffer instanceof ArrayBuffer)) {
                throw new Error(
                  `Decoding supported for ArrayBuffer, TypedArray and DataView, not ${typeof buffer}`
                );
              }
              if (this[Fatal]) {
                return utility.text_decoder_decode_without_replacement(this[Encoding], array_buffer);
              }
              return utility.text_decoder_decode(this[Encoding], array_buffer);
            } finally {
              host.hostcall_metrics_stop_timer(WASM_METRIC_TEXT_DECODE_MICROSECONDS_TOTAL);
            }
          });
          this[Encoding] = encoding || UTF_8;
          if (utility.text_decoder_decode_without_replacement !== void 0 && options && options.fatal === true) {
            this[Fatal] = true;
          } else {
            this[Fatal] = false;
          }
        }
        get fatal() {
          return this[Fatal];
        }
      };
      function encode_value_to_string(value) {
        switch (typeof value) {
          case "undefined":
            return "";
          case "string":
            return value;
          default: {
            if (value === null) {
              return "null";
            }
            return value.toString();
          }
        }
      }
      globalThis.TextEncoder = class TextEncoder {
        constructor() {
          __publicField(this, "encode", function TextEncoder_encode(str) {
            try {
              host.hostcall_metrics_add(WASM_METRIC_TEXT_ENCODE_INVOCATION_TOTAL, 1);
              host.hostcall_metrics_start_timer(WASM_METRIC_TEXT_ENCODE_MICROSECONDS_TOTAL);
              const value = encode_value_to_string(str);
              if (typeof value !== "string") {
                return new Uint8Array(0);
              }
              return new Uint8Array(utility.text_encoder_encode(value));
            } finally {
              host.hostcall_metrics_stop_timer(WASM_METRIC_TEXT_ENCODE_MICROSECONDS_TOTAL);
            }
          });
          __publicField(this, "encodeInto", function TextEncoder_encodeInto(str, array) {
            try {
              host.hostcall_metrics_add(WASM_METRIC_TEXT_ENCODE_INVOCATION_TOTAL, 1);
              host.hostcall_metrics_start_timer(WASM_METRIC_TEXT_ENCODE_MICROSECONDS_TOTAL);
              if (!(array instanceof Uint8Array)) {
                throw new Error("TextEncoder.encodeInto requires an Uint8Array");
              }
              const value = encode_value_to_string(str);
              if (array.byteLength === 0 || typeof value !== "string") {
                return {
                  read: 0,
                  written: 0
                };
              }
              return utility.text_encoder_encode_into(value, array);
            } finally {
              host.hostcall_metrics_stop_timer(WASM_METRIC_TEXT_ENCODE_MICROSECONDS_TOTAL);
            }
          });
        }
        get encoding() {
          return UTF_8;
        }
      };
      let unhandled_rejection = null;
      let pending_fetches = /* @__PURE__ */ new Map();
      globalThis[PendingResponseChunks] = /* @__PURE__ */ new Map();
      let wait_until_used_counter = 0;
      let wait_until_finished_counter = 0;
      function expect_number_of_args(args, expected) {
        if (args.length !== expected) {
          throw new Error(`Expected ${expected} arguments, got ${args.length}`);
        }
      }
      function expect_min_number_of_args(args, expected) {
        if (args.length < expected) {
          throw new Error(`Expected at least ${expected} arguments, got ${args.length}`);
        }
      }
      function create_context() {
        globalThis[Origins] = new EdgioSet(ENV_VAR_NAMESPACE_EDGIO_ORIGINS);
        globalThis.pump = function global_pump(p) {
          return manage_main_loop(p, true);
        };
        let context = {
          systemVars: EdgioDict(ENV_VAR_NAMESPACE_EDGIO_CONFIG),
          environmentVars: EdgioDict(ENV_VAR_NAMESPACE_EDGIO_PROPENVVAR),
          origins: globalThis[Origins],
          requestVars: EdgioDict(ENV_VAR_NAMESPACE_EDGIO_USRVAR),
          geo: EdgioDict(ENV_VAR_NAMESPACE_EDGIO_GEO),
          device: EdgioDict(ENV_VAR_NAMESPACE_EDGIO_WURFL),
          client: EdgioDict(ENV_VAR_NAMESPACE_EDGIO_VIRT),
          httpVars: EdgioDict(ENV_VAR_NAMESPACE_EDGIO_HTTP),
          metrics: new EdgioMetrics(),
          respondWith: function create_context_responseWith() {
            throw new Error(
              "respondWith() has been replaced with `return <response>` from the edge function itself."
            );
          },
          waitUntil: function create_context_waitUntil(promise) {
            expect_number_of_args(arguments, 1);
            ++wait_until_used_counter;
            Promise.resolve(promise).finally(() => {
              ++wait_until_finished_counter;
            });
          }
        };
        context.initClear = function create_context_initClear() {
          host.hostcall_init_clear();
        };
        return context;
      }
      function parseCookie(cookie) {
        const parts = cookie.split("=");
        const key = parts[0].trim();
        const value = parts[1];
        return { key, value };
      }
      function processSetCookies(options, response) {
        let deduplicatedCookies = {};
        const existingCookies = options.headers.cookie;
        if (existingCookies) {
          const individualCookies = existingCookies.split(";");
          for (let i = 0; i < individualCookies.length; i++) {
            const { key, value } = parseCookie(individualCookies[i]);
            deduplicatedCookies[key] = value;
          }
        }
        let setCookies = response.headers.get("set-cookie") || [];
        if (!Array.isArray(setCookies)) {
          setCookies = [setCookies];
        }
        for (let i = 0; i < setCookies.length; i++) {
          const { key, value } = parseCookie(setCookies[i].split(";")[0]);
          deduplicatedCookies[key] = value;
        }
        const keys = Object.keys(deduplicatedCookies);
        if (keys.length > 0) {
          options.headers.cookie = "";
          for (let i = 0; i < keys.length; i++) {
            const key = keys[i];
            const value = deduplicatedCookies[key];
            options.headers.cookie += `${key}=${value}${i < keys.length - 1 ? "; " : ""}`;
          }
        }
      }
      async function handleRedirect(originalUrl, options, redirectedCount, response) {
        const location = response.headers.get("location");
        if ([301, 302, 303, 307, 308].indexOf(response.status) < 0 || !location) {
          response[Url] = originalUrl;
          response.redirected = redirectedCount > 0;
          return response;
        }
        const redirect = options.redirect;
        if (redirect === "error") {
          throw new Error("redirect");
        }
        if (redirect === "manual") {
          return response;
        }
        ++redirectedCount;
        processSetCookies(options, response);
        const newResponse = await issueFetch(location, options, redirectedCount);
        return newResponse;
      }
      globalThis[PromisifyAsyncHostcall] = (pendingPromiseQueue, edgioId) => {
        let resolve;
        let reject;
        const promise = new Promise((promise_resolve, promise_reject) => {
          resolve = promise_resolve;
          reject = promise_reject;
        });
        pendingPromiseQueue.set(edgioId, {
          promise,
          resolve,
          reject
        });
        if (debugLoggingEnabled) {
          let queue = "pending_fetches";
          let obj = "request_id";
          if (pendingPromiseQueue === globalThis[PendingResponseChunks]) {
            queue = "pending_response_body_chunks";
            obj = "response_id";
          }
          host.hostcall_debug(`PromisifyAsyncHostcall(${queue} ${obj}: ${edgioId}) returns ${promise}`);
        }
        return promise;
      };
      async function issueFetch(urlOrRequest, options, redirectedCount) {
        let req;
        if (urlOrRequest instanceof Request) {
          req = urlOrRequest;
          req.url = urlOrRequest.url;
        } else {
          if (typeof urlOrRequest !== "string") {
            if (typeof urlOrRequest.toString !== "function" || urlOrRequest.toString() === "[object Object]") {
              throw new Error(
                'Invalid "url" argument in fetch() function. The "url" argument must be a string, a Request object, or an object where toString() returns the url.'
              );
            }
            urlOrRequest = urlOrRequest.toString();
          }
          req = new Request(urlOrRequest, options);
        }
        if (!options.edgio || !options.edgio.origin) {
          throw new Error(`edgio.origin must be included in the fetch options for ${urlOrRequest}`);
        }
        await req[MoveBodyToHost]();
        const origin = options.edgio.origin;
        try {
          host.hostcall_req_set_fetch_origin(req.edgioId, origin);
        } catch {
          throw new Error(
            `Invalid edgio.origin: "${origin}". Must be one of: ${globalThis[Origins].keys().join(
              ", "
            )}`
          );
        }
        function getOptionInt(options2, field, msg) {
          const value = options2[field];
          if (value !== void 0) {
            const iValue = parseInt(value);
            if (isNaN(iValue)) {
              throw new Error(`Invalid '${field}' value '${value}' specified. ${msg}`);
            }
            return iValue;
          }
        }
        const timeout = getOptionInt(
          options.edgio,
          "timeout",
          "Expected timeout in milliseconds as an integer."
        );
        if (timeout !== void 0) {
          try {
            host.hostcall_req_set_fetch_timeout(req.edgioId, timeout);
          } catch {
            throw new Error(`Failed to set fetch timeout on request.`);
          }
        }
        const caching = options.edgio.caching;
        if (caching) {
          const bypass_cache = caching.bypass_cache;
          if (bypass_cache !== void 0) {
            host.hostcall_req_set_fetch_bypass_cache(req.edgioId, !!bypass_cache);
          }
          if (caching.cache_key_query_string) {
            const exclude_all = caching.cache_key_query_string.exclude_all;
            if (exclude_all !== void 0) {
              host.hostcall_req_set_fetch_ckqs_exclude_all(req.edgioId, !!exclude_all);
            }
            const include_all = caching.cache_key_query_string.include_all;
            if (include_all !== void 0) {
              host.hostcall_req_set_fetch_ckqs_include_all(req.edgioId, !!include_all);
            }
          }
          if (caching.max_age !== void 0) {
            host.hostcall_req_set_fetch_max_age(req.edgioId, caching.max_age.toString());
          }
          if (caching.tags !== void 0) {
            host.hostcall_req_set_fetch_cache_tags(req.edgioId, caching.tags.toString());
          }
          if (caching.stale_while_revalidate !== void 0) {
            host.hostcall_req_set_fetch_stale_while_revalidate(
              req.edgioId,
              caching.stale_while_revalidate.toString()
            );
          }
        }
        host.hostcall_req_fetch_async(req.edgioId);
        const promise = globalThis[PromisifyAsyncHostcall](pending_fetches, req.edgioId);
        const request_url = req.url;
        const response = await promise;
        return handleRedirect(request_url, options, redirectedCount, response);
      }
      globalThis.fetch = async function fetch(urlOrRequest, options) {
        expect_min_number_of_args(arguments, 1);
        options = options || {};
        if (!options.redirect) {
          options.redirect = "follow";
        }
        if (!options.headers) {
          options.headers = {};
        }
        if (!options.edgio) {
          options.edgio = {};
        }
        const validRedirects = ["error", "follow", "manual"];
        if (validRedirects.indexOf(options.redirect) < 0) {
          throw new Error(
            `redirect must be one of "${validRedirects.join(", ")}", not "${options.redirect}"`
          );
        }
        if (!options.edgio.origin) {
          throw new Error(
            `edgio.origin must be specified as a fetch option. Must be one of: ${globalThis[Origins].keys().join(",")}`
          );
        }
        return issueFetch(urlOrRequest, options, 0);
      };
      const getEdgeFunction = edgeFunctions.get("__edge_function_init_script__");
      if (getEdgeFunction) {
        const edgeInitFunction = getEdgeFunction();
        if (typeof edgeInitFunction !== "function") {
          throw new Error(
            'Edge Initialization Function specified by Router option "edge_function_init_script" must have a named export "handleHttpInit". See https://docs.edg.io/guides/v7/edge-functions#defining-edge-functions for more information.'
          );
        }
        const context = create_context();
        const init_promise = Promise.resolve(edgeInitFunction.bind(globalThis)(context));
        manage_main_loop(init_promise, true);
      }
      return function main(edgioRequestId) {
        const context = create_context();
        const path = context.systemVars["__EDGE_FUNCTION_PATH__"];
        const getEdgeFunction2 = edgeFunctions.get(path);
        if (!getEdgeFunction2) {
          throw new Error(`No edge function found for path: ${path}`);
        }
        const edgeFunction = getEdgeFunction2();
        if (typeof edgeFunction !== "function") {
          throw new Error(
            'Edge Function must have a named export "handleHttpRequest". See https://docs.edg.io/guides/v7/edge-functions#defining-edge-functions for more information.'
          );
        }
        const req = new Request(null, {
          edgio: {
            id: edgioRequestId
          }
        });
        req.originalUrl = req.url;
        let rewrittenUrl = new URL(req.url);
        rewrittenUrl.pathname = context.httpVars.get("path");
        req.url = rewrittenUrl.toString();
        const main_promise = Promise.resolve(edgeFunction.bind(globalThis)(req, context));
        manage_main_loop(main_promise, false);
      };
      function manage_main_loop(main_promise, is_init_function) {
        let waiting_on_main_promise = true;
        const logPrefix = `sdk.js(${is_init_function ? "handleHttpInit" : "handleHttpRequest"}): `;
        if (debugLoggingEnabled)
          host.hostcall_debug(`${logPrefix}start main loop`);
        main_promise.then(async function manage_main_loop_response(response) {
          if (is_init_function) {
            if (response !== void 0) {
              if (debugLoggingEnabled)
                host.hostcall_debug(`${logPrefix}return with non-undefined value, throwing exception`);
              throw new Error(
                `The handleHttpInit function must not return a value or a Promise (got ${typeof response})`
              );
            }
            if (debugLoggingEnabled)
              host.hostcall_debug(`${logPrefix}return with undefined (as expected)`);
          } else {
            if (!(response instanceof Response)) {
              if (debugLoggingEnabled)
                host.hostcall_debug(`${logPrefix}return with non-Response object, throwing exception`);
              throw new Error(
                `The handleHttpRequest function must return a Response or a Promise resolving to a Response (got ${typeof response})`
              );
            }
            if (debugLoggingEnabled)
              host.hostcall_debug(`${logPrefix}return with response object, sending it to client`);
            await response[SendToClient]();
          }
        }).catch(function manage_main_loop_catch(err) {
          if (debugLoggingEnabled)
            host.hostcall_debug(`${logPrefix}main_promise caught an exception: ${err}`);
          unhandled_rejection = err;
        }).finally(function manage_main_loop_finally() {
          if (debugLoggingEnabled)
            host.hostcall_debug(`${logPrefix}main_promise is settled`);
          waiting_on_main_promise = false;
        });
        function jobs_are_pending() {
          if (debugLoggingEnabled)
            host.hostcall_debug(
              `${logPrefix}jobs_are_pending ${waiting_on_main_promise}/${wait_until_used_counter - wait_until_finished_counter}/${globalThis[PendingResponseChunks].size}`
            );
          return waiting_on_main_promise || wait_until_finished_counter < wait_until_used_counter || globalThis[PendingResponseChunks].size > 0;
        }
        function resolve_pending_fetch(req_id, resp_id, error_code) {
          const pending_fetch = pending_fetches.get(req_id);
          if (!pending_fetch) {
            throw new Error(`${logPrefix}No pending fetch for ID ${req_id}`);
          }
          pending_fetches.delete(req_id);
          const { resolve, reject } = pending_fetch;
          if (resp_id) {
            if (debugLoggingEnabled)
              host.hostcall_debug(`${logPrefix}creating Response(${resp_id})`);
            const response = new Response(null, { edgio: { id: resp_id } });
            if (debugLoggingEnabled)
              host.hostcall_debug(`${logPrefix}resolving fetch(req_id:${req_id})`);
            resolve(response);
          } else {
            if (debugLoggingEnabled)
              host.hostcall_debug(`${logPrefix}creating ResponseError(${error_code})`);
            reject(new ResponseError(error_code));
          }
        }
        function resolve_pending_response_body(resp_id) {
          const pending_response = globalThis[PendingResponseChunks].get(resp_id);
          if (!pending_response) {
            throw new Error(`${logPrefix}No pending response for ID ${resp_id}`);
          }
          const { resolve, _reject } = pending_response;
          if (debugLoggingEnabled)
            host.hostcall_debug(`${logPrefix}resolving response_body(resp_id:${resp_id})`);
          resolve(resp_id);
        }
        while (jobs_are_pending()) {
          if (debugLoggingEnabled)
            host.hostcall_debug(`${logPrefix}Execute pending jobs starts.`);
          utility.execute_pending();
          if (debugLoggingEnabled)
            host.hostcall_debug(`${logPrefix}Execute pending jobs completed.`);
          if (debugLoggingEnabled)
            host.hostcall_debug(`${logPrefix}Checking for unhandled exceptions...`);
          if (unhandled_rejection) {
            host.hostcall_debug(`${logPrefix}Found unhandled exception: ${unhandled_rejection}`);
            const err = unhandled_rejection;
            unhandled_rejection = null;
            throw err;
          }
          if (pending_fetches.size + globalThis[PendingResponseChunks].size > 0) {
            if (debugLoggingEnabled)
              host.hostcall_debug(
                `${logPrefix}Waiting for ${pending_fetches.size} fetches. ${globalThis[PendingResponseChunks].size} response chunks`
              );
            const event = host.hostcall_event_await_next();
            if (debugLoggingEnabled)
              host.hostcall_debug(`${logPrefix}hostcall_event_await_next: event(${event})`);
            if (event == EVENT_IO_FETCH) {
              const [req_id, resp_id, error_code] = host.hostcall_event_get_fetch_id();
              if (debugLoggingEnabled)
                host.hostcall_debug(
                  `${logPrefix}hostcall_event_await_next: req_id(${req_id}), resp_id(${resp_id}), error_code(${error_code})`
                );
              resolve_pending_fetch(req_id, resp_id, error_code);
            } else if (event == EVENT_IO_RESPONSE_CHUNK) {
              let resp_id = host.hostcall_event_response_chunk_get_response_id();
              if (debugLoggingEnabled)
                host.hostcall_debug(
                  `${logPrefix}hostcall_event_response_chunk_get_response_id: resp_id(${resp_id})`
                );
              resolve_pending_response_body(resp_id);
            } else {
              if (debugLoggingEnabled)
                host.hostcall_debug(`${logPrefix}hostcall_await_next_event: Unknown event(${event})`);
            }
          }
        }
        if (debugLoggingEnabled)
          host.hostcall_debug(`${logPrefix}no more pending jobs`);
      }
    };
  }
});

// src/deploy/edge-functions/edgeFunctionsIndexCodeTemplate.js
var require_edgeFunctionsIndexCodeTemplate = __commonJS({
  "src/deploy/edge-functions/edgeFunctionsIndexCodeTemplate.js"(exports, module) {
    module.exports = (() => {
      const runtime_init = function runtime_init2(runtime, v1EdgioRequestId) {
        const sdk = require_sdk();
        const edgeFunctions = "__INSERT_EDGE_FUNCTIONS_MAP_HERE__";
        const run = sdk(runtime, edgeFunctions);
        if (typeof run !== "function") {
          throw new Error("The SDK was not initialized correctly.");
        }
        if (typeof runtime.version === "undefined") {
          if (typeof v1EdgioRequestId !== "number") {
            throw new Error("The runtime object is missing both the version and the request ID.");
          }
          run(v1EdgioRequestId);
          return;
        }
        return run;
      };
      runtime_init.version = 2;
      return runtime_init;
    })();
  }
});
export default require_edgeFunctionsIndexCodeTemplate();
