UNPKG

@graphql-mesh/hmac-upstream-signature

Version:
1,913 lines 56.9 kB
'use strict';

var executorCommon = require('@graphql-tools/executor-common');
var promiseHelpers = require('@whatwg-node/promise-helpers');

function getDefaultExportFromCjs (x) {
	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}

var jsonify = {};

var parse;
var hasRequiredParse;

function requireParse () {
	if (hasRequiredParse) return parse;
	hasRequiredParse = 1;

	var at; // The index of the current character
	var ch; // The current character
	var escapee = {
		'"': '"',
		'\\': '\\',
		'/': '/',
		b: '\b',
		f: '\f',
		n: '\n',
		r: '\r',
		t: '\t'
	};
	var text;

	// Call error when something is wrong.
	function error(m) {
		throw {
			name: 'SyntaxError',
			message: m,
			at: at,
			text: text
		};
	}

	function next(c) {
		// If a c parameter is provided, verify that it matches the current character.
		if (c && c !== ch) {
			error("Expected '" + c + "' instead of '" + ch + "'");
		}

		// Get the next character. When there are no more characters, return the empty string.

		ch = text.charAt(at);
		at += 1;
		return ch;
	}

	function number() {
		// Parse a number value.
		var num;
		var str = '';

		if (ch === '-') {
			str = '-';
			next('-');
		}
		while (ch >= '0' && ch <= '9') {
			str += ch;
			next();
		}
		if (ch === '.') {
			str += '.';
			while (next() && ch >= '0' && ch <= '9') {
				str += ch;
			}
		}
		if (ch === 'e' || ch === 'E') {
			str += ch;
			next();
			if (ch === '-' || ch === '+') {
				str += ch;
				next();
			}
			while (ch >= '0' && ch <= '9') {
				str += ch;
				next();
			}
		}
		num = Number(str);
		if (!isFinite(num)) {
			error('Bad number');
		}
		return num;
	}

	function string() {
		// Parse a string value.
		var hex;
		var i;
		var str = '';
		var uffff;

		// When parsing for string values, we must look for " and \ characters.
		if (ch === '"') {
			while (next()) {
				if (ch === '"') {
					next();
					return str;
				} else if (ch === '\\') {
					next();
					if (ch === 'u') {
						uffff = 0;
						for (i = 0; i < 4; i += 1) {
							hex = parseInt(next(), 16);
							if (!isFinite(hex)) {
								break;
							}
							uffff = (uffff * 16) + hex;
						}
						str += String.fromCharCode(uffff);
					} else if (typeof escapee[ch] === 'string') {
						str += escapee[ch];
					} else {
						break;
					}
				} else {
					str += ch;
				}
			}
		}
		error('Bad string');
	}

	// Skip whitespace.
	function white() {
		while (ch && ch <= ' ') {
			next();
		}
	}

	// true, false, or null.
	function word() {
		switch (ch) {
			case 't':
				next('t');
				next('r');
				next('u');
				next('e');
				return true;
			case 'f':
				next('f');
				next('a');
				next('l');
				next('s');
				next('e');
				return false;
			case 'n':
				next('n');
				next('u');
				next('l');
				next('l');
				return null;
			default:
				error("Unexpected '" + ch + "'");
		}
	}

	// Parse an array value.
	function array() {
		var arr = [];

		if (ch === '[') {
			next('[');
			white();
			if (ch === ']') {
				next(']');
				return arr; // empty array
			}
			while (ch) {
				arr.push(value()); // eslint-disable-line no-use-before-define
				white();
				if (ch === ']') {
					next(']');
					return arr;
				}
				next(',');
				white();
			}
		}
		error('Bad array');
	}

	// Parse an object value.
	function object() {
		var key;
		var obj = {};

		if (ch === '{') {
			next('{');
			white();
			if (ch === '}') {
				next('}');
				return obj; // empty object
			}
			while (ch) {
				key = string();
				white();
				next(':');
				if (Object.prototype.hasOwnProperty.call(obj, key)) {
					error('Duplicate key "' + key + '"');
				}
				obj[key] = value(); // eslint-disable-line no-use-before-define
				white();
				if (ch === '}') {
					next('}');
					return obj;
				}
				next(',');
				white();
			}
		}
		error('Bad object');
	}

	// Parse a JSON value. It could be an object, an array, a string, a number, or a word.
	function value() {
		white();
		switch (ch) {
			case '{':
				return object();
			case '[':
				return array();
			case '"':
				return string();
			case '-':
				return number();
			default:
				return ch >= '0' && ch <= '9' ? number() : word();
		}
	}

	// Return the json_parse function. It will have access to all of the above functions and variables.
	parse = function (source, reviver) {
		var result;

		text = source;
		at = 0;
		ch = ' ';
		result = value();
		white();
		if (ch) {
			error('Syntax error');
		}

		// If there is a reviver function, we recursively walk the new structure,
		// passing each name/value pair to the reviver function for possible
		// transformation, starting with a temporary root object that holds the result
		// in an empty key. If there is not a reviver function, we simply return the
		// result.

		return typeof reviver === 'function' ? (function walk(holder, key) {
			var k;
			var v;
			var val = holder[key];
			if (val && typeof val === 'object') {
				for (k in value) {
					if (Object.prototype.hasOwnProperty.call(val, k)) {
						v = walk(val, k);
						if (typeof v === 'undefined') {
							delete val[k];
						} else {
							val[k] = v;
						}
					}
				}
			}
			return reviver.call(holder, key, val);
		}({ '': result }, '')) : result;
	};
	return parse;
}

var stringify;
var hasRequiredStringify;

function requireStringify () {
	if (hasRequiredStringify) return stringify;
	hasRequiredStringify = 1;

	var escapable = /[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
	var gap;
	var indent;
	var meta = { // table of character substitutions
		'\b': '\\b',
		'\t': '\\t',
		'\n': '\\n',
		'\f': '\\f',
		'\r': '\\r',
		'"': '\\"',
		'\\': '\\\\'
	};
	var rep;

	function quote(string) {
		// If the string contains no control characters, no quote characters, and no
		// backslash characters, then we can safely slap some quotes around it.
		// Otherwise we must also replace the offending characters with safe escape sequences.

		escapable.lastIndex = 0;
		return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
			var c = meta[a];
			return typeof c === 'string' ? c
				: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
		}) + '"' : '"' + string + '"';
	}

	function str(key, holder) {
		// Produce a string from holder[key].
		var i; // The loop counter.
		var k; // The member key.
		var v; // The member value.
		var length;
		var mind = gap;
		var partial;
		var value = holder[key];

		// If the value has a toJSON method, call it to obtain a replacement value.
		if (value && typeof value === 'object' && typeof value.toJSON === 'function') {
			value = value.toJSON(key);
		}

		// If we were called with a replacer function, then call the replacer to obtain a replacement value.
		if (typeof rep === 'function') {
			value = rep.call(holder, key, value);
		}

		// What happens next depends on the value's type.
		switch (typeof value) {
			case 'string':
				return quote(value);

			case 'number':
				// JSON numbers must be finite. Encode non-finite numbers as null.
				return isFinite(value) ? String(value) : 'null';

			case 'boolean':
			case 'null':
				// If the value is a boolean or null, convert it to a string. Note:
				// typeof null does not produce 'null'. The case is included here in
				// the remote chance that this gets fixed someday.
				return String(value);

			case 'object':
				if (!value) {
					return 'null';
				}
				gap += indent;
				partial = [];

				// Array.isArray
				if (Object.prototype.toString.apply(value) === '[object Array]') {
					length = value.length;
					for (i = 0; i < length; i += 1) {
						partial[i] = str(i, value) || 'null';
					}

					// Join all of the elements together, separated with commas, and wrap them in brackets.
					v = partial.length === 0 ? '[]' : gap
						? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
						: '[' + partial.join(',') + ']';
					gap = mind;
					return v;
				}

				// If the replacer is an array, use it to select the members to be stringified.
				if (rep && typeof rep === 'object') {
					length = rep.length;
					for (i = 0; i < length; i += 1) {
						k = rep[i];
						if (typeof k === 'string') {
							v = str(k, value);
							if (v) {
								partial.push(quote(k) + (gap ? ': ' : ':') + v);
							}
						}
					}
				} else {
					// Otherwise, iterate through all of the keys in the object.
					for (k in value) {
						if (Object.prototype.hasOwnProperty.call(value, k)) {
							v = str(k, value);
							if (v) {
								partial.push(quote(k) + (gap ? ': ' : ':') + v);
							}
						}
					}
				}

				// Join all of the member texts together, separated with commas, and wrap them in braces.

				v = partial.length === 0 ? '{}' : gap
					? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
					: '{' + partial.join(',') + '}';
				gap = mind;
				return v;
		}
	}

	stringify = function (value, replacer, space) {
		var i;
		gap = '';
		indent = '';

		// If the space parameter is a number, make an indent string containing that many spaces.
		if (typeof space === 'number') {
			for (i = 0; i < space; i += 1) {
				indent += ' ';
			}
		} else if (typeof space === 'string') {
			// If the space parameter is a string, it will be used as the indent string.
			indent = space;
		}

		// If there is a replacer, it must be a function or an array. Otherwise, throw an error.
		rep = replacer;
		if (
			replacer
			&& typeof replacer !== 'function'
			&& (typeof replacer !== 'object' || typeof replacer.length !== 'number')
		) {
			throw new Error('JSON.stringify');
		}

		// Make a fake root object containing our value under the key of ''.
		// Return the result of stringifying the value.
		return str('', { '': value });
	};
	return stringify;
}

var hasRequiredJsonify;

function requireJsonify () {
	if (hasRequiredJsonify) return jsonify;
	hasRequiredJsonify = 1;

	jsonify.parse = requireParse();
	jsonify.stringify = requireStringify();
	return jsonify;
}

var toString = {}.toString;

var isarray = Array.isArray || function (arr) {
  return toString.call(arr) == '[object Array]';
};

var toStr$1 = Object.prototype.toString;

var isArguments = function isArguments(value) {
	var str = toStr$1.call(value);
	var isArgs = str === '[object Arguments]';
	if (!isArgs) {
		isArgs = str !== '[object Array]' &&
			value !== null &&
			typeof value === 'object' &&
			typeof value.length === 'number' &&
			value.length >= 0 &&
			toStr$1.call(value.callee) === '[object Function]';
	}
	return isArgs;
};

var implementation$2;
var hasRequiredImplementation;

function requireImplementation () {
	if (hasRequiredImplementation) return implementation$2;
	hasRequiredImplementation = 1;

	var keysShim;
	if (!Object.keys) {
		// modified from https://github.com/es-shims/es5-shim
		var has = Object.prototype.hasOwnProperty;
		var toStr = Object.prototype.toString;
		var isArgs = isArguments; // eslint-disable-line global-require
		var isEnumerable = Object.prototype.propertyIsEnumerable;
		var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
		var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
		var dontEnums = [
			'toString',
			'toLocaleString',
			'valueOf',
			'hasOwnProperty',
			'isPrototypeOf',
			'propertyIsEnumerable',
			'constructor'
		];
		var equalsConstructorPrototype = function (o) {
			var ctor = o.constructor;
			return ctor && ctor.prototype === o;
		};
		var excludedKeys = {
			$applicationCache: true,
			$console: true,
			$external: true,
			$frame: true,
			$frameElement: true,
			$frames: true,
			$innerHeight: true,
			$innerWidth: true,
			$onmozfullscreenchange: true,
			$onmozfullscreenerror: true,
			$outerHeight: true,
			$outerWidth: true,
			$pageXOffset: true,
			$pageYOffset: true,
			$parent: true,
			$scrollLeft: true,
			$scrollTop: true,
			$scrollX: true,
			$scrollY: true,
			$self: true,
			$webkitIndexedDB: true,
			$webkitStorageInfo: true,
			$window: true
		};
		var hasAutomationEqualityBug = (function () {
			/* global window */
			if (typeof window === 'undefined') { return false; }
			for (var k in window) {
				try {
					if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
						try {
							equalsConstructorPrototype(window[k]);
						} catch (e) {
							return true;
						}
					}
				} catch (e) {
					return true;
				}
			}
			return false;
		}());
		var equalsConstructorPrototypeIfNotBuggy = function (o) {
			/* global window */
			if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
				return equalsConstructorPrototype(o);
			}
			try {
				return equalsConstructorPrototype(o);
			} catch (e) {
				return false;
			}
		};

		keysShim = function keys(object) {
			var isObject = object !== null && typeof object === 'object';
			var isFunction = toStr.call(object) === '[object Function]';
			var isArguments = isArgs(object);
			var isString = isObject && toStr.call(object) === '[object String]';
			var theKeys = [];

			if (!isObject && !isFunction && !isArguments) {
				throw new TypeError('Object.keys called on a non-object');
			}

			var skipProto = hasProtoEnumBug && isFunction;
			if (isString && object.length > 0 && !has.call(object, 0)) {
				for (var i = 0; i < object.length; ++i) {
					theKeys.push(String(i));
				}
			}

			if (isArguments && object.length > 0) {
				for (var j = 0; j < object.length; ++j) {
					theKeys.push(String(j));
				}
			} else {
				for (var name in object) {
					if (!(skipProto && name === 'prototype') && has.call(object, name)) {
						theKeys.push(String(name));
					}
				}
			}

			if (hasDontEnumBug) {
				var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);

				for (var k = 0; k < dontEnums.length; ++k) {
					if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
						theKeys.push(dontEnums[k]);
					}
				}
			}
			return theKeys;
		};
	}
	implementation$2 = keysShim;
	return implementation$2;
}

var slice = Array.prototype.slice;
var isArgs = isArguments;

var origKeys = Object.keys;
var keysShim = origKeys ? function keys(o) { return origKeys(o); } : requireImplementation();

var originalKeys = Object.keys;

keysShim.shim = function shimObjectKeys() {
	if (Object.keys) {
		var keysWorksWithArguments = (function () {
			// Safari 5.0 bug
			var args = Object.keys(arguments);
			return args && args.length === arguments.length;
		}(1, 2));
		if (!keysWorksWithArguments) {
			Object.keys = function keys(object) { // eslint-disable-line func-name-matching
				if (isArgs(object)) {
					return originalKeys(slice.call(object));
				}
				return originalKeys(object);
			};
		}
	} else {
		Object.keys = keysShim;
	}
	return Object.keys || keysShim;
};

var objectKeys$1 = keysShim;

var callBind$1 = {exports: {}};

/** @type {import('.')} */
var esObjectAtoms = Object;

/** @type {import('.')} */
var esErrors = Error;

/** @type {import('./eval')} */
var _eval = EvalError;

/** @type {import('./range')} */
var range = RangeError;

/** @type {import('./ref')} */
var ref = ReferenceError;

/** @type {import('./syntax')} */
var syntax = SyntaxError;

/** @type {import('./type')} */
var type = TypeError;

/** @type {import('./uri')} */
var uri = URIError;

/** @type {import('./abs')} */
var abs$1 = Math.abs;

/** @type {import('./floor')} */
var floor$1 = Math.floor;

/** @type {import('./max')} */
var max$2 = Math.max;

/** @type {import('./min')} */
var min$1 = Math.min;

/** @type {import('./pow')} */
var pow$1 = Math.pow;

/** @type {import('./round')} */
var round$1 = Math.round;

/** @type {import('./isNaN')} */
var _isNaN = Number.isNaN || function isNaN(a) {
	return a !== a;
};

var $isNaN = _isNaN;

/** @type {import('./sign')} */
var sign$1 = function sign(number) {
	if ($isNaN(number) || number === 0) {
		return number;
	}
	return number < 0 ? -1 : 1;
};

/** @type {import('./gOPD')} */
var gOPD$1 = Object.getOwnPropertyDescriptor;

/** @type {import('.')} */
var $gOPD$1 = gOPD$1;

if ($gOPD$1) {
	try {
		$gOPD$1([], 'length');
	} catch (e) {
		// IE 8 has a broken gOPD
		$gOPD$1 = null;
	}
}

var gopd$1 = $gOPD$1;

/** @type {import('.')} */
var $defineProperty$3 = Object.defineProperty || false;
if ($defineProperty$3) {
	try {
		$defineProperty$3({}, 'a', { value: 1 });
	} catch (e) {
		// IE 8 has a broken defineProperty
		$defineProperty$3 = false;
	}
}

var esDefineProperty = $defineProperty$3;

var shams;
var hasRequiredShams;

function requireShams () {
	if (hasRequiredShams) return shams;
	hasRequiredShams = 1;

	/** @type {import('./shams')} */
	/* eslint complexity: [2, 18], max-statements: [2, 33] */
	shams = function hasSymbols() {
		if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
		if (typeof Symbol.iterator === 'symbol') { return true; }

		/** @type {{ [k in symbol]?: unknown }} */
		var obj = {};
		var sym = Symbol('test');
		var symObj = Object(sym);
		if (typeof sym === 'string') { return false; }

		if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
		if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }

		// temp disabled per https://github.com/ljharb/object.assign/issues/17
		// if (sym instanceof Symbol) { return false; }
		// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
		// if (!(symObj instanceof Symbol)) { return false; }

		// if (typeof Symbol.prototype.toString !== 'function') { return false; }
		// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }

		var symVal = 42;
		obj[sym] = symVal;
		for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
		if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }

		if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }

		var syms = Object.getOwnPropertySymbols(obj);
		if (syms.length !== 1 || syms[0] !== sym) { return false; }

		if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }

		if (typeof Object.getOwnPropertyDescriptor === 'function') {
			// eslint-disable-next-line no-extra-parens
			var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym));
			if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
		}

		return true;
	};
	return shams;
}

var hasSymbols$1;
var hasRequiredHasSymbols;

function requireHasSymbols () {
	if (hasRequiredHasSymbols) return hasSymbols$1;
	hasRequiredHasSymbols = 1;

	var origSymbol = typeof Symbol !== 'undefined' && Symbol;
	var hasSymbolSham = requireShams();

	/** @type {import('.')} */
	hasSymbols$1 = function hasNativeSymbols() {
		if (typeof origSymbol !== 'function') { return false; }
		if (typeof Symbol !== 'function') { return false; }
		if (typeof origSymbol('foo') !== 'symbol') { return false; }
		if (typeof Symbol('bar') !== 'symbol') { return false; }

		return hasSymbolSham();
	};
	return hasSymbols$1;
}

var Reflect_getPrototypeOf;
var hasRequiredReflect_getPrototypeOf;

function requireReflect_getPrototypeOf () {
	if (hasRequiredReflect_getPrototypeOf) return Reflect_getPrototypeOf;
	hasRequiredReflect_getPrototypeOf = 1;

	/** @type {import('./Reflect.getPrototypeOf')} */
	Reflect_getPrototypeOf = (typeof Reflect !== 'undefined' && Reflect.getPrototypeOf) || null;
	return Reflect_getPrototypeOf;
}

var Object_getPrototypeOf;
var hasRequiredObject_getPrototypeOf;

function requireObject_getPrototypeOf () {
	if (hasRequiredObject_getPrototypeOf) return Object_getPrototypeOf;
	hasRequiredObject_getPrototypeOf = 1;

	var $Object = esObjectAtoms;

	/** @type {import('./Object.getPrototypeOf')} */
	Object_getPrototypeOf = $Object.getPrototypeOf || null;
	return Object_getPrototypeOf;
}

/* eslint no-invalid-this: 1 */

var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max$1 = Math.max;
var funcType = '[object Function]';

var concatty = function concatty(a, b) {
    var arr = [];

    for (var i = 0; i < a.length; i += 1) {
        arr[i] = a[i];
    }
    for (var j = 0; j < b.length; j += 1) {
        arr[j + a.length] = b[j];
    }

    return arr;
};

var slicy = function slicy(arrLike, offset) {
    var arr = [];
    for (var i = offset, j = 0; i < arrLike.length; i += 1, j += 1) {
        arr[j] = arrLike[i];
    }
    return arr;
};

var joiny = function (arr, joiner) {
    var str = '';
    for (var i = 0; i < arr.length; i += 1) {
        str += arr[i];
        if (i + 1 < arr.length) {
            str += joiner;
        }
    }
    return str;
};

var implementation$1 = function bind(that) {
    var target = this;
    if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
        throw new TypeError(ERROR_MESSAGE + target);
    }
    var args = slicy(arguments, 1);

    var bound;
    var binder = function () {
        if (this instanceof bound) {
            var result = target.apply(
                this,
                concatty(args, arguments)
            );
            if (Object(result) === result) {
                return result;
            }
            return this;
        }
        return target.apply(
            that,
            concatty(args, arguments)
        );

    };

    var boundLength = max$1(0, target.length - args.length);
    var boundArgs = [];
    for (var i = 0; i < boundLength; i++) {
        boundArgs[i] = '$' + i;
    }

    bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);

    if (target.prototype) {
        var Empty = function Empty() {};
        Empty.prototype = target.prototype;
        bound.prototype = new Empty();
        Empty.prototype = null;
    }

    return bound;
};

var implementation = implementation$1;

var functionBind = Function.prototype.bind || implementation;

/** @type {import('./functionCall')} */
var functionCall = Function.prototype.call;

/** @type {import('./functionApply')} */
var functionApply = Function.prototype.apply;

/** @type {import('./reflectApply')} */
var reflectApply = typeof Reflect !== 'undefined' && Reflect && Reflect.apply;

var bind$3 = functionBind;

var $apply$2 = functionApply;
var $call$2 = functionCall;
var $reflectApply = reflectApply;

/** @type {import('./actualApply')} */
var actualApply$1 = $reflectApply || bind$3.call($call$2, $apply$2);

var bind$2 = functionBind;
var $TypeError$3 = type;

var $call$1 = functionCall;
var $actualApply = actualApply$1;

/** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */
var callBindApplyHelpers = function callBindBasic(args) {
	if (args.length < 1 || typeof args[0] !== 'function') {
		throw new $TypeError$3('a function is required');
	}
	return $actualApply(bind$2, $call$1, args);
};

var get;
var hasRequiredGet;

function requireGet () {
	if (hasRequiredGet) return get;
	hasRequiredGet = 1;

	var callBind = callBindApplyHelpers;
	var gOPD = gopd$1;

	var hasProtoAccessor;
	try {
		// eslint-disable-next-line no-extra-parens, no-proto
		hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype;
	} catch (e) {
		if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') {
			throw e;
		}
	}

	// eslint-disable-next-line no-extra-parens
	var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__'));

	var $Object = Object;
	var $getPrototypeOf = $Object.getPrototypeOf;

	/** @type {import('./get')} */
	get = desc && typeof desc.get === 'function'
		? callBind([desc.get])
		: typeof $getPrototypeOf === 'function'
			? /** @type {import('./get')} */ function getDunder(value) {
				// eslint-disable-next-line eqeqeq
				return $getPrototypeOf(value == null ? value : $Object(value));
			}
			: false;
	return get;
}

var getProto$1;
var hasRequiredGetProto;

function requireGetProto () {
	if (hasRequiredGetProto) return getProto$1;
	hasRequiredGetProto = 1;

	var reflectGetProto = requireReflect_getPrototypeOf();
	var originalGetProto = requireObject_getPrototypeOf();

	var getDunderProto = requireGet();

	/** @type {import('.')} */
	getProto$1 = reflectGetProto
		? function getProto(O) {
			// @ts-expect-error TS can't narrow inside a closure, for some reason
			return reflectGetProto(O);
		}
		: originalGetProto
			? function getProto(O) {
				if (!O || (typeof O !== 'object' && typeof O !== 'function')) {
					throw new TypeError('getProto: not an object');
				}
				// @ts-expect-error TS can't narrow inside a closure, for some reason
				return originalGetProto(O);
			}
			: getDunderProto
				? function getProto(O) {
					// @ts-expect-error TS can't narrow inside a closure, for some reason
					return getDunderProto(O);
				}
				: null;
	return getProto$1;
}

var asyncFunction;
var hasRequiredAsyncFunction;

function requireAsyncFunction () {
	if (hasRequiredAsyncFunction) return asyncFunction;
	hasRequiredAsyncFunction = 1;

	// eslint-disable-next-line no-extra-parens, no-empty-function
	const cached = /** @type {import('.').AsyncFunctionConstructor} */ (async function () {}.constructor);

	/** @type {import('.')} */
	asyncFunction = () => cached;
	return asyncFunction;
}

var generatorFunction;
var hasRequiredGeneratorFunction;

function requireGeneratorFunction () {
	if (hasRequiredGeneratorFunction) return generatorFunction;
	hasRequiredGeneratorFunction = 1;

	// eslint-disable-next-line no-extra-parens, no-empty-function
	const cached = /** @type {GeneratorFunctionConstructor} */ (function* () {}.constructor);

	/** @type {import('.')} */
	generatorFunction = () => cached;
	return generatorFunction;
}

var asyncGeneratorFunction;
var hasRequiredAsyncGeneratorFunction;

function requireAsyncGeneratorFunction () {
	if (hasRequiredAsyncGeneratorFunction) return asyncGeneratorFunction;
	hasRequiredAsyncGeneratorFunction = 1;

	// eslint-disable-next-line no-extra-parens, no-empty-function
	const cached = /** @type {import('.').AsyncGeneratorFunctionConstructor} */ (async function* () {}.constructor);

	/** @type {import('.')} */
	asyncGeneratorFunction = () => cached;
	return asyncGeneratorFunction;
}

var hasown;
var hasRequiredHasown;

function requireHasown () {
	if (hasRequiredHasown) return hasown;
	hasRequiredHasown = 1;

	var call = Function.prototype.call;
	var $hasOwn = Object.prototype.hasOwnProperty;
	var bind = functionBind;

	/** @type {import('.')} */
	hasown = bind.call(call, $hasOwn);
	return hasown;
}

var undefined$1;

var $Object = esObjectAtoms;

var $Error = esErrors;
var $EvalError = _eval;
var $RangeError = range;
var $ReferenceError = ref;
var $SyntaxError$1 = syntax;
var $TypeError$2 = type;
var $URIError = uri;

var abs = abs$1;
var floor = floor$1;
var max = max$2;
var min = min$1;
var pow = pow$1;
var round = round$1;
var sign = sign$1;

var $gOPD = gopd$1;
var $defineProperty$2 = esDefineProperty;

var throwTypeError = function () {
	throw new $TypeError$2();
};
var ThrowTypeError = $gOPD
	? (function () {
		try {
			// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
			arguments.callee; // IE 8 does not throw here
			return throwTypeError;
		} catch (calleeThrows) {
			try {
				// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
				return $gOPD(arguments, 'callee').get;
			} catch (gOPDthrows) {
				return throwTypeError;
			}
		}
	}())
	: throwTypeError;

var hasSymbols = requireHasSymbols()();

var getProto = requireGetProto();
var $ObjectGPO = requireObject_getPrototypeOf();
var $ReflectGPO = requireReflect_getPrototypeOf();

var $apply$1 = functionApply;
var $call = functionCall;

var needsEval = {};

var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined$1 : getProto(Uint8Array);

var INTRINSICS = {
	__proto__: null,
	'%AggregateError%': typeof AggregateError === 'undefined' ? undefined$1 : AggregateError,
	'%Array%': Array,
	'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer,
	'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined$1,
	'%AsyncFromSyncIteratorPrototype%': undefined$1,
	'%AsyncFunction%': needsEval,
	'%AsyncGenerator%': needsEval,
	'%AsyncGeneratorFunction%': needsEval,
	'%AsyncIteratorPrototype%': needsEval,
	'%Atomics%': typeof Atomics === 'undefined' ? undefined$1 : Atomics,
	'%BigInt%': typeof BigInt === 'undefined' ? undefined$1 : BigInt,
	'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined$1 : BigInt64Array,
	'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined$1 : BigUint64Array,
	'%Boolean%': Boolean,
	'%DataView%': typeof DataView === 'undefined' ? undefined$1 : DataView,
	'%Date%': Date,
	'%decodeURI%': decodeURI,
	'%decodeURIComponent%': decodeURIComponent,
	'%encodeURI%': encodeURI,
	'%encodeURIComponent%': encodeURIComponent,
	'%Error%': $Error,
	'%eval%': eval, // eslint-disable-line no-eval
	'%EvalError%': $EvalError,
	'%Float16Array%': typeof Float16Array === 'undefined' ? undefined$1 : Float16Array,
	'%Float32Array%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array,
	'%Float64Array%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array,
	'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined$1 : FinalizationRegistry,
	'%Function%': Function,
	'%GeneratorFunction%': needsEval,
	'%Int8Array%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array,
	'%Int16Array%': typeof Int16Array === 'undefined' ? undefined$1 : Int16Array,
	'%Int32Array%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array,
	'%isFinite%': isFinite,
	'%isNaN%': isNaN,
	'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined$1,
	'%JSON%': typeof JSON === 'object' ? JSON : undefined$1,
	'%Map%': typeof Map === 'undefined' ? undefined$1 : Map,
	'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined$1 : getProto(new Map()[Symbol.iterator]()),
	'%Math%': Math,
	'%Number%': Number,
	'%Object%': $Object,
	'%Object.getOwnPropertyDescriptor%': $gOPD,
	'%parseFloat%': parseFloat,
	'%parseInt%': parseInt,
	'%Promise%': typeof Promise === 'undefined' ? undefined$1 : Promise,
	'%Proxy%': typeof Proxy === 'undefined' ? undefined$1 : Proxy,
	'%RangeError%': $RangeError,
	'%ReferenceError%': $ReferenceError,
	'%Reflect%': typeof Reflect === 'undefined' ? undefined$1 : Reflect,
	'%RegExp%': RegExp,
	'%Set%': typeof Set === 'undefined' ? undefined$1 : Set,
	'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined$1 : getProto(new Set()[Symbol.iterator]()),
	'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer,
	'%String%': String,
	'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined$1,
	'%Symbol%': hasSymbols ? Symbol : undefined$1,
	'%SyntaxError%': $SyntaxError$1,
	'%ThrowTypeError%': ThrowTypeError,
	'%TypedArray%': TypedArray,
	'%TypeError%': $TypeError$2,
	'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array,
	'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray,
	'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array,
	'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array,
	'%URIError%': $URIError,
	'%WeakMap%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap,
	'%WeakRef%': typeof WeakRef === 'undefined' ? undefined$1 : WeakRef,
	'%WeakSet%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet,

	'%Function.prototype.call%': $call,
	'%Function.prototype.apply%': $apply$1,
	'%Object.defineProperty%': $defineProperty$2,
	'%Object.getPrototypeOf%': $ObjectGPO,
	'%Math.abs%': abs,
	'%Math.floor%': floor,
	'%Math.max%': max,
	'%Math.min%': min,
	'%Math.pow%': pow,
	'%Math.round%': round,
	'%Math.sign%': sign,
	'%Reflect.getPrototypeOf%': $ReflectGPO
};

if (getProto) {
	try {
		null.error; // eslint-disable-line no-unused-expressions
	} catch (e) {
		// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
		var errorProto = getProto(getProto(e));
		INTRINSICS['%Error.prototype%'] = errorProto;
	}
}

var getAsyncFunction = requireAsyncFunction();
var getGeneratorFunction = requireGeneratorFunction();
var getAsyncGeneratorFunction = requireAsyncGeneratorFunction();

var doEval = function doEval(name) {
	var value;
	if (name === '%AsyncFunction%') {
		value = getAsyncFunction() || void undefined$1;
	} else if (name === '%GeneratorFunction%') {
		value = getGeneratorFunction() || void undefined$1;
	} else if (name === '%AsyncGeneratorFunction%') {
		value = getAsyncGeneratorFunction() || void undefined$1;
	} else if (name === '%AsyncGenerator%') {
		var fn = doEval('%AsyncGeneratorFunction%');
		if (fn) {
			value = fn.prototype;
		}
	} else if (name === '%AsyncIteratorPrototype%') {
		var gen = doEval('%AsyncGenerator%');
		if (gen && getProto) {
			value = getProto(gen.prototype);
		}
	}

	INTRINSICS[name] = value;

	return value;
};

var LEGACY_ALIASES = {
	__proto__: null,
	'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
	'%ArrayPrototype%': ['Array', 'prototype'],
	'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
	'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
	'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
	'%ArrayProto_values%': ['Array', 'prototype', 'values'],
	'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
	'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
	'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
	'%BooleanPrototype%': ['Boolean', 'prototype'],
	'%DataViewPrototype%': ['DataView', 'prototype'],
	'%DatePrototype%': ['Date', 'prototype'],
	'%ErrorPrototype%': ['Error', 'prototype'],
	'%EvalErrorPrototype%': ['EvalError', 'prototype'],
	'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
	'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
	'%FunctionPrototype%': ['Function', 'prototype'],
	'%Generator%': ['GeneratorFunction', 'prototype'],
	'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
	'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
	'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
	'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
	'%JSONParse%': ['JSON', 'parse'],
	'%JSONStringify%': ['JSON', 'stringify'],
	'%MapPrototype%': ['Map', 'prototype'],
	'%NumberPrototype%': ['Number', 'prototype'],
	'%ObjectPrototype%': ['Object', 'prototype'],
	'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
	'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
	'%PromisePrototype%': ['Promise', 'prototype'],
	'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
	'%Promise_all%': ['Promise', 'all'],
	'%Promise_reject%': ['Promise', 'reject'],
	'%Promise_resolve%': ['Promise', 'resolve'],
	'%RangeErrorPrototype%': ['RangeError', 'prototype'],
	'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
	'%RegExpPrototype%': ['RegExp', 'prototype'],
	'%SetPrototype%': ['Set', 'prototype'],
	'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
	'%StringPrototype%': ['String', 'prototype'],
	'%SymbolPrototype%': ['Symbol', 'prototype'],
	'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
	'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
	'%TypeErrorPrototype%': ['TypeError', 'prototype'],
	'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
	'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
	'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
	'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
	'%URIErrorPrototype%': ['URIError', 'prototype'],
	'%WeakMapPrototype%': ['WeakMap', 'prototype'],
	'%WeakSetPrototype%': ['WeakSet', 'prototype']
};

var bind$1 = functionBind;
var hasOwn = requireHasown();
var $concat = bind$1.call($call, Array.prototype.concat);
var $spliceApply = bind$1.call($apply$1, Array.prototype.splice);
var $replace = bind$1.call($call, String.prototype.replace);
var $strSlice = bind$1.call($call, String.prototype.slice);
var $exec = bind$1.call($call, RegExp.prototype.exec);

/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
	var first = $strSlice(string, 0, 1);
	var last = $strSlice(string, -1);
	if (first === '%' && last !== '%') {
		throw new $SyntaxError$1('invalid intrinsic syntax, expected closing `%`');
	} else if (last === '%' && first !== '%') {
		throw new $SyntaxError$1('invalid intrinsic syntax, expected opening `%`');
	}
	var result = [];
	$replace(string, rePropName, function (match, number, quote, subString) {
		result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
	});
	return result;
};
/* end adaptation */

var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
	var intrinsicName = name;
	var alias;
	if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
		alias = LEGACY_ALIASES[intrinsicName];
		intrinsicName = '%' + alias[0] + '%';
	}

	if (hasOwn(INTRINSICS, intrinsicName)) {
		var value = INTRINSICS[intrinsicName];
		if (value === needsEval) {
			value = doEval(intrinsicName);
		}
		if (typeof value === 'undefined' && !allowMissing) {
			throw new $TypeError$2('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
		}

		return {
			alias: alias,
			name: intrinsicName,
			value: value
		};
	}

	throw new $SyntaxError$1('intrinsic ' + name + ' does not exist!');
};

var getIntrinsic = function GetIntrinsic(name, allowMissing) {
	if (typeof name !== 'string' || name.length === 0) {
		throw new $TypeError$2('intrinsic name must be a non-empty string');
	}
	if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
		throw new $TypeError$2('"allowMissing" argument must be a boolean');
	}

	if ($exec(/^%?[^%]*%?$/, name) === null) {
		throw new $SyntaxError$1('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
	}
	var parts = stringToPath(name);
	var intrinsicBaseName = parts.length > 0 ? parts[0] : '';

	var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
	var intrinsicRealName = intrinsic.name;
	var value = intrinsic.value;
	var skipFurtherCaching = false;

	var alias = intrinsic.alias;
	if (alias) {
		intrinsicBaseName = alias[0];
		$spliceApply(parts, $concat([0, 1], alias));
	}

	for (var i = 1, isOwn = true; i < parts.length; i += 1) {
		var part = parts[i];
		var first = $strSlice(part, 0, 1);
		var last = $strSlice(part, -1);
		if (
			(
				(first === '"' || first === "'" || first === '`')
				|| (last === '"' || last === "'" || last === '`')
			)
			&& first !== last
		) {
			throw new $SyntaxError$1('property names with quotes must have matching quotes');
		}
		if (part === 'constructor' || !isOwn) {
			skipFurtherCaching = true;
		}

		intrinsicBaseName += '.' + part;
		intrinsicRealName = '%' + intrinsicBaseName + '%';

		if (hasOwn(INTRINSICS, intrinsicRealName)) {
			value = INTRINSICS[intrinsicRealName];
		} else if (value != null) {
			if (!(part in value)) {
				if (!allowMissing) {
					throw new $TypeError$2('base intrinsic for ' + name + ' exists, but the property is not available.');
				}
				return void undefined$1;
			}
			if ($gOPD && (i + 1) >= parts.length) {
				var desc = $gOPD(value, part);
				isOwn = !!desc;

				// By convention, when a data property is converted to an accessor
				// property to emulate a data property that does not suffer from
				// the override mistake, that accessor's getter is marked with
				// an `originalValue` property. Here, when we detect this, we
				// uphold the illusion by pretending to see that original data
				// property, i.e., returning the value rather than the getter
				// itself.
				if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
					value = desc.get;
				} else {
					value = value[part];
				}
			} else {
				isOwn = hasOwn(value, part);
				value = value[part];
			}

			if (isOwn && !skipFurtherCaching) {
				INTRINSICS[intrinsicRealName] = value;
			}
		}
	}
	return value;
};

var $defineProperty$1 = esDefineProperty;

var $SyntaxError = syntax;
var $TypeError$1 = type;

var gopd = gopd$1;

/** @type {import('.')} */
var defineDataProperty = function defineDataProperty(
	obj,
	property,
	value
) {
	if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
		throw new $TypeError$1('`obj` must be an object or a function`');
	}
	if (typeof property !== 'string' && typeof property !== 'symbol') {
		throw new $TypeError$1('`property` must be a string or a symbol`');
	}
	if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) {
		throw new $TypeError$1('`nonEnumerable`, if provided, must be a boolean or null');
	}
	if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) {
		throw new $TypeError$1('`nonWritable`, if provided, must be a boolean or null');
	}
	if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) {
		throw new $TypeError$1('`nonConfigurable`, if provided, must be a boolean or null');
	}
	if (arguments.length > 6 && typeof arguments[6] !== 'boolean') {
		throw new $TypeError$1('`loose`, if provided, must be a boolean');
	}

	var nonEnumerable = arguments.length > 3 ? arguments[3] : null;
	var nonWritable = arguments.length > 4 ? arguments[4] : null;
	var nonConfigurable = arguments.length > 5 ? arguments[5] : null;
	var loose = arguments.length > 6 ? arguments[6] : false;

	/* @type {false | TypedPropertyDescriptor<unknown>} */
	var desc = !!gopd && gopd(obj, property);

	if ($defineProperty$1) {
		$defineProperty$1(obj, property, {
			configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable,
			enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable,
			value: value,
			writable: nonWritable === null && desc ? desc.writable : !nonWritable
		});
	} else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) {
		// must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable
		obj[property] = value; // eslint-disable-line no-param-reassign
	} else {
		throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.');
	}
};

var $defineProperty = esDefineProperty;

var hasPropertyDescriptors = function hasPropertyDescriptors() {
	return !!$defineProperty;
};

hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() {
	// node v0.6 has a bug where array lengths can be Set but not Defined
	if (!$defineProperty) {
		return null;
	}
	try {
		return $defineProperty([], 'length', { value: 1 }).length !== 1;
	} catch (e) {
		// In Firefox 4-22, defining length on an array throws an exception.
		return true;
	}
};

var hasPropertyDescriptors_1 = hasPropertyDescriptors;

var GetIntrinsic$1 = getIntrinsic;
var define = defineDataProperty;
var hasDescriptors = hasPropertyDescriptors_1();
var gOPD = gopd$1;

var $TypeError = type;
var $floor = GetIntrinsic$1('%Math.floor%');

/** @type {import('.')} */
var setFunctionLength = function setFunctionLength(fn, length) {
	if (typeof fn !== 'function') {
		throw new $TypeError('`fn` is not a function');
	}
	if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) {
		throw new $TypeError('`length` must be a positive 32-bit integer');
	}

	var loose = arguments.length > 2 && !!arguments[2];

	var functionLengthIsConfigurable = true;
	var functionLengthIsWritable = true;
	if ('length' in fn && gOPD) {
		var desc = gOPD(fn, 'length');
		if (desc && !desc.configurable) {
			functionLengthIsConfigurable = false;
		}
		if (desc && !desc.writable) {
			functionLengthIsWritable = false;
		}
	}

	if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) {
		if (hasDescriptors) {
			define(/** @type {Parameters<define>[0]} */ (fn), 'length', length, true, true);
		} else {
			define(/** @type {Parameters<define>[0]} */ (fn), 'length', length);
		}
	}
	return fn;
};

var bind = functionBind;
var $apply = functionApply;
var actualApply = actualApply$1;

/** @type {import('./applyBind')} */
var applyBind = function applyBind() {
	return actualApply(bind, $apply, arguments);
};

(function (module) {

	var setFunctionLength$1 = setFunctionLength;

	var $defineProperty = esDefineProperty;

	var callBindBasic = callBindApplyHelpers;
	var applyBind$1 = applyBind;

	module.exports = function callBind(originalFunction) {
		var func = callBindBasic(arguments);
		var adjustedLength = 1 + originalFunction.length - (arguments.length - 1);
		return setFunctionLength$1(
			func,
			adjustedLength > 0 ? adjustedLength : 0,
			true
		);
	};

	if ($defineProperty) {
		$defineProperty(module.exports, 'apply', { value: applyBind$1 });
	} else {
		module.exports.apply = applyBind$1;
	} 
} (callBind$1));

var callBindExports = callBind$1.exports;

var GetIntrinsic = getIntrinsic;

var callBindBasic = callBindApplyHelpers;

/** @type {(thisArg: string, searchString: string, position?: number) => number} */
var $indexOf$1 = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]);

/** @type {import('.')} */
var callBound$1 = function callBoundIntrinsic(name, allowMissing) {
	/* eslint no-extra-parens: 0 */

	var intrinsic = /** @type {(this: unknown, ...args: unknown[]) => unknown} */ (GetIntrinsic(name, !!allowMissing));
	if (typeof intrinsic === 'function' && $indexOf$1(name, '.prototype.') > -1) {
		return callBindBasic(/** @type {const} */ ([intrinsic]));
	}
	return intrinsic;
};

/** @type {typeof JSON.stringify} */
var jsonStringify = (typeof JSON !== 'undefined' ? JSON : requireJsonify()).stringify;

var isArray = isarray;
var objectKeys = objectKeys$1;
var callBind = callBindExports;
var callBound = callBound$1;

var $join = callBound('Array.prototype.join');
var $indexOf = callBound('Array.prototype.indexOf');
var $splice = callBound('Array.prototype.splice');
var $sort = callBound('Array.prototype.sort');

/** @type {(n: number, char: string) => string} */
var strRepeat = function repeat(n, char) {
	var str = '';
	for (var i = 0; i < n; i += 1) {
		str += char;
	}
	return str;
};

/** @type {(parent: import('.').Node, key: import('.').Key, value: unknown) => unknown} */
var defaultReplacer = function (_parent, _key, value) { return value; };

/** @type {import('.')} */
var jsonStableStringify$1 = function stableStringify(obj) {
	/** @type {Parameters<import('.')>[1]} */
	var opts = arguments.length > 1 ? arguments[1] : void undefined;
	var space = (opts && opts.space) || '';
	if (typeof space === 'number') { space = strRepeat(space, ' '); }
	var cycles = !!opts && typeof opts.cycles === 'boolean' && opts.cycles;
	/** @type {undefined | typeof defaultReplacer} */
	var replacer = opts && opts.replacer ? callBind(opts.replacer) : defaultReplacer;
	if (opts && typeof opts.collapseEmpty !== 'undefined' && typeof opts.collapseEmpty !== 'boolean') {
		throw new TypeError('`collapseEmpty` must be a boolean, if provided');
	}
	var collapseEmpty = !!opts && opts.collapseEmpty;

	var cmpOpt = typeof opts === 'function' ? opts : opts && opts.cmp;
	/** @type {undefined | (<T extends import('.').NonArrayNode>(node: T) => (a: Exclude<keyof T, symbol | number>, b: Exclude<keyof T, symbol | number>) => number)} */
	var cmp = cmpOpt && function (node) {
		// eslint-disable-next-line no-extra-parens
		var get = /** @type {NonNullable<typeof cmpOpt>} */ (cmpOpt).length > 2
			&& /** @type {import('.').Getter['get']} */ function get(k) { return node[k]; };
		return function (a, b) {
			// eslint-disable-next-line no-extra-parens
			return /** @type {NonNullable<typeof cmpOpt>} */ (cmpOpt)(
				{ key: a, value: node[a] },
				{ key: b, value: node[b] },
				// @ts-expect-error TS doesn't understand the optimization used here
				get ? /** @type {import('.').Getter} */ { __proto__: null, get: get } : void undefined
			);
		};
	};

	/** @type {import('.').Node[]} */
	var seen = [];
	return (/** @type {(parent: import('.').Node, key: string | number, node: unknown, level: number) => string | undefined} */
		function stringify(parent, key, node, level) {
			var indent = space ? '\n' + strRepeat(level, space) : '';
			var colonSeparator = space ? ': ' : ':';

			// eslint-disable-next-line no-extra-parens
			if (node && /** @type {{ toJSON?: unknown }} */ (node).toJSON && typeof /** @type {{ toJSON?: unknown }} */ (node).toJSON === 'function') {
				// eslint-disable-next-line no-extra-parens
				node = /** @type {{ toJSON: Function }} */ (node).toJSON();
			}

			node = replacer(parent, key, node);
			if (node === undefined) {
				return;
			}
			if (typeof node !== 'object' || node === null) {
				return jsonStringify(node);
			}

			/** @type {(out: string[], brackets: '[]' | '{}') => string} */
			var groupOutput = function (out, brackets) {
				return collapseEmpty && out.length === 0
					? brackets
					: (brackets === '[]' ? '[' : '{') + $join(out, ',') + indent + (brackets === '[]' ? ']' : '}');
			};

			if (isArray(node)) {
				var out = [];
				for (var i = 0; i < node.length; i++) {
					var item = stringify(node, i, node[i], level + 1) || jsonStringify(null);
					out[out.length] = indent + space + item;
				}
				return groupOutput(out, '[]');
			}

			if ($indexOf(seen, node) !== -1) {
				if (cycles) { return jsonStringify('__cycle__'); }
				throw new TypeError('Converting circular structure to JSON');
			} else {
				seen[seen.length] = /** @type {import('.').NonArrayNode} */ (node);
			}

			/** @type {import('.').Key[]} */
			// eslint-disable-next-line no-extra-parens
			var keys = $sort(objectKeys(node), cmp && cmp(/** @type {import('.').NonArrayNode} */ (node)));
			var out = [];
			for (var i = 0; i < keys.length; i++) {
				var key = keys[i];
				// eslint-disable-next-line no-extra-parens
				var value = stringify(/** @type {import('.').Node} */ (node), key, /** @type {import('.').NonArrayNode} */ (node)[key], level + 1);

				if (!value) { continue; }

				var keyValue = jsonStringify(key)
					+ colonSeparator
					+ value;

				out[out.length] = indent + space + keyValue;
			}
			$splice(seen, $indexOf(seen, node), 1);
			return groupOutput(out, '{}');
		}({ '': obj }, '', obj, 0)
	);
};

var jsonStableStringify = /*@__PURE__*/getDefaultExportFromCjs(jsonStableStringify$1);

const DEFAULT_EXTENSION_NAME = "hmac-signature";
const DEFAULT_SHOULD_SIGN_FN = () => true;
const defaultExecutionRequestSerializer = (executionRequest) => jsonStableStringify(
  executorCommon.serializeExecutionRequest({
    executionRequest: {
      document: executionRequest.document,
      variables: executionRequest.variables
    }
  })
);
const defaultParamsSerializer = (params) => jsonStableStringify({
  query: params.query,
  variables: params.variables != null && Object.keys(params.variables).length > 0 ? params.variables : void 0
});
function createCryptoKey({
  textEncoder,
  crypto,
  secret,
  usages
}) {
  return crypto.subtle.importKey(
    "raw",
    textEncoder.encode(secret),
    { name: "HMAC", hash: "SHA-256" },
    false,
    usages
  );
}
function useHmacUpstreamSignature(options) {
  if (!options.secret) {
    throw new Error(
      'Property "secret" is required for useHmacUpstreamSignature plugin'
    );
  }
  const shouldSign = options.shouldSign || DEFAULT_SHOULD_SIGN_FN;
  const extensionName = options.extensionName || DEFAULT_EXTENSION_NAME;
  const serializeExecutionRequest2 = options.serializeExecutionRequest || defaultExecutionRequestSerializer;
  let key$;
  let fetchAPI;
  let textEncoder;
  return {
    onYogaInit({ yoga }) {
      fetchAPI = yoga.fetchAPI;
    },
    onSubgraphExecute({
      subgraphName,
      subgraph,
      executionRequest,
      log: rootLog
    }) {
      const log = rootLog.child("[useHmacUpstreamSignature] ");
      log.debug(`Running shouldSign for subgraph ${subgraphName}`);
      if (shouldSign({ subgraphName, subgraph, executionRequest })) {
        log.debug(
          `shouldSign is true for subgraph ${subgraphName}, signing request`
        );
        textEncoder ||= new fetchAPI.TextEncoder();
        return promiseHelpers.handleMaybePromise(
          () => key$ ||= createCryptoKey({
            textEncoder,
            crypto: fetchAPI.crypto,
            secret: options.secret,
            usages: ["sign"]
          }),
          (key) => {
            key$ = key;
            const serializedExecutionRequest = serializeExecutionRequest2(executionRequest);
            const encodedContent = textEncoder.encode(
              serializedExecutionRequest
            );
            return promiseHelpers.handleMaybePromise(
              () => fetchAPI.crypto.subtle.sign("HMAC", key, encodedContent),
              (signature) => {
                const extensionValue = fetchAPI.btoa(
                  String.fromCharCode(...new Uint8Array(signature))
                );
                log.debug(
                  {
                    signature: extensionValue,
                    payload: serializedExecutionRequest
                  },
                  `Produced hmac signature for subgraph ${subgraphName}`
                );
                if (!executionRequest.extensions) {
                  executionRequest.extensions = {};
                }
                executionRequest.extensions[extensionName] = extensionValue;
              }
            );
          }
        );
      } else {
        log.debug(
          `shouldSign is false for subgraph ${subgraphName}, skipping hmac signature`
        );
      }
    }
  };
}
function useHmacSignatureValidation(options) {
  if (!options.secret) {
    throw new Error(
      'Property "secret" is required for useHmacSignatureValidation plugin'
    );
  }
  const extensionName = options.extensionName || DEFAULT_EXTENSION_NAME;
  let key$;
  let textEncoder;
  const paramsSerializer = options.serializeParams || defaultParamsSerializer;
  let logger;
  return {
    onYogaInit({ yoga }) {
      logger = yoga.logger;
    },
    onParams({ params, fetchAPI }) {
      textEncoder ||= new fetchAPI.TextEncoder();
      const extension = params.extensions?.[extensionName];
      if (!extension) {
        throw new Error(
          `Missing HMAC signature: extension ${extensionName} not found in request.`
        );
      }
      return promiseHelpers.handleMaybePromise(
        () => key$ ||= createCryptoKey({
          textEncoder,
          crypto: fetchAPI.crypto,
          secret: options.secret,
          usages: ["verify"]
        }),
        (key) => {
          key$ = key;
          const sigBuf = Uint8Array.from(
            atob(extension),
            (c) => c.charCodeAt(0)
          );
          const serializedParams = paramsSerializer(params);
          logger.debug(
            "[useHmacSignatureValidation] HMAC signature will be calculate based on serialized params",
            { serializedParams }
          );
          return promiseHelpers.handleMaybePromise(
            () => fetchAPI.crypto.subtle.verify(
              "HMAC",
              key,
              sigBuf,
              textEncoder.encode(serializedParams)
            ),
            (result) => {
              if (!result) {
                logger.error(
                  "[useHmacSignatureValidation] HMAC signature does not match the body content. short circuit request."
                );
                throw new Error(
                  `Invalid HMAC signature: extension ${extensionName} does not match the body content.`
                );
              }
            }
          );
        }
      );
    }
  };
}

exports.defaultExecutionRequestSerializer = defaultExecutionRequestSerializer;
exports.defaultParamsSerializer = defaultParamsSerializer;
exports.useHmacSignatureValidation = useHmacSignatureValidation;
exports.useHmacUpstreamSignature = useHmacUpstreamSignature;